MCPcopy
hub / github.com/tidwall/sjson / set

Function set

sjson.go:506–574  ·  view source on GitHub ↗
(jstr, path, raw string,
	stringify, del, optimistic, inplace bool)

Source from the content-addressed store, hash-verified

504}
505
506func set(jstr, path, raw string,
507 stringify, del, optimistic, inplace bool) ([]byte, error) {
508 if path == "" {
509 return []byte(jstr), &errorType{"path cannot be empty"}
510 }
511 if !del && optimistic && isOptimisticPath(path) {
512 res := gjson.Get(jstr, path)
513 if res.Exists() && res.Index > 0 {
514 sz := len(jstr) - len(res.Raw) + len(raw)
515 if stringify {
516 sz += 2
517 }
518 if inplace && sz <= len(jstr) {
519 if !stringify || !mustMarshalString(raw) {
520 jsonh := *(*stringHeader)(unsafe.Pointer(&jstr))
521 jsonbh := sliceHeader{
522 data: jsonh.data, len: jsonh.len, cap: jsonh.len}
523 jbytes := *(*[]byte)(unsafe.Pointer(&jsonbh))
524 if stringify {
525 jbytes[res.Index] = '"'
526 copy(jbytes[res.Index+1:], []byte(raw))
527 jbytes[res.Index+1+len(raw)] = '"'
528 copy(jbytes[res.Index+1+len(raw)+1:],
529 jbytes[res.Index+len(res.Raw):])
530 } else {
531 copy(jbytes[res.Index:], []byte(raw))
532 copy(jbytes[res.Index+len(raw):],
533 jbytes[res.Index+len(res.Raw):])
534 }
535 return jbytes[:sz], nil
536 }
537 return []byte(jstr), nil
538 }
539 buf := make([]byte, 0, sz)
540 buf = append(buf, jstr[:res.Index]...)
541 if stringify {
542 buf = appendStringify(buf, raw)
543 } else {
544 buf = append(buf, raw...)
545 }
546 buf = append(buf, jstr[res.Index+len(res.Raw):]...)
547 return buf, nil
548 }
549 }
550 var paths []pathResult
551 r, simple := parsePath(path)
552 if simple {
553 paths = append(paths, r)
554 for r.more {
555 r, simple = parsePath(r.path)
556 if !simple {
557 break
558 }
559 paths = append(paths, r)
560 }
561 }
562 if !simple {
563 if del {

Callers 3

SetRawOptionsFunction · 0.85
SetBytesOptionsFunction · 0.85
SetRawBytesOptionsFunction · 0.85

Calls 6

isOptimisticPathFunction · 0.85
mustMarshalStringFunction · 0.85
appendStringifyFunction · 0.85
parsePathFunction · 0.85
setComplexPathFunction · 0.85
appendRawPathsFunction · 0.85

Tested by

no test coverage detected