BxByteArray.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package bx
  2. import (
  3. "encoding/binary"
  4. )
  5. const (
  6. DefaultCapacity = 128
  7. )
  8. type BxByteArray struct {
  9. list []byte
  10. next int
  11. }
  12. func NewBxByteArray(capacity int) *BxByteArray {
  13. return &BxByteArray{
  14. list: make([]byte, capacity),
  15. next: 0,
  16. }
  17. }
  18. func NewDefaultBxByteArray() *BxByteArray {
  19. return NewBxByteArray(DefaultCapacity)
  20. }
  21. func (b *BxByteArray) add(data byte) {
  22. if b.next == len(b.list) {
  23. b.list = append(b.list, make([]byte, len(b.list)*2)...)
  24. }
  25. b.list[b.next] = data
  26. b.next++
  27. }
  28. func (b *BxByteArray) addInt16(data int16, endian int) {
  29. if b.next+1 >= len(b.list) {
  30. b.list = append(b.list, make([]byte, len(b.list)*2)...)
  31. }
  32. if endian == 0 { // LITTLE
  33. binary.LittleEndian.PutUint16(b.list[b.next:], uint16(data))
  34. } else { // BIG
  35. binary.BigEndian.PutUint16(b.list[b.next:], uint16(data))
  36. }
  37. b.next += 2
  38. }
  39. func (b *BxByteArray) addInt(data int32, endian int) {
  40. if b.next+3 >= len(b.list) {
  41. b.list = append(b.list, make([]byte, len(b.list)*2)...)
  42. }
  43. if endian == 0 { // LITTLE
  44. binary.LittleEndian.PutUint32(b.list[b.next:], uint32(data))
  45. } else { // BIG
  46. binary.BigEndian.PutUint32(b.list[b.next:], uint32(data))
  47. }
  48. b.next += 4
  49. }
  50. func (b *BxByteArray) addBytes(src []byte) {
  51. if src != nil {
  52. if b.next+len(src)-1 >= len(b.list) {
  53. b.list = append(b.list, make([]byte, len(b.list)+len(src))...)
  54. }
  55. copy(b.list[b.next:], src)
  56. b.next += len(src)
  57. }
  58. }
  59. func (b *BxByteArray) addBytesOffsetLength(src []byte, offset int, length int) {
  60. if src != nil {
  61. if b.next+length-1 >= len(b.list) {
  62. b.list = append(b.list, make([]byte, len(b.list)+length)...)
  63. }
  64. copy(b.list[b.next:], src[offset:offset+length])
  65. b.next += length
  66. }
  67. }
  68. func (b *BxByteArray) set(index int, data byte) {
  69. if index < len(b.list) {
  70. b.list[index] = data
  71. }
  72. }
  73. func (b *BxByteArray) get(index int) byte {
  74. return b.list[index]
  75. }
  76. func (b *BxByteArray) Build() []byte {
  77. return b.list[:b.next]
  78. }
  79. func (b *BxByteArray) size() int {
  80. return b.next
  81. }
  82. func (b *BxByteArray) clear() {
  83. b.next = 0
  84. }