real_encoder.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package encoding
  2. import "encoding/binary"
  3. type realEncoder struct {
  4. raw []byte
  5. off int
  6. stack []pushEncoder
  7. }
  8. // primitives
  9. func (re *realEncoder) putInt8(in int8) {
  10. re.raw[re.off] = byte(in)
  11. re.off += 1
  12. }
  13. func (re *realEncoder) putInt16(in int16) {
  14. binary.BigEndian.PutUint16(re.raw[re.off:], uint16(in))
  15. re.off += 2
  16. }
  17. func (re *realEncoder) putInt32(in int32) {
  18. binary.BigEndian.PutUint32(re.raw[re.off:], uint32(in))
  19. re.off += 4
  20. }
  21. func (re *realEncoder) putInt64(in int64) {
  22. binary.BigEndian.PutUint64(re.raw[re.off:], uint64(in))
  23. re.off += 8
  24. }
  25. // arrays
  26. func (re *realEncoder) putInt32Array(in []int32) {
  27. re.putArrayCount(len(in))
  28. for _, val := range in {
  29. re.putInt32(val)
  30. }
  31. }
  32. func (re *realEncoder) putArrayCount(in int) {
  33. re.putInt32(int32(in))
  34. }
  35. // misc
  36. func (re *realEncoder) putString(in string) {
  37. re.putInt16(int16(len(in)))
  38. copy(re.raw[re.off:], in)
  39. re.off += len(in)
  40. }
  41. func (re *realEncoder) putBytes(in []byte) {
  42. if in == nil {
  43. re.putInt32(-1)
  44. return
  45. }
  46. re.putInt32(int32(len(in)))
  47. re.putRaw(in)
  48. }
  49. func (re *realEncoder) putRaw(in []byte) {
  50. copy(re.raw[re.off:], in)
  51. re.off += len(in)
  52. }
  53. // stackable
  54. func (re *realEncoder) push(in pushEncoder) {
  55. in.saveOffset(re.off)
  56. re.off += in.reserveLength()
  57. re.stack = append(re.stack, in)
  58. }
  59. func (re *realEncoder) pushLength32() {
  60. re.push(&length32Encoder{})
  61. }
  62. func (re *realEncoder) pushCRC32() {
  63. re.push(&crc32Encoder{})
  64. }
  65. func (re *realEncoder) pop() {
  66. // this is go's ugly pop pattern (the inverse of append)
  67. in := re.stack[len(re.stack)-1]
  68. re.stack = re.stack[:len(re.stack)-1]
  69. in.run(re.off, re.raw)
  70. }