data_reader.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. package network
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. )
  6. type DataReader struct {
  7. buffer *bytes.Buffer
  8. }
  9. func NewDataReader(data []byte) *DataReader {
  10. return &DataReader{buffer: bytes.NewBuffer(data)}
  11. }
  12. func (reader *DataReader) Byte() (byte, error) {
  13. var b byte
  14. err := binary.Read(reader.buffer, binary.BigEndian, &b)
  15. if err != nil {
  16. return 0, err
  17. }
  18. return b, nil
  19. }
  20. func (reader *DataReader) Bytes(bytesLen int) ([]byte, error) {
  21. bs := make([]byte, bytesLen)
  22. err := binary.Read(reader.buffer, binary.BigEndian, bs)
  23. if err != nil {
  24. return nil, err
  25. }
  26. return bs, nil
  27. }
  28. func (reader *DataReader) Uint8() (uint8, error) {
  29. var u uint8
  30. err := binary.Read(reader.buffer, binary.BigEndian, &u)
  31. if err != nil {
  32. return 0, err
  33. }
  34. return u, nil
  35. }
  36. func (reader *DataReader) Uint16() (uint16, error) {
  37. var u uint16
  38. err := binary.Read(reader.buffer, binary.BigEndian, &u)
  39. if err != nil {
  40. return 0, err
  41. }
  42. return u, nil
  43. }
  44. func (reader *DataReader) Uint32() (uint32, error) {
  45. var u uint32
  46. err := binary.Read(reader.buffer, binary.BigEndian, &u)
  47. if err != nil {
  48. return 0, err
  49. }
  50. return u, nil
  51. }
  52. func (reader *DataReader) Uint64() (uint64, error) {
  53. var u uint64
  54. err := binary.Read(reader.buffer, binary.BigEndian, &u)
  55. if err != nil {
  56. return 0, err
  57. }
  58. return u, nil
  59. }
  60. func (reader *DataReader) String(bytesLen int) (string, error) {
  61. retBytes := make([]byte, bytesLen)
  62. err := binary.Read(reader.buffer, binary.BigEndian, retBytes)
  63. if err != nil {
  64. return "", err
  65. }
  66. return string(retBytes), nil
  67. }
  68. func (reader *DataReader) Len() int {
  69. return reader.buffer.Len()
  70. }
  71. func (reader *DataReader) Cap() int {
  72. return reader.buffer.Cap()
  73. }
  74. func (reader *DataReader) GetBytes() []byte {
  75. return reader.buffer.Bytes()
  76. }
  77. func (reader *DataReader) ToWriter() (*DataWriter, error) {
  78. writer := NewDataWriter()
  79. err := writer.Bytes(writer.buffer.Bytes())
  80. if err != nil {
  81. return nil, err
  82. }
  83. return writer, nil
  84. }