unquote.go (1657B)
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 17 package unquote 18 19 import ( 20 `unsafe` 21 `runtime` 22 23 `github.com/bytedance/sonic/internal/native` 24 `github.com/bytedance/sonic/internal/native/types` 25 `github.com/bytedance/sonic/internal/rt` 26 ) 27 28 func String(s string) (ret string, err types.ParsingError) { 29 mm := make([]byte, 0, len(s)) 30 err = intoBytesUnsafe(s, &mm) 31 ret = rt.Mem2Str(mm) 32 return 33 } 34 35 func IntoBytes(s string, m *[]byte) types.ParsingError { 36 if cap(*m) < len(s) { 37 return types.ERR_EOF 38 } else { 39 return intoBytesUnsafe(s, m) 40 } 41 } 42 43 func intoBytesUnsafe(s string, m *[]byte) types.ParsingError { 44 pos := -1 45 slv := (*rt.GoSlice)(unsafe.Pointer(m)) 46 str := (*rt.GoString)(unsafe.Pointer(&s)) 47 /* unquote as the default configuration, replace invalid unicode with \ufffd */ 48 ret := native.Unquote(str.Ptr, str.Len, slv.Ptr, &pos, types.F_UNICODE_REPLACE) 49 50 /* check for errors */ 51 if ret < 0 { 52 return types.ParsingError(-ret) 53 } 54 55 /* update the length */ 56 slv.Len = ret 57 runtime.KeepAlive(s) 58 return 0 59 }