Skip to content

Commit

Permalink
feat(dec.int): use uint(size) and int(size) methods
Browse files Browse the repository at this point in the history
  • Loading branch information
ernado committed Nov 2, 2021
1 parent ab978c8 commit a1c3960
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 14 deletions.
30 changes: 16 additions & 14 deletions dec_int.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,32 +24,34 @@ func init() {
}
}

// Uint read uint.
func (d *Decoder) Uint() (uint, error) {
if strconv.IntSize == 32 {
func (d *Decoder) uint(size int) (uint, error) {
if size == 32 {
v, err := d.Uint32()
if err != nil {
return 0, err
}
return uint(v), nil
return uint(v), err
}
v, err := d.Uint64()
if err != nil {
return 0, err
}
return uint(v), nil
return uint(v), err
}

// Int reads integer.
func (d *Decoder) Int() (int, error) {
if strconv.IntSize == 32 {
// Uint read uint.
func (d *Decoder) Uint() (uint, error) {
return d.uint(strconv.IntSize)
}

func (d *Decoder) int(size int) (int, error) {
if size == 32 {
v, err := d.Int32()
return int(v), err
}
v, err := d.Int64()
return int(v), err
}

// Int reads integer.
func (d *Decoder) Int() (int, error) {
return d.int(strconv.IntSize)
}

// Int32 reads int32 value.
func (d *Decoder) Int32() (int32, error) {
c, err := d.byte()
Expand Down
51 changes: 51 additions & 0 deletions dec_int_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package jx

import (
"testing"

"github.com/stretchr/testify/require"
)

func BenchmarkDecoder_Int(b *testing.B) {
data := []byte(`69315063`)
d := GetDecoder()
for i := 0; i < b.N; i++ {
d.ResetBytes(data)
if _, err := d.Int(); err != nil {
b.Fatal(err)
}
}
}

func BenchmarkDecoder_Uint(b *testing.B) {
data := []byte(`69315063`)
d := GetDecoder()
for i := 0; i < b.N; i++ {
d.ResetBytes(data)
if _, err := d.Uint(); err != nil {
b.Fatal(err)
}
}
}

func TestDecoder_int_sizes(t *testing.T) {
data := []byte(`69315063`)
d := GetDecoder()
for _, size := range []int{32, 64} {
d.ResetBytes(data)
v, err := d.int(size)
require.NoError(t, err)
require.Equal(t, 69315063, v)
}
}

func TestDecoder_uint_sizes(t *testing.T) {
data := []byte(`69315063`)
d := GetDecoder()
for _, size := range []int{32, 64} {
d.ResetBytes(data)
v, err := d.uint(size)
require.NoError(t, err)
require.Equal(t, uint(69315063), v)
}
}

0 comments on commit a1c3960

Please sign in to comment.