codec.go 918 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package debugging_runtime
  2. import (
  3. "bytes"
  4. "errors"
  5. "github.com/panjf2000/gnet/v2"
  6. )
  7. type codec struct {
  8. buf bytes.Buffer
  9. }
  10. func (w *codec) Decode(c gnet.Conn) ([][]byte, error) {
  11. size := c.InboundBuffered()
  12. buf := make([]byte, size)
  13. read, err := c.Read(buf)
  14. if err != nil {
  15. return nil, err
  16. }
  17. if read < size {
  18. return nil, errors.New("read less than size")
  19. }
  20. return w.getLines(buf), nil
  21. }
  22. func (w *codec) getLines(data []byte) [][]byte {
  23. // write to buffer
  24. w.buf.Write(data)
  25. // read line by line, split by \n, remaining data will be kept in buffer
  26. buf := make([]byte, w.buf.Len())
  27. w.buf.Read(buf)
  28. w.buf.Reset()
  29. lines := bytes.Split(buf, []byte("\n"))
  30. // if last line is not completed, keep it in buffer
  31. if len(lines[len(lines)-1]) != 0 {
  32. w.buf.Write(lines[len(lines)-1])
  33. lines = lines[:len(lines)-1]
  34. } else if len(lines) > 0 {
  35. lines = lines[:len(lines)-1]
  36. }
  37. return lines
  38. }