Skip to content

Commit efa236f

Browse files
authored
bigint unmarshaller to support numbers or numbered strings (#100)
1 parent 32dc838 commit efa236f

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

bigintHelpers.go.tmpl

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,29 @@ func (b BigInt) MarshalText() ([]byte, error) {
2424

2525
// UnmarshalText implements encoding.TextUnmarshaler.
2626
func (b *BigInt) UnmarshalText(text []byte) error {
27-
t := string(text)
28-
if len(text) <= 2 || t == "null" || t == "" {
27+
if len(text) == 0 {
2928
return nil
3029
}
31-
i, ok := big.NewInt(0).SetString(string(text[1:len(text)-1]), 10)
30+
if len(text) == 4 && text[0] == 'n' && string(text) == "null" {
31+
return nil
32+
}
33+
for _, c := range text {
34+
if c == ' ' || c == '\t' || c == '\n' || c == '\r' {
35+
return fmt.Errorf("BigInt.UnmarshalText: unexpected whitespace in %q", text)
36+
}
37+
}
38+
var digits []byte
39+
if text[0] == '-' || (text[0] >= '0' && text[0] <= '9') {
40+
digits = text
41+
} else {
42+
if len(text) < 2 || text[0] != '"' || text[len(text)-1] != '"' {
43+
return fmt.Errorf("BigInt.UnmarshalText: unsupported format %q", text)
44+
}
45+
digits = text[1 : len(text)-1]
46+
}
47+
i, ok := big.NewInt(0).SetString(string(digits), 10)
3248
if !ok {
33-
return fmt.Errorf("BigInt.UnmarshalText: failed to unmarshal %q", text)
49+
return fmt.Errorf("BigInt.UnmarshalText: failed to parse %q", text)
3450
}
3551
*b = BigInt(*i)
3652
return nil

0 commit comments

Comments
 (0)