quote.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. // Copyright 2023 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package jsontext
  5. import (
  6. "github.com/go-json-experiment/json/internal/jsonflags"
  7. "github.com/go-json-experiment/json/internal/jsonwire"
  8. )
  9. // AppendQuote appends a double-quoted JSON string literal representing src
  10. // to dst and returns the extended buffer.
  11. // It uses the minimal string representation per RFC 8785, section 3.2.2.2.
  12. // Invalid UTF-8 bytes are replaced with the Unicode replacement character
  13. // and an error is returned at the end indicating the presence of invalid UTF-8.
  14. // The dst must not overlap with the src.
  15. func AppendQuote[Bytes ~[]byte | ~string](dst []byte, src Bytes) ([]byte, error) {
  16. dst, err := jsonwire.AppendQuote(dst, src, &jsonflags.Flags{})
  17. if err != nil {
  18. err = &SyntacticError{Err: err}
  19. }
  20. return dst, err
  21. }
  22. // AppendUnquote appends the decoded interpretation of src as a
  23. // double-quoted JSON string literal to dst and returns the extended buffer.
  24. // The input src must be a JSON string without any surrounding whitespace.
  25. // Invalid UTF-8 bytes are replaced with the Unicode replacement character
  26. // and an error is returned at the end indicating the presence of invalid UTF-8.
  27. // Any trailing bytes after the JSON string literal results in an error.
  28. // The dst must not overlap with the src.
  29. func AppendUnquote[Bytes ~[]byte | ~string](dst []byte, src Bytes) ([]byte, error) {
  30. dst, err := jsonwire.AppendUnquote(dst, src)
  31. if err != nil {
  32. err = &SyntacticError{Err: err}
  33. }
  34. return dst, err
  35. }