generic: pad string representation

This replicates api behaviour.

Signed-off-by: Yonah <contrib@gensokyo.uk>
This commit is contained in:
Yonah 2025-09-17 06:01:00 +09:00
parent 5b9d1e4fe8
commit cc45f04800
Signed by: yonah
SSH Key Fingerprint: SHA256:vnQvK8+XXH9Tbni2AV1a/8qdVK/zPcXw52GM0ruQvwA
2 changed files with 10 additions and 1 deletions

View File

@ -3,12 +3,20 @@ package monstersirenfetch
import ( import (
"encoding/json" "encoding/json"
"strconv" "strconv"
"strings"
) )
// StringInt is a JSON string representing an integer. // StringInt is a JSON string representing an integer.
type StringInt int 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) { func (i *StringInt) UnmarshalJSON(data []byte) (err error) {
var v string var v string
err = json.Unmarshal(data, &v) err = json.Unmarshal(data, &v)

View File

@ -18,6 +18,7 @@ func TestStringInt(t *testing.T) {
val int val int
}{ }{
{"valid", nil, `"3735928559"`, 0xdeadbeef}, {"valid", nil, `"3735928559"`, 0xdeadbeef},
{"valid pad", nil, `"0009"`, 9},
{"invalid json", newSyntaxError("unexpected end of JSON input", 11), `"3735928559`, -1}, {"invalid json", newSyntaxError("unexpected end of JSON input", 11), `"3735928559`, -1},
{"invalid number", &strconv.NumError{Func: "Atoi", Num: ":3735928559", Err: strconv.ErrSyntax}, `":3735928559"`, -1}, {"invalid number", &strconv.NumError{Func: "Atoi", Num: ":3735928559", Err: strconv.ErrSyntax}, `":3735928559"`, -1},
} }