MCPcopy Create free account
hub / github.com/dolthub/doltgresql / DecodeRawBytesToByteArray

Function DecodeRawBytesToByteArray

postgres/parser/lex/encode.go:303–353  ·  view source on GitHub ↗

DecodeRawBytesToByteArray converts raw bytes to a SQL-level byte array according to the encoding specification in "be". When using the Hex format, the caller is responsible for skipping the "\x" prefix, if any. See DecodeRawBytesToByteArrayAuto() below for an alternative.

(data string, be BytesEncodeFormat)

Source from the content-addressed store, hash-verified

301// "\x" prefix, if any. See DecodeRawBytesToByteArrayAuto() below for
302// an alternative.
303func DecodeRawBytesToByteArray(data string, be BytesEncodeFormat) ([]byte, error) {
304 switch be {
305 case BytesEncodeHex:
306 return hex.DecodeString(data)
307
308 case BytesEncodeEscape:
309 // PostgreSQL does not allow all the escapes formats recognized by
310 // CockroachDB's scanner. It only recognizes octal and \\ for the
311 // backslash itself.
312 // See https://www.postgresql.org/docs/current/static/datatype-binary.html#AEN5667
313 res := make([]byte, 0, len(data))
314 for i := 0; i < len(data); i++ {
315 ch := data[i]
316 if ch != '\\' {
317 res = append(res, ch)
318 continue
319 }
320 if i >= len(data)-1 {
321 return nil, pgerror.New(pgcode.InvalidEscapeSequence,
322 "bytea encoded value ends with escape character")
323 }
324 if data[i+1] == '\\' {
325 res = append(res, '\\')
326 i++
327 continue
328 }
329 if i+3 >= len(data) {
330 return nil, pgerror.New(pgcode.InvalidEscapeSequence,
331 "bytea encoded value ends with incomplete escape sequence")
332 }
333 b := byte(0)
334 for j := 1; j <= 3; j++ {
335 octDigit := data[i+j]
336 if octDigit < '0' || octDigit > '7' || (j == 1 && octDigit > '3') {
337 return nil, pgerror.New(pgcode.InvalidEscapeSequence,
338 "invalid bytea escape sequence")
339 }
340 b = (b << 3) | (octDigit - '0')
341 }
342 res = append(res, b)
343 i += 3
344 }
345 return res, nil
346
347 case BytesEncodeBase64:
348 return base64.StdEncoding.DecodeString(data)
349
350 default:
351 return nil, errors.AssertionFailedf("unhandled format: %s", be)
352 }
353}
354
355// DecodeRawBytesToByteArrayAuto detects which format to use with
356// DecodeRawBytesToByteArray(). It only supports hex ("\x" prefix)

Callers 1

Calls 1

NewFunction · 0.92

Tested by

no test coverage detected