feat: add Decoder.UseNumber and the Number type
Test / test (push) Successful in 1m52s

Assisted-by: GLM 5.3 Flash
This commit is contained in:
2026-09-21 23:49:39 +02:00
parent 582222738b
commit ce0c1ebd9d
9 changed files with 320 additions and 4 deletions
+52
View File
@@ -1946,3 +1946,55 @@ func TestMarshalerResultIsNormalised(t *testing.T) {
t.Errorf("output mismatch:\ngot: %q\nwant: %q", out, want)
}
}
func TestMarshalNumber(t *testing.T) {
t.Run("the literal is written as it is", func(t *testing.T) {
out, err := Marshal(map[string]any{
"hex": Number("0x1f"), "sep": Number("1_000"),
"signed": Number("+1.0"), "inf": Number("inf"),
})
if err != nil {
t.Fatal(err)
}
want := "hex = 0x1f\ninf = inf\nsep = 1_000\nsigned = +1.0\n"
if string(out) != want {
t.Errorf("output mismatch:\ngot: %q\nwant: %q", out, want)
}
})
t.Run("a Number field round-trips", func(t *testing.T) {
type Cfg struct {
Rate Number `toml:"rate"`
}
out, err := Marshal(Cfg{Rate: "1_000"})
if err != nil {
t.Fatal(err)
}
if string(out) != "rate = 1_000\n" {
t.Fatalf("output %q", out)
}
var back map[string]any
if err := NewDecoder().UseNumber().Decode(out, &back); err != nil {
t.Fatal(err)
}
if got, ok := back["rate"].(Number); !ok || got != "1_000" {
t.Errorf("round trip = %#v, want Number(\"1_000\")", back["rate"])
}
})
t.Run("a Number inside a value array", func(t *testing.T) {
out, err := Marshal(map[string]any{"vals": []any{Number("0x1f"), "s", int64(2)}})
if err != nil {
t.Fatal(err)
}
want := "vals = [0x1f, \"s\", 2]\n"
if string(out) != want {
t.Errorf("output mismatch:\ngot: %q\nwant: %q", out, want)
}
})
t.Run("an invalid literal is an error", func(t *testing.T) {
for _, lit := range []Number{"01", "1__0", "abc", "1.2.3"} {
if _, err := Marshal(map[string]any{"n": lit}); err == nil {
t.Errorf("Number(%q) encoded without an error", lit)
}
}
})
}