123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- package network
- import (
- "bytes"
- "encoding/binary"
- )
- type DataReader struct {
- buffer *bytes.Buffer
- }
- func NewDataReader(data []byte) *DataReader {
- return &DataReader{buffer: bytes.NewBuffer(data)}
- }
- func (reader *DataReader) Byte() (byte, error) {
- var b byte
- err := binary.Read(reader.buffer, binary.BigEndian, &b)
- if err != nil {
- return 0, err
- }
- return b, nil
- }
- func (reader *DataReader) Bytes(bytesLen int) ([]byte, error) {
- bs := make([]byte, bytesLen)
- err := binary.Read(reader.buffer, binary.BigEndian, bs)
- if err != nil {
- return nil, err
- }
- return bs, nil
- }
- func (reader *DataReader) Uint8() (uint8, error) {
- var u uint8
- err := binary.Read(reader.buffer, binary.BigEndian, &u)
- if err != nil {
- return 0, err
- }
- return u, nil
- }
- func (reader *DataReader) Uint16() (uint16, error) {
- var u uint16
- err := binary.Read(reader.buffer, binary.BigEndian, &u)
- if err != nil {
- return 0, err
- }
- return u, nil
- }
- func (reader *DataReader) Uint32() (uint32, error) {
- var u uint32
- err := binary.Read(reader.buffer, binary.BigEndian, &u)
- if err != nil {
- return 0, err
- }
- return u, nil
- }
- func (reader *DataReader) Uint64() (uint64, error) {
- var u uint64
- err := binary.Read(reader.buffer, binary.BigEndian, &u)
- if err != nil {
- return 0, err
- }
- return u, nil
- }
- func (reader *DataReader) String(bytesLen int) (string, error) {
- retBytes := make([]byte, bytesLen)
- err := binary.Read(reader.buffer, binary.BigEndian, retBytes)
- if err != nil {
- return "", err
- }
- return string(retBytes), nil
- }
- func (reader *DataReader) Len() int {
- return reader.buffer.Len()
- }
- func (reader *DataReader) Cap() int {
- return reader.buffer.Cap()
- }
- func (reader *DataReader) GetBytes() []byte {
- return reader.buffer.Bytes()
- }
- func (reader *DataReader) ToWriter() (*DataWriter, error) {
- writer := NewDataWriter()
- err := writer.Bytes(writer.buffer.Bytes())
- if err != nil {
- return nil, err
- }
- return writer, nil
- }
|