From e727e7adb694fdcf11a63f5a7789f7814eab3b55 Mon Sep 17 00:00:00 2001 From: James Shubin Date: Mon, 27 Nov 2023 20:30:49 -0500 Subject: [PATCH] lang: funcs: core: net: Add more mac fmt functions --- lang/funcs/core/net/macfmt_func.go | 23 +++++++++++++++++++ lang/funcs/core/net/macfmt_func_test.go | 30 +++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/lang/funcs/core/net/macfmt_func.go b/lang/funcs/core/net/macfmt_func.go index bec50f1b..3fc9b585 100644 --- a/lang/funcs/core/net/macfmt_func.go +++ b/lang/funcs/core/net/macfmt_func.go @@ -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 +} diff --git a/lang/funcs/core/net/macfmt_func_test.go b/lang/funcs/core/net/macfmt_func_test.go index eff84249..400d96ee 100644 --- a/lang/funcs/core/net/macfmt_func_test.go +++ b/lang/funcs/core/net/macfmt_func_test.go @@ -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) + } + } + }) + } +}