generic: pad for different lengths

This can be autodetected based on existing string.

Signed-off-by: Yonah <contrib@gensokyo.uk>
This commit is contained in:
Yonah 2025-09-17 06:40:31 +09:00
parent 2f34599823
commit b001ef50aa
Signed by: yonah
SSH Key Fingerprint: SHA256:vnQvK8+XXH9Tbni2AV1a/8qdVK/zPcXw52GM0ruQvwA
2 changed files with 9 additions and 3 deletions

View File

@ -11,8 +11,10 @@ type StringInt int
func (i *StringInt) MarshalJSON() ([]byte, error) { func (i *StringInt) MarshalJSON() ([]byte, error) {
s := strconv.Itoa(int(*i)) s := strconv.Itoa(int(*i))
if len(s) < 4 { if len(s) <= 4 {
s = strings.Repeat("0", 4-len(s)) + s 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) return json.Marshal(s)
} }

View File

@ -18,8 +18,12 @@ func TestStringInt(t *testing.T) {
data string data string
val int val int
}{ }{
{"valid", nil, `"3735928559"`, 0xdeadbeef}, {"valid long", nil, `"3735928559"`, 0xdeadbeef},
{"valid pad", nil, `"0009"`, 9}, {"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 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},
} }