Created
May 20, 2018 19:14
-
-
Save riptl/3a41d4be535f78f718b5a771a472fab6 to your computer and use it in GitHub Desktop.
deserialize byte slices
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package bufferutils | |
import "encoding/binary" | |
var bin = binary.BigEndian | |
type ByteSlicer struct { | |
Buf []byte | |
Ptr int | |
} | |
func SliceBytes(buf []byte) ByteSlicer { | |
return ByteSlicer { buf, 0 } | |
} | |
func (b *ByteSlicer) Reset() { | |
b.Seek(0) | |
} | |
func (b *ByteSlicer) Seek(offset int) { | |
// Bounds check | |
_ = b.Buf[offset] | |
b.Ptr = offset | |
} | |
func (b *ByteSlicer) CopyNext(target []byte) { | |
copy(target, b.Next(len(target))) | |
} | |
func (b *ByteSlicer) Next(count int) []byte { | |
buf := b.Get(count) | |
b.Skip(count) | |
return buf | |
} | |
func (b *ByteSlicer) Get(count int) []byte { | |
return b.Buf[b.Ptr:b.Ptr+count] | |
} | |
func (b *ByteSlicer) Skip(count int) { | |
b.Ptr += count | |
} | |
func (b *ByteSlicer) NextUint8() uint8 { | |
i := b.Buf[b.Ptr] // byte = uint8 | |
b.Ptr++ | |
return i | |
} | |
func (b *ByteSlicer) NextUint16() uint16 { | |
return bin.Uint16(b.Next(2)) | |
} | |
func (b *ByteSlicer) NextUint32() uint32 { | |
return bin.Uint32(b.Next(4)) | |
} | |
func (b *ByteSlicer) NextUint64() uint64 { | |
return bin.Uint64(b.Next(8)) | |
} | |
func (b *ByteSlicer) NextInt8() int8 { | |
return int8(b.NextUint8()) | |
} | |
func (b *ByteSlicer) NextInt16() int16 { | |
return int16(b.NextUint16()) | |
} | |
func (b *ByteSlicer) NextInt32() int32 { | |
return int32(b.NextUint32()) | |
} | |
func (b *ByteSlicer) NextInt64() int64 { | |
return int64(b.NextUint64()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment