unquote.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright 2021 ByteDance Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package unquote
  17. import (
  18. `unsafe`
  19. `runtime`
  20. `github.com/bytedance/sonic/internal/native`
  21. `github.com/bytedance/sonic/internal/native/types`
  22. `github.com/bytedance/sonic/internal/rt`
  23. )
  24. func String(s string) (ret string, err types.ParsingError) {
  25. mm := make([]byte, 0, len(s))
  26. err = intoBytesUnsafe(s, &mm)
  27. ret = rt.Mem2Str(mm)
  28. return
  29. }
  30. func IntoBytes(s string, m *[]byte) types.ParsingError {
  31. if cap(*m) < len(s) {
  32. return types.ERR_EOF
  33. } else {
  34. return intoBytesUnsafe(s, m)
  35. }
  36. }
  37. func intoBytesUnsafe(s string, m *[]byte) types.ParsingError {
  38. pos := -1
  39. slv := (*rt.GoSlice)(unsafe.Pointer(m))
  40. str := (*rt.GoString)(unsafe.Pointer(&s))
  41. /* unquote as the default configuration, replace invalid unicode with \ufffd */
  42. ret := native.Unquote(str.Ptr, str.Len, slv.Ptr, &pos, types.F_UNICODE_REPLACE)
  43. /* check for errors */
  44. if ret < 0 {
  45. return types.ParsingError(-ret)
  46. }
  47. /* update the length */
  48. slv.Len = ret
  49. runtime.KeepAlive(s)
  50. return 0
  51. }