Files
gists/projects/go-tools/go/goipgrep/internal/normalize/mac.go

44 lines
854 B
Go

package normalize
import (
"strings"
)
// NormalizeMAC converts supported MAC forms to canonical lower-case colon-separated form.
// Accepts: xx:xx:xx:xx:xx:xx, xx-xx-xx-xx-xx-xx, xxxx.xxxx.xxxx
func NormalizeMAC(s string) (string, bool) {
s = strings.TrimSpace(s)
if s == "" {
return "", false
}
s = strings.ToLower(s)
// remove common separators
s = strings.ReplaceAll(s, ":", "")
s = strings.ReplaceAll(s, "-", "")
s = strings.ReplaceAll(s, ".", "")
if len(s) != 12 {
return "", false
}
for i := 0; i < 12; i++ {
c := s[i]
if (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') {
continue
}
return "", false
}
// canonical form aa:bb:cc:dd:ee:ff
var b strings.Builder
b.Grow(17)
for i := 0; i < 12; i += 2 {
if i > 0 {
b.WriteByte(':')
}
b.WriteByte(s[i])
b.WriteByte(s[i+1])
}
return b.String(), true
}