quickjs_jit_stdlib/llrt/llrt_encoding/
lib.rs1use std::borrow::Cow;
6
7use hex_simd::AsciiCase;
8
9#[derive(Clone, PartialEq)]
10pub enum Encoder {
11 Hex,
12 Base64,
13 Windows1252,
14 Utf8,
15 Utf16le,
16 Utf16be,
17}
18
19const ENCODING_MAP: phf::Map<&'static str, Encoder> = phf::phf_map! {
20 "buffer" => Encoder::Utf8,
21 "hex" => Encoder::Hex,
22 "base64" => Encoder::Base64,
23 "unicode-1-1-utf-8" => Encoder::Utf8,
24 "unicode11utf8" => Encoder::Utf8,
25 "unicode20utf8" => Encoder::Utf8,
26 "utf-8" => Encoder::Utf8,
27 "utf8" => Encoder::Utf8,
28 "x-unicode20utf8" => Encoder::Utf8,
29 "csunicode" => Encoder::Utf16le,
30 "iso-10646-ucs-2" => Encoder::Utf16le,
31 "ucs-2" => Encoder::Utf16le,
32 "ucs2" => Encoder::Utf16le,
33 "unicode" => Encoder::Utf16le,
34 "unicodefeff" => Encoder::Utf16le,
35 "utf-16" => Encoder::Utf16le,
36 "utf-16le" => Encoder::Utf16le,
37 "utf16le" => Encoder::Utf16le,
38 "unicodefffe" => Encoder::Utf16be,
39 "utf-16be" => Encoder::Utf16be,
40 "ansi_x3.4-1968" => Encoder::Windows1252,
41 "ascii" => Encoder::Windows1252,
42 "cp1252" => Encoder::Windows1252,
43 "cp819" => Encoder::Windows1252,
44 "csisolatin1" => Encoder::Windows1252,
45 "ibm819" => Encoder::Windows1252,
46 "iso-8859-1" => Encoder::Windows1252,
47 "iso-ir-100" => Encoder::Windows1252,
48 "iso8859-1" => Encoder::Windows1252,
49 "iso88591" => Encoder::Windows1252,
50 "iso_8859-1" => Encoder::Windows1252,
51 "iso_8859-1:1987" => Encoder::Windows1252,
52 "l1" => Encoder::Windows1252,
53 "latin1" => Encoder::Windows1252,
54 "us-ascii" => Encoder::Windows1252,
55 "windows-1252" => Encoder::Windows1252,
56 "x-cp1252" => Encoder::Windows1252,
57};
58
59impl Encoder {
60 pub fn from_optional_str(encoding: Option<&str>) -> Result<Self, String> {
61 encoding.map_or(Ok(Self::Utf8), Self::from_str)
62 }
63
64 #[allow(clippy::should_implement_trait)]
65 pub fn from_str(encoding: &str) -> Result<Self, String> {
66 ENCODING_MAP
67 .get(encoding.trim_ascii().to_ascii_lowercase().as_str())
68 .cloned()
69 .ok_or_else(|| ["The \"", encoding, "\" encoding is not supported"].concat())
70 }
71
72 pub fn encode_to_string(&self, bytes: &[u8], lossy: bool) -> Result<String, String> {
73 match self {
74 Self::Hex => Ok(bytes_to_hex_string(bytes)),
75 Self::Base64 => Ok(bytes_to_b64_string(bytes)),
76 Self::Utf8 => bytes_to_utf8_string(bytes, lossy),
77 Self::Windows1252 => Ok(bytes_to_windows1252_string(bytes)),
78 Self::Utf16le => bytes_to_utf16_string(bytes, Endian::Little, lossy),
79 Self::Utf16be => bytes_to_utf16_string(bytes, Endian::Big, lossy),
80 }
81 }
82
83 #[allow(dead_code)]
84 pub fn encode(&self, bytes: &[u8]) -> Result<Vec<u8>, String> {
85 match self {
86 Self::Hex => Ok(bytes_to_hex(bytes)),
87 Self::Base64 => Ok(bytes_to_b64(bytes)),
88 Self::Utf8 | Self::Windows1252 | Self::Utf16le | Self::Utf16be => Ok(bytes.to_vec()),
89 }
90 }
91
92 pub fn decode<'a, T: Into<Cow<'a, [u8]>>>(&self, bytes: T) -> Result<Vec<u8>, String> {
93 match self {
94 Self::Hex => bytes_from_hex(bytes),
95 Self::Base64 => bytes_from_b64(bytes),
96 Self::Utf8 | Self::Windows1252 | Self::Utf16le | Self::Utf16be => {
97 Ok(bytes.into().into())
98 }
99 }
100 }
101
102 pub fn decode_from_string(&self, string: String) -> Result<Vec<u8>, String> {
103 match self {
104 Self::Hex => bytes_from_hex(string.into_bytes()),
105 Self::Base64 => bytes_from_b64(string.into_bytes()),
106 Self::Utf8 | Self::Windows1252 => Ok(string.into_bytes()),
107 Self::Utf16le => Ok(string
108 .encode_utf16()
109 .flat_map(|utf16| utf16.to_le_bytes())
110 .collect::<Vec<u8>>()),
111 Self::Utf16be => Ok(string
112 .encode_utf16()
113 .flat_map(|utf16| utf16.to_be_bytes())
114 .collect::<Vec<u8>>()),
115 }
116 }
117
118 pub fn as_label(&self) -> &str {
119 match self {
120 Self::Hex => "hex",
121 Self::Base64 => "base64",
122 Self::Windows1252 => "windows-1252",
123 Self::Utf8 => "utf-8",
124 Self::Utf16le => "utf-16le",
125 Self::Utf16be => "utf-16be",
126 }
127 }
128}
129
130pub fn bytes_to_hex(bytes: &[u8]) -> Vec<u8> {
131 hex_simd::encode_type(bytes, AsciiCase::Lower)
132}
133
134pub fn bytes_from_hex<'a, T: Into<Cow<'a, [u8]>>>(hex_bytes: T) -> Result<Vec<u8>, String> {
135 hex_simd::decode_to_vec(hex_bytes.into()).map_err(|err| err.to_string())
136}
137
138pub fn bytes_from_b64<'a, T: Into<Cow<'a, [u8]>>>(base64_bytes: T) -> Result<Vec<u8>, String> {
139 let bytes: Cow<'a, [u8]> = base64_bytes.into();
140
141 let url_safe_byte_positions: Vec<usize> = memchr::memchr2_iter(b'-', b'_', &bytes).collect();
143
144 if url_safe_byte_positions.is_empty() {
145 return base64_simd::forgiving_decode_to_vec(&bytes).map_err(|e| e.to_string());
146 }
147
148 let mut bytes = bytes.into_owned();
150 for pos in url_safe_byte_positions {
151 bytes[pos] = match bytes[pos] {
152 b'-' => b'+',
153 b'_' => b'/',
154 _ => unreachable!(),
155 };
156 }
157 base64_simd::forgiving_decode_to_vec(&bytes).map_err(|e| e.to_string())
158}
159
160pub fn bytes_from_b64_strict(bytes: &[u8]) -> Result<Vec<u8>, String> {
163 base64_simd::STANDARD
164 .decode_to_vec(bytes)
165 .map_err(|e| e.to_string())
166}
167
168pub fn bytes_to_b64_string(bytes: &[u8]) -> String {
169 base64_simd::STANDARD.encode_to_string(bytes)
170}
171
172pub fn bytes_to_b64_url_safe_string(bytes: &[u8]) -> String {
173 base64_simd::URL_SAFE_NO_PAD.encode_to_string(bytes)
174}
175
176pub fn bytes_from_b64_url_safe(bytes: &[u8]) -> Result<Vec<u8>, String> {
177 base64_simd::URL_SAFE_NO_PAD
178 .decode_to_vec(bytes)
179 .map_err(|e| e.to_string())
180}
181
182pub fn bytes_to_b64(bytes: &[u8]) -> Vec<u8> {
183 base64_simd::STANDARD.encode_type(bytes)
184}
185
186pub fn bytes_to_hex_string(bytes: &[u8]) -> String {
187 hex_simd::encode_to_string(bytes, AsciiCase::Lower)
188}
189
190pub fn bytes_to_utf8_string(bytes: &[u8], lossy: bool) -> Result<String, String> {
191 if lossy {
192 Ok(String::from_utf8_lossy(bytes).to_string())
193 } else {
194 String::from_utf8(bytes.to_vec()).map_err(|e| e.to_string())
195 }
196}
197
198pub fn bytes_to_windows1252_string(bytes: &[u8]) -> String {
199 bytes.iter().map(|&byte| index_windows_1252(byte)).collect()
200}
201
202fn index_windows_1252(byte: u8) -> char {
204 match byte {
205 0x80 => '\u{20AC}',
206 0x82 => '\u{201A}',
207 0x83 => '\u{0192}',
208 0x84 => '\u{201E}',
209 0x85 => '\u{2026}',
210 0x86 => '\u{2020}',
211 0x87 => '\u{2021}',
212 0x88 => '\u{02C6}',
213 0x89 => '\u{2030}',
214 0x8A => '\u{0160}',
215 0x8B => '\u{2039}',
216 0x8C => '\u{0152}',
217 0x8E => '\u{017D}',
218 0x91 => '\u{2018}',
219 0x92 => '\u{2019}',
220 0x93 => '\u{201C}',
221 0x94 => '\u{201D}',
222 0x95 => '\u{2022}',
223 0x96 => '\u{2013}',
224 0x97 => '\u{2014}',
225 0x98 => '\u{02DC}',
226 0x99 => '\u{2122}',
227 0x9A => '\u{0161}',
228 0x9B => '\u{203A}',
229 0x9C => '\u{0153}',
230 0x9E => '\u{017E}',
231 0x9F => '\u{0178}',
232 _ => char::from(byte),
233 }
234}
235
236#[derive(Clone, Copy)]
237pub enum Endian {
238 Little,
239 Big,
240}
241
242pub fn bytes_to_utf16_string(bytes: &[u8], endian: Endian, lossy: bool) -> Result<String, String> {
243 if !lossy && !bytes.len().is_multiple_of(2) {
244 return Err("Input byte slice length must be even".to_string());
245 }
246
247 let data16: Vec<u16> = match endian {
248 Endian::Little => bytes
249 .as_chunks::<2>()
250 .0
251 .iter()
252 .copied()
253 .map(u16::from_le_bytes)
254 .collect(),
255 Endian::Big => bytes
256 .as_chunks::<2>()
257 .0
258 .iter()
259 .copied()
260 .map(u16::from_be_bytes)
261 .collect(),
262 };
263
264 let mut result = if lossy {
265 String::from_utf16_lossy(&data16)
266 } else {
267 String::from_utf16(&data16).map_err(|e| e.to_string())?
268 };
269
270 if lossy && !bytes.len().is_multiple_of(2) {
272 let last = data16.last().copied();
273 if !matches!(last, Some(0xD800..=0xDBFF)) {
274 result.push('\u{FFFD}');
275 }
276 }
277
278 Ok(result)
279}
280
281#[cfg(test)]
282mod tests {
283 use super::*;
284
285 #[test]
286 fn b64_strict_matches_smithy_semantics() {
287 assert_eq!(bytes_from_b64_strict(b"SGVsbG8=").unwrap(), b"Hello");
289 assert!(bytes_from_b64_strict(b"-_8=").is_err());
291 assert!(bytes_from_b64_strict(b"SGVs bG8=").is_err());
292 assert!(bytes_from_b64_strict(b"SGVsbG8").is_err());
293 }
294
295 #[test]
296 fn windows1252_decodes_special_bytes() {
297 assert_eq!(bytes_to_windows1252_string(&[0x80]), "€");
298 assert_eq!(bytes_to_windows1252_string(&[0x82]), "‚");
299 assert_eq!(bytes_to_windows1252_string(&[0x93]), "“");
300 assert_eq!(bytes_to_windows1252_string(&[0xFF]), "ÿ");
301 }
302}