From b001ef50aa648673946ea66929a55d0444d32ee0 Mon Sep 17 00:00:00 2001 From: Yonah Date: Wed, 17 Sep 2025 06:40:31 +0900 Subject: [PATCH] generic: pad for different lengths This can be autodetected based on existing string. Signed-off-by: Yonah --- generic.go | 4 +++- generic_test.go | 8 ++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/generic.go b/generic.go index 8d6f441..6a925df 100644 --- a/generic.go +++ b/generic.go @@ -11,8 +11,10 @@ type StringInt int func (i *StringInt) MarshalJSON() ([]byte, error) { s := strconv.Itoa(int(*i)) - if len(s) < 4 { + if len(s) <= 4 { s = strings.Repeat("0", 4-len(s)) + s + } else if len(s) < 6 { + s = strings.Repeat("0", 6-len(s)) + s } return json.Marshal(s) } diff --git a/generic_test.go b/generic_test.go index 9c7793b..bc053cf 100644 --- a/generic_test.go +++ b/generic_test.go @@ -18,8 +18,12 @@ func TestStringInt(t *testing.T) { data string val int }{ - {"valid", nil, `"3735928559"`, 0xdeadbeef}, - {"valid pad", nil, `"0009"`, 9}, + {"valid long", nil, `"3735928559"`, 0xdeadbeef}, + {"valid pad 4", nil, `"0000"`, 0}, + {"valid 4", nil, `"1000"`, 1e3}, + {"valid pad 6", nil, `"010000"`, 1e4}, + {"valid 6", nil, `"100000"`, 1e5}, + {"invalid json", newSyntaxError("unexpected end of JSON input", 11), `"3735928559`, -1}, {"invalid number", &strconv.NumError{Func: "Atoi", Num: ":3735928559", Err: strconv.ErrSyntax}, `":3735928559"`, -1}, }