Path: blob/main/vendor/github.com/google/uuid/node.go
2875 views
// Copyright 2016 Google Inc. All rights reserved.1// Use of this source code is governed by a BSD-style2// license that can be found in the LICENSE file.34package uuid56import (7"sync"8)910var (11nodeMu sync.Mutex12ifname string // name of interface being used13nodeID [6]byte // hardware for version 1 UUIDs14zeroID [6]byte // nodeID with only 0's15)1617// NodeInterface returns the name of the interface from which the NodeID was18// derived. The interface "user" is returned if the NodeID was set by19// SetNodeID.20func NodeInterface() string {21defer nodeMu.Unlock()22nodeMu.Lock()23return ifname24}2526// SetNodeInterface selects the hardware address to be used for Version 1 UUIDs.27// If name is "" then the first usable interface found will be used or a random28// Node ID will be generated. If a named interface cannot be found then false29// is returned.30//31// SetNodeInterface never fails when name is "".32func SetNodeInterface(name string) bool {33defer nodeMu.Unlock()34nodeMu.Lock()35return setNodeInterface(name)36}3738func setNodeInterface(name string) bool {39iname, addr := getHardwareInterface(name) // null implementation for js40if iname != "" && addr != nil {41ifname = iname42copy(nodeID[:], addr)43return true44}4546// We found no interfaces with a valid hardware address. If name47// does not specify a specific interface generate a random Node ID48// (section 4.1.6)49if name == "" {50ifname = "random"51randomBits(nodeID[:])52return true53}54return false55}5657// NodeID returns a slice of a copy of the current Node ID, setting the Node ID58// if not already set.59func NodeID() []byte {60defer nodeMu.Unlock()61nodeMu.Lock()62if nodeID == zeroID {63setNodeInterface("")64}65nid := nodeID66return nid[:]67}6869// SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes70// of id are used. If id is less than 6 bytes then false is returned and the71// Node ID is not set.72func SetNodeID(id []byte) bool {73if len(id) < 6 {74return false75}76defer nodeMu.Unlock()77nodeMu.Lock()78copy(nodeID[:], id)79ifname = "user"80return true81}8283// NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is84// not valid. The NodeID is only well defined for version 1 and 2 UUIDs.85func (uuid UUID) NodeID() []byte {86var node [6]byte87copy(node[:], uuid[10:])88return node[:]89}909192