Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate github.com/json-iterator/go to sigs.k8s.io/json #257

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion fieldpath/path.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func (fp Path) Copy() Path {

// MakePath constructs a Path. The parts may be PathElements, ints, strings.
func MakePath(parts ...interface{}) (Path, error) {
var fp Path
fp := make(Path, 0, len(parts))
for _, p := range parts {
switch t := p.(type) {
case PathElement:
Expand Down
113 changes: 46 additions & 67 deletions fieldpath/serialize-pe.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,52 +19,49 @@ package fieldpath
import (
"errors"
"fmt"
"io"
"strconv"
"strings"

jsoniter "github.com/json-iterator/go"
"sigs.k8s.io/structured-merge-diff/v4/internal/builder"
"sigs.k8s.io/structured-merge-diff/v4/value"
)

var ErrUnknownPathElementType = errors.New("unknown path element type")

const (
// Field indicates that the content of this path element is a field's name
peField = "f"
peField byte = 'f'

// Value indicates that the content of this path element is a field's value
peValue = "v"
peValue byte = 'v'

// Index indicates that the content of this path element is an index in an array
peIndex = "i"
peIndex byte = 'i'

// Key indicates that the content of this path element is a key value map
peKey = "k"
peKey byte = 'k'

// Separator separates the type of a path element from the contents
peSeparator = ":"
peSeparator byte = ':'
)

var (
peFieldSepBytes = []byte(peField + peSeparator)
peValueSepBytes = []byte(peValue + peSeparator)
peIndexSepBytes = []byte(peIndex + peSeparator)
peKeySepBytes = []byte(peKey + peSeparator)
peSepBytes = []byte(peSeparator)
peFieldSepBytes = []byte{peField, peSeparator}
peValueSepBytes = []byte{peValue, peSeparator}
peIndexSepBytes = []byte{peIndex, peSeparator}
peKeySepBytes = []byte{peKey, peSeparator}
)

// DeserializePathElement parses a serialized path element
func DeserializePathElement(s string) (PathElement, error) {
b := []byte(s)
b := builder.StringToReadOnlyByteSlice(s)
if len(b) < 2 {
return PathElement{}, errors.New("key must be 2 characters long:")
return PathElement{}, errors.New("key must be 2 characters long")
}
typeSep, b := b[:2], b[2:]
if typeSep[1] != peSepBytes[0] {
typeSep0, typeSep1, b := b[0], b[1], b[2:]
if typeSep1 != peSeparator {
return PathElement{}, fmt.Errorf("missing colon: %v", s)
}
switch typeSep[0] {
switch typeSep0 {
case peFieldSepBytes[0]:
// Slice s rather than convert b, to save on
// allocations.
Expand All @@ -73,29 +70,18 @@ func DeserializePathElement(s string) (PathElement, error) {
FieldName: &str,
}, nil
case peValueSepBytes[0]:
iter := readPool.BorrowIterator(b)
defer readPool.ReturnIterator(iter)
v, err := value.ReadJSONIter(iter)
v, err := value.FromJSON(b)
if err != nil {
return PathElement{}, err
}
return PathElement{Value: &v}, nil
case peKeySepBytes[0]:
iter := readPool.BorrowIterator(b)
defer readPool.ReturnIterator(iter)
fields := value.FieldList{}

iter.ReadObjectCB(func(iter *jsoniter.Iterator, key string) bool {
v, err := value.ReadJSONIter(iter)
if err != nil {
iter.Error = err
return false
}
fields = append(fields, value.Field{Name: key, Value: v})
return true
})
fields, err := value.FieldListFromJSON(b)
if err != nil {
return PathElement{}, err
}
fields.Sort()
return PathElement{Key: &fields}, iter.Error
return PathElement{Key: &fields}, nil
case peIndexSepBytes[0]:
i, err := strconv.Atoi(s[2:])
if err != nil {
Expand All @@ -109,60 +95,53 @@ func DeserializePathElement(s string) (PathElement, error) {
}
}

var (
readPool = jsoniter.NewIterator(jsoniter.ConfigCompatibleWithStandardLibrary).Pool()
writePool = jsoniter.NewStream(jsoniter.ConfigCompatibleWithStandardLibrary, nil, 1024).Pool()
)

// SerializePathElement serializes a path element
func SerializePathElement(pe PathElement) (string, error) {
buf := strings.Builder{}
buf := builder.JSONBuilder{}
err := serializePathElementToWriter(&buf, pe)
return buf.String(), err
}

func serializePathElementToWriter(w io.Writer, pe PathElement) error {
stream := writePool.BorrowStream(w)
defer writePool.ReturnStream(stream)
func serializePathElementToWriter(w *builder.JSONBuilder, pe PathElement) error {
switch {
case pe.FieldName != nil:
if _, err := stream.Write(peFieldSepBytes); err != nil {
if _, err := w.Write(peFieldSepBytes); err != nil {
return err
}
stream.WriteRaw(*pe.FieldName)
w.WriteString(*pe.FieldName)
case pe.Key != nil:
if _, err := stream.Write(peKeySepBytes); err != nil {
if _, err := w.Write(peKeySepBytes); err != nil {
return err
}
stream.WriteObjectStart()

for i, field := range *pe.Key {
if i > 0 {
stream.WriteMore()
w.WriteByte('{')
nrKeys := len(*pe.Key)
for i, f := range *pe.Key {
if err := w.WriteJSON(f.Name); err != nil {
return err
}
w.WriteByte(':')
if err := w.WriteJSON(f.Value.Unstructured()); err != nil {
return err
}
if i < nrKeys-1 {
w.WriteByte(',')
}
stream.WriteObjectField(field.Name)
value.WriteJSONStream(field.Value, stream)
}
stream.WriteObjectEnd()
w.WriteByte('}')
case pe.Value != nil:
if _, err := stream.Write(peValueSepBytes); err != nil {
if _, err := w.Write(peValueSepBytes); err != nil {
return err
}
if err := w.WriteJSON((*pe.Value).Unstructured()); err != nil {
return err
}
value.WriteJSONStream(*pe.Value, stream)
case pe.Index != nil:
if _, err := stream.Write(peIndexSepBytes); err != nil {
if _, err := w.Write(peIndexSepBytes); err != nil {
return err
}
stream.WriteInt(*pe.Index)
w.WriteString(strconv.Itoa(*pe.Index))
default:
return errors.New("invalid PathElement")
}
b := stream.Buffer()
err := stream.Flush()
// Help jsoniter manage its buffers--without this, the next
// use of the stream is likely to require an allocation. Look
// at the jsoniter stream code to understand why. They were probably
// optimizing for folks using the buffer directly.
stream.SetBuffer(b[:0])
return err
return nil
}
Loading