serialize-pe.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package fieldpath
  14. import (
  15. "errors"
  16. "fmt"
  17. "io"
  18. "strconv"
  19. "strings"
  20. jsoniter "github.com/json-iterator/go"
  21. "sigs.k8s.io/structured-merge-diff/v4/value"
  22. )
  23. var ErrUnknownPathElementType = errors.New("unknown path element type")
  24. const (
  25. // Field indicates that the content of this path element is a field's name
  26. peField = "f"
  27. // Value indicates that the content of this path element is a field's value
  28. peValue = "v"
  29. // Index indicates that the content of this path element is an index in an array
  30. peIndex = "i"
  31. // Key indicates that the content of this path element is a key value map
  32. peKey = "k"
  33. // Separator separates the type of a path element from the contents
  34. peSeparator = ":"
  35. )
  36. var (
  37. peFieldSepBytes = []byte(peField + peSeparator)
  38. peValueSepBytes = []byte(peValue + peSeparator)
  39. peIndexSepBytes = []byte(peIndex + peSeparator)
  40. peKeySepBytes = []byte(peKey + peSeparator)
  41. peSepBytes = []byte(peSeparator)
  42. )
  43. // DeserializePathElement parses a serialized path element
  44. func DeserializePathElement(s string) (PathElement, error) {
  45. b := []byte(s)
  46. if len(b) < 2 {
  47. return PathElement{}, errors.New("key must be 2 characters long:")
  48. }
  49. typeSep, b := b[:2], b[2:]
  50. if typeSep[1] != peSepBytes[0] {
  51. return PathElement{}, fmt.Errorf("missing colon: %v", s)
  52. }
  53. switch typeSep[0] {
  54. case peFieldSepBytes[0]:
  55. // Slice s rather than convert b, to save on
  56. // allocations.
  57. str := s[2:]
  58. return PathElement{
  59. FieldName: &str,
  60. }, nil
  61. case peValueSepBytes[0]:
  62. iter := readPool.BorrowIterator(b)
  63. defer readPool.ReturnIterator(iter)
  64. v, err := value.ReadJSONIter(iter)
  65. if err != nil {
  66. return PathElement{}, err
  67. }
  68. return PathElement{Value: &v}, nil
  69. case peKeySepBytes[0]:
  70. iter := readPool.BorrowIterator(b)
  71. defer readPool.ReturnIterator(iter)
  72. fields := value.FieldList{}
  73. iter.ReadObjectCB(func(iter *jsoniter.Iterator, key string) bool {
  74. v, err := value.ReadJSONIter(iter)
  75. if err != nil {
  76. iter.Error = err
  77. return false
  78. }
  79. fields = append(fields, value.Field{Name: key, Value: v})
  80. return true
  81. })
  82. fields.Sort()
  83. return PathElement{Key: &fields}, iter.Error
  84. case peIndexSepBytes[0]:
  85. i, err := strconv.Atoi(s[2:])
  86. if err != nil {
  87. return PathElement{}, err
  88. }
  89. return PathElement{
  90. Index: &i,
  91. }, nil
  92. default:
  93. return PathElement{}, ErrUnknownPathElementType
  94. }
  95. }
  96. var (
  97. readPool = jsoniter.NewIterator(jsoniter.ConfigCompatibleWithStandardLibrary).Pool()
  98. writePool = jsoniter.NewStream(jsoniter.ConfigCompatibleWithStandardLibrary, nil, 1024).Pool()
  99. )
  100. // SerializePathElement serializes a path element
  101. func SerializePathElement(pe PathElement) (string, error) {
  102. buf := strings.Builder{}
  103. err := serializePathElementToWriter(&buf, pe)
  104. return buf.String(), err
  105. }
  106. func serializePathElementToWriter(w io.Writer, pe PathElement) error {
  107. stream := writePool.BorrowStream(w)
  108. defer writePool.ReturnStream(stream)
  109. switch {
  110. case pe.FieldName != nil:
  111. if _, err := stream.Write(peFieldSepBytes); err != nil {
  112. return err
  113. }
  114. stream.WriteRaw(*pe.FieldName)
  115. case pe.Key != nil:
  116. if _, err := stream.Write(peKeySepBytes); err != nil {
  117. return err
  118. }
  119. stream.WriteObjectStart()
  120. for i, field := range *pe.Key {
  121. if i > 0 {
  122. stream.WriteMore()
  123. }
  124. stream.WriteObjectField(field.Name)
  125. value.WriteJSONStream(field.Value, stream)
  126. }
  127. stream.WriteObjectEnd()
  128. case pe.Value != nil:
  129. if _, err := stream.Write(peValueSepBytes); err != nil {
  130. return err
  131. }
  132. value.WriteJSONStream(*pe.Value, stream)
  133. case pe.Index != nil:
  134. if _, err := stream.Write(peIndexSepBytes); err != nil {
  135. return err
  136. }
  137. stream.WriteInt(*pe.Index)
  138. default:
  139. return errors.New("invalid PathElement")
  140. }
  141. b := stream.Buffer()
  142. err := stream.Flush()
  143. // Help jsoniter manage its buffers--without this, the next
  144. // use of the stream is likely to require an allocation. Look
  145. // at the jsoniter stream code to understand why. They were probably
  146. // optimizing for folks using the buffer directly.
  147. stream.SetBuffer(b[:0])
  148. return err
  149. }