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

Function EncodeByteArrayToRawBytes

pkg/sql/lex/encode.go:96–139  ·  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 BytesEncodeFormat, skipHexPrefix bool)

Source from the content-addressed store, hash-verified

94// prefix the output with "\x". This is suitable e.g. for the encode()
95// built-in.
96func EncodeByteArrayToRawBytes(data string, be BytesEncodeFormat, skipHexPrefix bool) string {
97 switch be {
98 case BytesEncodeHex:
99 head := 2
100 if skipHexPrefix {
101 head = 0
102 }
103 res := make([]byte, head+hex.EncodedLen(len(data)))
104 if !skipHexPrefix {
105 res[0] = '\\'
106 res[1] = 'x'
107 }
108 hex.Encode(res[head:], []byte(data))
109 return string(res)
110
111 case BytesEncodeEscape:
112 // PostgreSQL does not allow all the escapes formats recognized by
113 // CockroachDB's scanner. It only recognizes octal and \\ for the
114 // backslash itself.
115 // See https://www.postgresql.org/docs/current/static/datatype-binary.html#AEN5667
116 res := make([]byte, 0, len(data))
117 for _, c := range []byte(data) {
118 if c == '\\' {
119 res = append(res, '\\', '\\')
120 } else if c < 32 || c >= 127 {
121 // Escape the character in octal.
122 //
123 // Note: CockroachDB only supports UTF-8 for which all values
124 // below 128 are ASCII. There is no locale-dependent escaping
125 // in that case.
126 res = append(res, '\\', '0'+(c>>6), '0'+((c>>3)&7), '0'+(c&7))
127 } else {
128 res = append(res, c)
129 }
130 }
131 return string(res)
132
133 case BytesEncodeBase64:
134 return base64.StdEncoding.EncodeToString([]byte(data))
135
136 default:
137 panic(errors.AssertionFailedf("unhandled format: %s", be))
138 }
139}
140
141// DecodeRawBytesToByteArray converts raw bytes to a SQL-level byte array
142// according to the encoding specification in "be".

Callers

nothing calls this directly

Calls 1

EncodeMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…