1use crate::error::{Error, Result};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
9pub enum StringLiteral {
10 #[default]
13 Backslash,
14 BackslashUtf8,
16 Extended,
18 Standard,
20}
21
22fn refused(message: &str) -> Error {
23 Error::Validation(message.into())
24}
25
26impl StringLiteral {
27 pub const CASES: [(StringLiteral, &'static str); 4] = [
29 (StringLiteral::Backslash, "Backslash"),
30 (StringLiteral::BackslashUtf8, "BackslashUtf8"),
31 (StringLiteral::Extended, "Extended"),
32 (StringLiteral::Standard, "Standard"),
33 ];
34
35 pub const fn escape_prefix(self) -> &'static str {
40 match self {
41 StringLiteral::Extended => "E",
42 _ => "",
43 }
44 }
45
46 pub const fn escapes_in_plain_literal(self) -> bool {
50 matches!(self, StringLiteral::Backslash | StringLiteral::BackslashUtf8)
51 }
52
53 const fn escapes_backslash(self) -> bool {
54 !matches!(self, StringLiteral::Standard)
55 }
56
57 const fn refuses_backslash_after_high_byte(self) -> bool {
58 matches!(self, StringLiteral::Backslash | StringLiteral::Extended)
59 }
60
61 const fn refuses_nul(self) -> bool {
62 matches!(self, StringLiteral::Extended | StringLiteral::Standard)
63 }
64
65 pub fn quote(self, value: &str) -> Result<String> {
81 if self.refuses_nul() && value.contains('\0') {
82 return Err(refused("String literal contains a NUL byte"));
83 }
84 let escapes = self.escapes_backslash() && value.contains('\\');
85 if escapes && self.refuses_backslash_after_high_byte() {
86 let mut before = '\0';
87 for c in value.chars() {
88 if c == '\\' && !before.is_ascii() {
89 return Err(refused(
90 "String literal has a backslash after a byte of 0x80 or above, which a multibyte connection charset can read as part of the preceding character",
91 ));
92 }
93 before = c;
94 }
95 }
96 let mut out = String::with_capacity(value.len() + 3);
97 if escapes {
98 out.push_str(self.escape_prefix());
99 }
100 out.push('\'');
101 for c in value.chars() {
102 match c {
103 '\'' => out.push_str("''"),
104 '\\' if escapes => out.push_str("\\\\"),
105 c => out.push(c),
106 }
107 }
108 out.push('\'');
109 Ok(out)
110 }
111
112 pub fn unquote(self, literal: &[u8]) -> Result<Vec<u8>> {
125 let malformed = || refused("Malformed string literal");
126 let prefix = self.escape_prefix().as_bytes();
127 let mut escaped = self.escapes_in_plain_literal();
128 let mut literal = literal;
129 if !prefix.is_empty()
130 && literal.len() > prefix.len()
131 && literal[..prefix.len()].eq_ignore_ascii_case(prefix)
132 && literal[prefix.len()] == b'\''
133 {
134 literal = &literal[prefix.len()..];
135 escaped = true;
136 }
137 if literal.len() < 2 || literal[0] != b'\'' || literal[literal.len() - 1] != b'\'' {
138 return Err(malformed());
139 }
140 let body = &literal[1..literal.len() - 1];
141 let mut value = Vec::with_capacity(body.len());
142 let mut position = 0;
143 while position < body.len() {
144 let byte = body[position];
145 if byte == b'\'' {
146 if body.get(position + 1) != Some(&b'\'') {
147 return Err(malformed());
148 }
149 value.push(b'\'');
150 position += 2;
151 } else if escaped && byte == b'\\' {
152 if position + 1 >= body.len() {
153 return Err(malformed());
154 }
155 let escape = self.read_escape(body, position + 1);
156 self.decode(escape, &mut value)?;
157 position += 1 + escape.len();
158 } else {
159 value.push(byte);
160 position += 1;
161 }
162 }
163 if self.refuses_nul() && value.contains(&0) {
164 return Err(refused("String literal contains a NUL byte"));
165 }
166 Ok(value)
167 }
168
169 fn read_escape(self, body: &[u8], position: usize) -> &[u8] {
171 let one = &body[position..=position];
172 match (self, body[position]) {
173 (StringLiteral::BackslashUtf8, b'x') => read_hex(body, position, 2, 2),
174 (StringLiteral::Extended, b'0'..=b'7') => {
175 let digits = body[position..].iter().take(3).take_while(|byte| (b'0'..=b'7').contains(byte)).count();
176 &body[position..position + digits]
177 }
178 (StringLiteral::Extended, b'x') => read_hex(body, position, 1, 2),
179 (StringLiteral::Extended, b'u') => read_hex(body, position, 4, 4),
180 (StringLiteral::Extended, b'U') => read_hex(body, position, 8, 8),
181 _ => one,
182 }
183 }
184
185 fn decode(self, escape: &[u8], value: &mut Vec<u8>) -> Result<()> {
186 let numeric = escape.len() > 1 || (self == StringLiteral::Extended && (b'0'..=b'7').contains(&escape[0]));
187 if numeric {
188 let digits = std::str::from_utf8(&escape[1..]).unwrap_or_default();
189 match escape[0] {
190 b'x' => value.push(u32::from_str_radix(digits, 16).unwrap_or(0) as u8),
192 b'u' | b'U' => {
193 let point = u32::from_str_radix(digits, 16).ok().and_then(char::from_u32);
194 let point = point.ok_or_else(|| refused("String literal has an invalid Unicode escape"))?;
195 value.extend_from_slice(point.encode_utf8(&mut [0; 4]).as_bytes());
196 }
197 _ => {
198 let digits = std::str::from_utf8(escape).unwrap_or_default();
199 value.push(u32::from_str_radix(digits, 8).unwrap_or(0) as u8);
200 }
201 }
202 return Ok(());
203 }
204 let byte = escape[0];
205 let decoded = match (self, byte) {
206 (StringLiteral::Backslash | StringLiteral::BackslashUtf8, b'0') => 0,
207 (StringLiteral::BackslashUtf8, b'a') => 0x07,
208 (StringLiteral::Backslash | StringLiteral::BackslashUtf8 | StringLiteral::Extended, b'b') => 0x08,
209 (StringLiteral::BackslashUtf8 | StringLiteral::Extended, b'f') => 0x0C,
210 (StringLiteral::Backslash | StringLiteral::BackslashUtf8 | StringLiteral::Extended, b'n') => b'\n',
211 (StringLiteral::Backslash | StringLiteral::BackslashUtf8 | StringLiteral::Extended, b'r') => b'\r',
212 (StringLiteral::Backslash | StringLiteral::BackslashUtf8 | StringLiteral::Extended, b't') => b'\t',
213 (StringLiteral::BackslashUtf8, b'v') => 0x0B,
214 (StringLiteral::Backslash, b'Z') => 0x1A,
215 (StringLiteral::Backslash, b'%' | b'_') | (StringLiteral::Standard, _) => {
216 value.push(b'\\');
217 byte
218 }
219 _ => byte,
220 };
221 value.push(decoded);
222 Ok(())
223 }
224}
225
226fn read_hex(body: &[u8], position: usize, minimum: usize, maximum: usize) -> &[u8] {
229 let digits = body[position + 1..].iter().take(maximum).take_while(|byte| byte.is_ascii_hexdigit()).count();
230 if digits < minimum { &body[position..=position] } else { &body[position..=position + digits] }
231}
232
233pub(crate) fn narrow(widened: &[u8]) -> Vec<u8> {
235 String::from_utf8_lossy(widened).chars().map(|c| u8::try_from(u32::from(c)).unwrap_or(b'?')).collect()
236}
237
238pub(crate) fn widen(bytes: &[u8]) -> Vec<u8> {
240 bytes.iter().map(|&byte| char::from(byte)).collect::<String>().into_bytes()
241}