address.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. package address
  7. import (
  8. "regexp"
  9. "strings"
  10. )
  11. var (
  12. regexAddress *regexp.Regexp = regexp.MustCompile(
  13. `^(([0-9a-f]{0,4}):)?([0-9a-f]{2}):([0-9a-f]{2})\.([0-9a-f]{1})$`,
  14. )
  15. )
  16. // Address contains the components of a PCI Address
  17. type Address struct {
  18. Domain string
  19. Bus string
  20. Device string
  21. Function string
  22. }
  23. // String() returns the canonical [D]BDF representation of this Address
  24. func (addr *Address) String() string {
  25. return addr.Domain + ":" + addr.Bus + ":" + addr.Device + "." + addr.Function
  26. }
  27. // FromString returns an Address struct from an ddress string in either
  28. // $BUS:$DEVICE.$FUNCTION (BDF) format or it can be a full PCI address that
  29. // includes the 4-digit $DOMAIN information as well:
  30. // $DOMAIN:$BUS:$DEVICE.$FUNCTION.
  31. //
  32. // Returns "" if the address string wasn't a valid PCI address.
  33. func FromString(address string) *Address {
  34. addrLowered := strings.ToLower(address)
  35. matches := regexAddress.FindStringSubmatch(addrLowered)
  36. if len(matches) == 6 {
  37. dom := "0000"
  38. if matches[1] != "" {
  39. dom = matches[2]
  40. }
  41. return &Address{
  42. Domain: dom,
  43. Bus: matches[3],
  44. Device: matches[4],
  45. Function: matches[5],
  46. }
  47. }
  48. return nil
  49. }