package ints import "testing" type marshalCase struct { n uint64 want string } // TestMarshal covers the base-10^4 chunking across every power boundary. func TestMarshal(t *testing.T) { cases := []marshalCase{ {0, "0"}, {1, "1"}, {9, "9"}, {10, "10"}, {9999, "9999"}, {10000, "10000"}, {10001, "10001"}, {99999999, "99999999"}, {100000000, "100000000"}, {123456789, "123456789"}, {12345678901234567890, "12345678901234567890"}, } for _, c := range cases { got := string(New(c.n).Marshal(nil)) if got != c.want { t.Fatalf("Marshal(%d) = %s, want %s", c.n, got, c.want) } } } // TestMarshalAppends checks that Marshal writes after existing dst content, the // way it is used when building a JSON array by hand. func TestMarshalAppends(t *testing.T) { if got := string(New(uint64(42)).Marshal([]byte("x="))); got != "x=42" { t.Fatalf("Marshal into dst: got %s", got) } if got := string(New(uint64(0)).Marshal([]byte("x="))); got != "x=0" { t.Fatalf("Marshal zero into dst: got %s", got) } } func TestUnmarshal(t *testing.T) { n := New(uint64(0)) rem, err := n.Unmarshal([]byte("12345")) if err != nil { t.Fatal(err) } if n.Uint64() != 12345 || len(rem) != 0 { t.Fatalf("Unmarshal 12345: got %d", n.Uint64()) } // A trailing delimiter stays in the remainder. rem, err = n.Unmarshal([]byte("678,")) if err != nil { t.Fatal(err) } if n.Uint64() != 678 || string(rem) != "," { t.Fatalf("Unmarshal remainder: got %s", string(rem)) } // A leading zero is a complete value on its own. rem, err = n.Unmarshal([]byte("0abc")) if err != nil { t.Fatal(err) } if n.Uint64() != 0 || string(rem) != "abc" { t.Fatalf("Unmarshal zero: got %s", string(rem)) } if _, err = n.Unmarshal(nil); err == nil { t.Fatal("Unmarshal of nothing should fail") } if _, err = n.Unmarshal([]byte("1234567890123456789012")); err == nil { t.Fatal("Unmarshal of an over-long number should fail") } } // TestRoundTrip is the property the JSON writers rely on. func TestRoundTrip(t *testing.T) { vals := []uint64{0, 1, 10, 9999, 10000, 4294967296, 12345678901234567890} for _, v := range vals { text := New(v).Marshal(nil) n := New(uint64(0)) if _, err := n.Unmarshal(text); err != nil { t.Fatal(err) } if n.Uint64() != v { t.Fatalf("roundtrip: got %d want %d", n.Uint64(), v) } } } func TestAccessors(t *testing.T) { n := New(uint64(65535)) if n.Int64() != 65535 { t.Fatal("Int64") } if n.Uint16() != 65535 { t.Fatal("Uint16") } }