main.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package yu_pack
  2. // Pack
  3. // @Description: Pack 底层实现
  4. type Pack struct {
  5. // 每次扩容的字节数
  6. grow_size int
  7. buf []byte
  8. get_i int
  9. }
  10. // New
  11. //
  12. // @Description: 创建 Pack 对象
  13. func New() (t *Pack) {
  14. t = &Pack{}
  15. t.grow_size = 128
  16. return
  17. }
  18. // SetGrowSize
  19. //
  20. // @Description: 设置每次扩容的尺寸
  21. func (t *Pack) SetGrowSize(size int) *Pack {
  22. t.grow_size = size
  23. return t
  24. }
  25. // Grow
  26. //
  27. // @Description: 将缓冲区复制到一个新的、更大的缓冲区,以便至少有 size 个超过 len(this.buf) 的容量字节。
  28. func (t *Pack) Grow(size int) *Pack {
  29. if len(t.buf) == 0 && cap(t.buf) == 0 {
  30. t.buf = make([]byte, 0, size+t.grow_size)
  31. return t
  32. }
  33. if len(t.buf)+size > cap(t.buf) {
  34. j_buf := make([]byte, len(t.buf), size+cap(t.buf)+t.grow_size)
  35. copy(j_buf, t.buf)
  36. t.buf = j_buf
  37. }
  38. return t
  39. }
  40. // -----------------------------------------------------------------------------------------------------基础
  41. // SetBytes
  42. //
  43. // @Description: 置缓冲区数据
  44. func (t *Pack) SetBytes(buf []byte) *Pack {
  45. t.buf = nil
  46. t.Grow(len(buf))
  47. t.buf = append(t.buf, buf...)
  48. t.get_i = 0
  49. return t
  50. }
  51. // String
  52. //
  53. // @Description: 返回缓冲区总数据的字符串
  54. func (t *Pack) String() string {
  55. return string(t.buf)
  56. }
  57. // Bytes
  58. //
  59. // @Description: 返回缓冲区总数据
  60. func (t *Pack) Bytes() []byte {
  61. j_buf := make([]byte, len(t.buf))
  62. copy(j_buf, t.buf)
  63. return j_buf
  64. }
  65. // Len
  66. //
  67. // @Description: 返回缓冲区总长度
  68. func (t *Pack) Len() int {
  69. return len(t.buf)
  70. }
  71. // Cap returns the capacity of the builder's underlying byte slice. It is the
  72. // total space allocated for the string being built and includes any bytes
  73. // already written.
  74. func (t *Pack) Cap() int {
  75. return cap(t.buf)
  76. }
  77. // Reset
  78. //
  79. // @Description: 重置缓冲区
  80. func (t *Pack) Reset() *Pack {
  81. t.buf = nil
  82. t.get_i = 0
  83. return t
  84. }