Skip to content

Commit

Permalink
nit
Browse files Browse the repository at this point in the history
  • Loading branch information
nikolaydubina committed Dec 13, 2024
1 parent e3f3af8 commit 3b84dd4
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 4 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -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
```
11 changes: 7 additions & 4 deletions l9.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down Expand Up @@ -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')
Expand Down
48 changes: 48 additions & 0 deletions l9_test.go
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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)
}
})
}

0 comments on commit 3b84dd4

Please sign in to comment.