MCPcopy Create free account
hub / github.com/couchbase/sync_gateway / injectJSONPropertyFromBytes

Function injectJSONPropertyFromBytes

base/util.go:1407–1439  ·  view source on GitHub ↗

injectJSONPropertyFromBytes injects val under the given key into b.

(b []byte, bIsEmpty bool, kvPairs []KVPairBytes)

Source from the content-addressed store, hash-verified

1405
1406// injectJSONPropertyFromBytes injects val under the given key into b.
1407func injectJSONPropertyFromBytes(b []byte, bIsEmpty bool, kvPairs []KVPairBytes) (newJSON []byte) {
1408
1409 newJSONLength := len(b)
1410 for _, kv := range kvPairs {
1411 newJSONLength += len(kv.Key) + len(kv.Val) + 4 // json overhead for comma, quoted key, and colon
1412 }
1413 if bIsEmpty {
1414 // Take off the length of a comma when the starting body is empty
1415 newJSONLength--
1416 }
1417
1418 // Create the new byte slice with the required capacity
1419 newJSON = make([]byte, newJSONLength)
1420
1421 // copy almost all of b, except the last closing brace
1422 offset := copy(newJSON, b[0:len(b)-1])
1423
1424 for i, kv := range kvPairs {
1425 // if the body isn't empty, or we're not on our first value, prepend a comma before our property
1426 if i > 0 || !bIsEmpty {
1427 offset += copy(newJSON[offset:], ",")
1428 }
1429
1430 // inject valBytes as the last property
1431 offset += copy(newJSON[offset:], `"`+kv.Key+`":`)
1432 offset += copy(newJSON[offset:], kv.Val)
1433 }
1434
1435 // closing brace
1436 _ = copy(newJSON[offset:], "}")
1437
1438 return newJSON
1439}
1440
1441// WrapJSONUnknownFieldErr wraps JSON unknown field errors with ErrUnknownField for later checking via errors.Cause
1442func WrapJSONUnknownFieldErr(err error) error {

Callers 2

InjectJSONPropertiesFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected