MCPcopy Create free account
hub / github.com/auxten/postgresql-parser / EncodeByteArrayToRawBytes

Function EncodeByteArrayToRawBytes

pkg/sql/lex/encode.go:240–285  ·  view source on GitHub ↗

EncodeByteArrayToRawBytes converts a SQL-level byte array into raw bytes according to the encoding specification in "be". If the skipHexPrefix argument is set, the hexadecimal encoding does not prefix the output with "\x". This is suitable e.g. for the encode() built-in.

(
	data string, be sessiondata.BytesEncodeFormat, skipHexPrefix bool,
)

Source from the content-addressed store, hash-verified

238// prefix the output with "\x". This is suitable e.g. for the encode()
239// built-in.
240func EncodeByteArrayToRawBytes(
241 data string, be sessiondata.BytesEncodeFormat, skipHexPrefix bool,
242) string {
243 switch be {
244 case sessiondata.BytesEncodeHex:
245 head := 2
246 if skipHexPrefix {
247 head = 0
248 }
249 res := make([]byte, head+hex.EncodedLen(len(data)))
250 if !skipHexPrefix {
251 res[0] = '\\'
252 res[1] = 'x'
253 }
254 hex.Encode(res[head:], []byte(data))
255 return string(res)
256
257 case sessiondata.BytesEncodeEscape:
258 // PostgreSQL does not allow all the escapes formats recognized by
259 // CockroachDB's scanner. It only recognizes octal and \\ for the
260 // backslash itself.
261 // See https://www.postgresql.org/docs/current/static/datatype-binary.html#AEN5667
262 res := make([]byte, 0, len(data))
263 for _, c := range []byte(data) {
264 if c == '\\' {
265 res = append(res, '\\', '\\')
266 } else if c < 32 || c >= 127 {
267 // Escape the character in octal.
268 //
269 // Note: CockroachDB only supports UTF-8 for which all values
270 // below 128 are ASCII. There is no locale-dependent escaping
271 // in that case.
272 res = append(res, '\\', '0'+(c>>6), '0'+((c>>3)&7), '0'+(c&7))
273 } else {
274 res = append(res, c)
275 }
276 }
277 return string(res)
278
279 case sessiondata.BytesEncodeBase64:
280 return base64.StdEncoding.EncodeToString([]byte(data))
281
282 default:
283 panic(fmt.Sprintf("unhandled format: %s", be))
284 }
285}
286
287// DecodeRawBytesToByteArray converts raw bytes to a SQL-level byte array
288// according to the encoding specification in "be".

Callers 1

PerformCastFunction · 0.92

Calls 1

EncodeMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…