From cc45f04800013f0d4b23f147074310e31a6b53b4 Mon Sep 17 00:00:00 2001 From: Yonah Date: Wed, 17 Sep 2025 06:01:00 +0900 Subject: [PATCH] generic: pad string representation This replicates api behaviour. Signed-off-by: Yonah --- generic.go | 10 +++++++++- generic_test.go | 1 + 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/generic.go b/generic.go index 7c977b9..8d6f441 100644 --- a/generic.go +++ b/generic.go @@ -3,12 +3,20 @@ package monstersirenfetch import ( "encoding/json" "strconv" + "strings" ) // StringInt is a JSON string representing an integer. type StringInt int -func (i *StringInt) MarshalJSON() ([]byte, error) { return json.Marshal(strconv.Itoa(int(*i))) } +func (i *StringInt) MarshalJSON() ([]byte, error) { + s := strconv.Itoa(int(*i)) + if len(s) < 4 { + s = strings.Repeat("0", 4-len(s)) + s + } + return json.Marshal(s) +} + func (i *StringInt) UnmarshalJSON(data []byte) (err error) { var v string err = json.Unmarshal(data, &v) diff --git a/generic_test.go b/generic_test.go index 84d4485..1d7f04c 100644 --- a/generic_test.go +++ b/generic_test.go @@ -18,6 +18,7 @@ func TestStringInt(t *testing.T) { val int }{ {"valid", nil, `"3735928559"`, 0xdeadbeef}, + {"valid pad", nil, `"0009"`, 9}, {"invalid json", newSyntaxError("unexpected end of JSON input", 11), `"3735928559`, -1}, {"invalid number", &strconv.NumError{Func: "Atoi", Num: ":3735928559", Err: strconv.ErrSyntax}, `":3735928559"`, -1}, }