github.com/jaypipes/ghw@v0.21.1/pkg/pci/address/address.go (about)

     1  //
     2  // Use and distribution licensed under the Apache license version 2.
     3  //
     4  // See the COPYING file in the root project directory for full text.
     5  //
     6  
     7  package address
     8  
     9  import (
    10  	"regexp"
    11  	"strings"
    12  )
    13  
    14  var (
    15  	regexAddress *regexp.Regexp = regexp.MustCompile(
    16  		`^((1?[0-9a-f]{0,4}):)?([0-9a-f]{2}):([0-9a-f]{2})\.([0-9a-f]{1})$`,
    17  	)
    18  )
    19  
    20  // Address contains the components of a PCI Address
    21  type Address struct {
    22  	Domain   string
    23  	Bus      string
    24  	Device   string
    25  	Function string
    26  }
    27  
    28  // String() returns the canonical [D]BDF representation of this Address
    29  func (addr *Address) String() string {
    30  	return addr.Domain + ":" + addr.Bus + ":" + addr.Device + "." + addr.Function
    31  }
    32  
    33  // FromString returns [Address] from an address string in either
    34  // $BUS:$DEVICE.$FUNCTION (BDF) format or a full PCI address that
    35  // includes the domain: $DOMAIN:$BUS:$DEVICE.$FUNCTION.
    36  //
    37  // If the address string isn't a valid PCI address, then nil is returned.
    38  func FromString(address string) *Address {
    39  	addrLowered := strings.ToLower(address)
    40  	matches := regexAddress.FindStringSubmatch(addrLowered)
    41  	if len(matches) == 6 {
    42  		dom := "0000"
    43  		if matches[1] != "" {
    44  			dom = matches[2]
    45  		}
    46  		return &Address{
    47  			Domain:   dom,
    48  			Bus:      matches[3],
    49  			Device:   matches[4],
    50  			Function: matches[5],
    51  		}
    52  	}
    53  	return nil
    54  }