File tree 3 files changed +65
-4
lines changed
3 files changed +65
-4
lines changed Original file line number Diff line number Diff line change 1
1
base10 encoding of primitive types
2
+
3
+ ``` bash
4
+ $ go test -bench=. -benchmem .
5
+ goos: darwin
6
+ goarch: arm64
7
+ pkg: github.com/ndx-technologies/base10quant
8
+ cpu: Apple M3 Max
9
+ BenchmarkL9/string-16 96114614 12.32 ns/op 16 B/op 1 allocs/op
10
+ BenchmarkL9/from_string-16 160158512 7.478 ns/op 0 B/op 0 allocs/op
11
+ ```
Original file line number Diff line number Diff line change @@ -4,9 +4,12 @@ import (
4
4
"errors"
5
5
)
6
6
7
- var ErrInvalidFormat = errors .New ("invalid format" )
7
+ var ErrL9InvalidFormat = errors .New ("l9: invalid format" )
8
8
9
- const MaxL9 = 999_999_999
9
+ const (
10
+ MaxL9 = 999_999_999
11
+ MinL9 = 0
12
+ )
10
13
11
14
// L9 is base10 chars encoding least significant 9 decimals of uint32.
12
15
type L9 struct { v uint32 }
@@ -44,12 +47,12 @@ func (s L9) MarshalText() ([]byte, error) {
44
47
45
48
func (s * L9 ) UnmarshalText (b []byte ) error {
46
49
if len (b ) != 9 {
47
- return ErrInvalidFormat
50
+ return ErrL9InvalidFormat
48
51
}
49
52
s .v = 0
50
53
for i := 0 ; i < 9 ; i ++ {
51
54
if b [i ] < '0' || b [i ] > '9' {
52
- return ErrInvalidFormat
55
+ return ErrL9InvalidFormat
53
56
}
54
57
s .v *= 10
55
58
s .v += uint32 (b [i ] - '0' )
Original file line number Diff line number Diff line change 1
1
package base10quant_test
2
2
3
3
import (
4
+ "fmt"
5
+ "math/rand"
4
6
"testing"
5
7
6
8
"github.com/ndx-technologies/base10quant"
7
9
)
8
10
11
+ func ExampleL9 () {
12
+ var v base10quant.L9
13
+ v .UnmarshalText ([]byte ("123456789" ))
14
+ fmt .Println (v )
15
+ // Output: 123456789
16
+ }
17
+
9
18
func TestL9 (t * testing.T ) {
10
19
t .Run ("ok" , func (t * testing.T ) {
11
20
tests := []struct {
@@ -89,3 +98,42 @@ func FuzzL9(f *testing.F) {
89
98
}
90
99
})
91
100
}
101
+
102
+ func BenchmarkL9 (b * testing.B ) {
103
+ b .Run ("string" , func (b * testing.B ) {
104
+ x := rand .Uint32 ()
105
+ v := base10quant .L9FromUint32 (x )
106
+ var s string
107
+
108
+ b .ResetTimer ()
109
+ for i := 0 ; i < b .N ; i ++ {
110
+ s = v .String ()
111
+ }
112
+
113
+ if len (s ) == 0 {
114
+ b .Fatal ("unexpected empty string" )
115
+ }
116
+ })
117
+
118
+ b .Run ("from_string" , func (b * testing.B ) {
119
+ x := rand .Uint32 ()
120
+ v := base10quant .L9FromUint32 (x )
121
+ s := v .String ()
122
+ var err error
123
+
124
+ b .ResetTimer ()
125
+ for i := 0 ; i < b .N ; i ++ {
126
+ v , err = base10quant .L9FromString (s )
127
+ }
128
+
129
+ if len (s ) == 0 {
130
+ b .Fatal ("unexpected empty string" )
131
+ }
132
+ if v == (base10quant.L9 {}) {
133
+ b .Fatal ("unexpected empty value" )
134
+ }
135
+ if err != nil {
136
+ b .Fatal (err )
137
+ }
138
+ })
139
+ }
You can’t perform that action at this time.
0 commit comments