From 3b84dd4bc41bb075b0521b2a239a0a337709a083 Mon Sep 17 00:00:00 2001 From: Nikolay Dubina Date: Fri, 13 Dec 2024 22:20:38 +0800 Subject: [PATCH] nit --- README.md | 10 ++++++++++ l9.go | 11 +++++++---- l9_test.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 4ccaf21..cf57bc8 100644 --- a/README.md +++ b/README.md @@ -1 +1,11 @@ base10 encoding of primitive types + +```bash +$ go test -bench=. -benchmem . +goos: darwin +goarch: arm64 +pkg: github.com/ndx-technologies/base10quant +cpu: Apple M3 Max +BenchmarkL9/string-16 96114614 12.32 ns/op 16 B/op 1 allocs/op +BenchmarkL9/from_string-16 160158512 7.478 ns/op 0 B/op 0 allocs/op +``` diff --git a/l9.go b/l9.go index 0f9c723..df3b248 100644 --- a/l9.go +++ b/l9.go @@ -4,9 +4,12 @@ import ( "errors" ) -var ErrInvalidFormat = errors.New("invalid format") +var ErrL9InvalidFormat = errors.New("l9: invalid format") -const MaxL9 = 999_999_999 +const ( + MaxL9 = 999_999_999 + MinL9 = 0 +) // L9 is base10 chars encoding least significant 9 decimals of uint32. type L9 struct{ v uint32 } @@ -44,12 +47,12 @@ func (s L9) MarshalText() ([]byte, error) { func (s *L9) UnmarshalText(b []byte) error { if len(b) != 9 { - return ErrInvalidFormat + return ErrL9InvalidFormat } s.v = 0 for i := 0; i < 9; i++ { if b[i] < '0' || b[i] > '9' { - return ErrInvalidFormat + return ErrL9InvalidFormat } s.v *= 10 s.v += uint32(b[i] - '0') diff --git a/l9_test.go b/l9_test.go index ef1e368..464d5f9 100644 --- a/l9_test.go +++ b/l9_test.go @@ -1,11 +1,20 @@ package base10quant_test import ( + "fmt" + "math/rand" "testing" "github.com/ndx-technologies/base10quant" ) +func ExampleL9() { + var v base10quant.L9 + v.UnmarshalText([]byte("123456789")) + fmt.Println(v) + // Output: 123456789 +} + func TestL9(t *testing.T) { t.Run("ok", func(t *testing.T) { tests := []struct { @@ -89,3 +98,42 @@ func FuzzL9(f *testing.F) { } }) } + +func BenchmarkL9(b *testing.B) { + b.Run("string", func(b *testing.B) { + x := rand.Uint32() + v := base10quant.L9FromUint32(x) + var s string + + b.ResetTimer() + for i := 0; i < b.N; i++ { + s = v.String() + } + + if len(s) == 0 { + b.Fatal("unexpected empty string") + } + }) + + b.Run("from_string", func(b *testing.B) { + x := rand.Uint32() + v := base10quant.L9FromUint32(x) + s := v.String() + var err error + + b.ResetTimer() + for i := 0; i < b.N; i++ { + v, err = base10quant.L9FromString(s) + } + + if len(s) == 0 { + b.Fatal("unexpected empty string") + } + if v == (base10quant.L9{}) { + b.Fatal("unexpected empty value") + } + if err != nil { + b.Fatal(err) + } + }) +}