You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

76 lines
2.0 KiB

  1. // Copyright 2017, OpenCensus Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // Package tagencoding contains the tag encoding
  16. // used interally by the stats collector.
  17. package tagencoding // import "go.opencensus.io/internal/tagencoding"
  18. // Values represent the encoded buffer for the values.
  19. type Values struct {
  20. Buffer []byte
  21. WriteIndex int
  22. ReadIndex int
  23. }
  24. func (vb *Values) growIfRequired(expected int) {
  25. if len(vb.Buffer)-vb.WriteIndex < expected {
  26. tmp := make([]byte, 2*(len(vb.Buffer)+1)+expected)
  27. copy(tmp, vb.Buffer)
  28. vb.Buffer = tmp
  29. }
  30. }
  31. // WriteValue is the helper method to encode Values from map[Key][]byte.
  32. func (vb *Values) WriteValue(v []byte) {
  33. length := len(v) & 0xff
  34. vb.growIfRequired(1 + length)
  35. // writing length of v
  36. vb.Buffer[vb.WriteIndex] = byte(length)
  37. vb.WriteIndex++
  38. if length == 0 {
  39. // No value was encoded for this key
  40. return
  41. }
  42. // writing v
  43. copy(vb.Buffer[vb.WriteIndex:], v[:length])
  44. vb.WriteIndex += length
  45. }
  46. // ReadValue is the helper method to decode Values to a map[Key][]byte.
  47. func (vb *Values) ReadValue() []byte {
  48. // read length of v
  49. length := int(vb.Buffer[vb.ReadIndex])
  50. vb.ReadIndex++
  51. if length == 0 {
  52. // No value was encoded for this key
  53. return nil
  54. }
  55. // read value of v
  56. v := make([]byte, length)
  57. endIdx := vb.ReadIndex + length
  58. copy(v, vb.Buffer[vb.ReadIndex:endIdx])
  59. vb.ReadIndex = endIdx
  60. return v
  61. }
  62. // Bytes returns a reference to already written bytes in the Buffer.
  63. func (vb *Values) Bytes() []byte {
  64. return vb.Buffer[:vb.WriteIndex]
  65. }