lang: funcs: core: net: Add more mac fmt functions

This commit is contained in:
James Shubin
2023-11-27 20:30:49 -05:00
parent af1c952700
commit e727e7adb6
2 changed files with 53 additions and 0 deletions

View File

@@ -31,6 +31,10 @@ func init() {
T: types.NewType("func(a str) str"),
V: MacFmt,
})
simple.ModuleRegister(ModuleName, "oldmacfmt", &types.FuncValue{
T: types.NewType("func(a str) str"),
V: OldMacFmt,
})
}
// MacFmt takes a MAC address with hyphens and converts it to a format with
@@ -51,3 +55,22 @@ func MacFmt(input []types.Value) (types.Value, error) {
V: strings.Replace(mac, "-", ":", -1),
}, nil
}
// OldMacFmt takes a MAC address with colons and converts it to a format with
// hyphens. This is the old deprecated style that nobody likes.
func OldMacFmt(input []types.Value) (types.Value, error) {
mac := input[0].Str()
// Check if the MAC address is valid.
if len(mac) != len("00:00:00:00:00:00") {
return nil, fmt.Errorf("invalid MAC address length: %s", mac)
}
_, err := net.ParseMAC(mac)
if err != nil {
return nil, err
}
return &types.StrValue{
V: strings.Replace(mac, ":", "-", -1),
}, nil
}

View File

@@ -52,3 +52,33 @@ func TestMacFmt(t *testing.T) {
})
}
}
func TestOldMacFmt(t *testing.T) {
var tests = []struct {
name string
in string
out string
wantErr bool
}{
{"Valid mac with hyphens", "01:23:45:67:89:AB", "01-23-45-67-89-AB", false},
{"Valid mac with colons", "01-23-45-67-89-AB", "01-23-45-67-89-AB", false},
{"Incorrect mac length with hyphens", "01-23-45-67-89-AB-01-23-45-67-89-AB", "01-23-45-67-89-AB-01-23-45-67-89-AB", true},
{"Invalid mac", "", "", true},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
m, err := OldMacFmt([]types.Value{&types.StrValue{V: tt.in}})
if (err != nil) != tt.wantErr {
t.Errorf("func MacFmt() error = %v, wantErr %v", err, tt.wantErr)
return
}
if m != nil {
if err := m.Cmp(&types.StrValue{V: tt.out}); err != nil {
t.Errorf("got %q, want %q", m.Value(), tt.out)
}
}
})
}
}