Browse Source

Merge pull request #1373 from shanson7/peekint8

Provide peekInt8 to reduce allocations
Vlad Gorodetsky 5 years ago
parent
commit
72033d7980
3 changed files with 10 additions and 6 deletions
  1. 1 0
      packet_decoder.go
  2. 8 0
      real_decoder.go
  3. 1 6
      records.go

+ 1 - 0
packet_decoder.go

@@ -27,6 +27,7 @@ type packetDecoder interface {
 	remaining() int
 	getSubset(length int) (packetDecoder, error)
 	peek(offset, length int) (packetDecoder, error) // similar to getSubset, but it doesn't advance the offset
+	peekInt8(offset int) (int8, error)              // similar to peek, but just one byte
 
 	// Stacks, see PushDecoder
 	push(in pushDecoder) error

+ 8 - 0
real_decoder.go

@@ -290,6 +290,14 @@ func (rd *realDecoder) peek(offset, length int) (packetDecoder, error) {
 	return &realDecoder{raw: rd.raw[off : off+length]}, nil
 }
 
+func (rd *realDecoder) peekInt8(offset int) (int8, error) {
+	const byteLen = 1
+	if rd.remaining() < offset+byteLen {
+		return -1, ErrInsufficientData
+	}
+	return int8(rd.raw[rd.off+offset]), nil
+}
+
 // stacks
 
 func (rd *realDecoder) push(in pushDecoder) error {

+ 1 - 6
records.go

@@ -185,12 +185,7 @@ func (r *Records) isOverflow() (bool, error) {
 }
 
 func magicValue(pd packetDecoder) (int8, error) {
-	dec, err := pd.peek(magicOffset, magicLength)
-	if err != nil {
-		return 0, err
-	}
-
-	return dec.getInt8()
+	return pd.peekInt8(magicOffset)
 }
 
 func (r *Records) getControlRecord() (ControlRecord, error) {