github.com/geofffranks/garden-linux@v0.0.0-20160715111146-26c893169cfa/network/bridgemgr/bridge_name_generator.go (about)

     1  package bridgemgr
     2  
     3  import (
     4  	"strconv"
     5  	"time"
     6  )
     7  
     8  type BridgeNameGenerator interface {
     9  	Generate() string
    10  }
    11  
    12  type bridgeNameGenerator struct {
    13  	prefix      string
    14  	bridgeNames chan string
    15  }
    16  
    17  func NewBridgeNameGenerator(prefix string) *bridgeNameGenerator {
    18  	nameChan := make(chan string)
    19  	randPartLen := uint(15 - len(prefix))
    20  
    21  	go func(bridgeNames chan<- string) {
    22  		for bridgeNum := time.Now().UnixNano(); ; bridgeNum++ {
    23  			bridgeName := []byte{}
    24  
    25  			var i uint
    26  			for i = 0; i < randPartLen; i++ {
    27  				bridgeName = strconv.AppendInt(
    28  					bridgeName,
    29  					(bridgeNum>>(55-(i+1)*5))&31,
    30  					32,
    31  				)
    32  			}
    33  
    34  			bridgeNames <- string(bridgeName)
    35  		}
    36  	}(nameChan)
    37  
    38  	return &bridgeNameGenerator{
    39  		prefix:      prefix,
    40  		bridgeNames: nameChan,
    41  	}
    42  }
    43  
    44  func (generator *bridgeNameGenerator) Generate() string {
    45  	return generator.prefix + <-generator.bridgeNames
    46  }