data_writer.go 1.6 KB

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