Skip to content

Commit

Permalink
Fix variable-size int/float reader
Browse files Browse the repository at this point in the history
  • Loading branch information
kelindar committed Dec 24, 2021
1 parent 809eee6 commit 80a9a9a
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 6 deletions.
28 changes: 22 additions & 6 deletions commit/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,19 +104,35 @@ func (r *Reader) Index() uint32 {
return uint32(r.Offset)
}

// Int reads a int64 value.
// Int reads a int value of any size.
func (r *Reader) Int() int {
return int(binary.BigEndian.Uint64(r.buffer[r.i0:r.i1]))
return int(r.Uint())
}

// Uint reads a uint64 value.
// Uint reads a uint value of any size.
func (r *Reader) Uint() uint {
return uint(binary.BigEndian.Uint64(r.buffer[r.i0:r.i1]))
switch r.i1 - r.i0 {
case 2:
return uint(binary.BigEndian.Uint16(r.buffer[r.i0:r.i1]))
case 4:
return uint(binary.BigEndian.Uint32(r.buffer[r.i0:r.i1]))
case 8:
return uint(binary.BigEndian.Uint64(r.buffer[r.i0:r.i1]))
default:
panic("column: unable to read, unsupported integer size")
}
}

// Float reads a float64 value.
// Float reads a floating-point value of any size.
func (r *Reader) Float() float64 {
return r.Float64()
switch r.i1 - r.i0 {
case 4:
return float64(r.Float32())
case 8:
return r.Float64()
default:
panic("column: unable to read, unsupported float size")
}
}

// String reads a string value.
Expand Down
39 changes: 39 additions & 0 deletions commit/reader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,45 @@ func TestReaderIface(t *testing.T) {
assert.Equal(t, uint32(777), r.Index())
}

func TestReadIntMixedSize(t *testing.T) {
buf := NewBuffer(0)
buf.PutInt16(Put, 0, 10)
buf.PutInt32(Put, 1, 20)
buf.PutInt64(Put, 2, 30)
buf.PutString(Put, 3, "hello")

r := NewReader()
r.Seek(buf)
assert.True(t, r.Next())
assert.Equal(t, 10, r.Int())
assert.True(t, r.Next())
assert.Equal(t, 20, r.Int())
assert.True(t, r.Next())
assert.Equal(t, 30, r.Int())
assert.True(t, r.Next())
assert.Panics(t, func() {
r.Int()
})
}

func TestReadFloatMixedSize(t *testing.T) {
buf := NewBuffer(0)
buf.PutFloat32(Put, 0, 10)
buf.PutFloat64(Put, 1, 20)
buf.PutString(Put, 3, "hello")

r := NewReader()
r.Seek(buf)
assert.True(t, r.Next())
assert.Equal(t, 10.0, r.Float())
assert.True(t, r.Next())
assert.Equal(t, 20.0, r.Float())
assert.True(t, r.Next())
assert.Panics(t, func() {
r.Float()
})
}

func TestReaderMax(t *testing.T) {
buf := NewBuffer(0)
buf.Reset("test")
Expand Down

0 comments on commit 80a9a9a

Please sign in to comment.