1use alloc::{string::String, vec::Vec};
23
24pub use crate::charsets::Charset;
25pub use crate::decode::Decoder;
26pub use crate::multibyte::MultiByte;
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum Encoding {
32 Utf8,
33 Utf8Bom,
34 Utf16Le,
35 Utf16Be,
36}
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41#[non_exhaustive]
42pub enum Error {
43 Invalid,
44 Unsupported,
45 Limit,
46 Unmappable(char),
47}
48
49pub fn decode(bytes: &[u8], limit: usize) -> Result<(String, Encoding), Error> {
51 if bytes.len() > limit {
52 return Err(Error::Limit);
53 }
54 if bytes.starts_with(&[0xff, 0xfe, 0, 0]) || bytes.starts_with(&[0, 0, 0xfe, 0xff]) {
55 return Err(Error::Unsupported);
56 }
57 let (b, enc) = if bytes.starts_with(&[0xef, 0xbb, 0xbf]) {
58 (&bytes[3..], Encoding::Utf8Bom)
59 } else if bytes.starts_with(&[0xff, 0xfe]) {
60 (&bytes[2..], Encoding::Utf16Le)
61 } else if bytes.starts_with(&[0xfe, 0xff]) {
62 (&bytes[2..], Encoding::Utf16Be)
63 } else {
64 (bytes, Encoding::Utf8)
65 };
66 let text = match enc {
67 Encoding::Utf8 | Encoding::Utf8Bom => {
68 String::from(core::str::from_utf8(b).map_err(|_| Error::Invalid)?)
69 }
70 _ => {
71 if b.len() % 2 != 0 {
72 return Err(Error::Invalid);
73 }
74 let units = b.chunks_exact(2).map(|p| {
75 if enc == Encoding::Utf16Le {
76 u16::from_le_bytes([p[0], p[1]])
77 } else {
78 u16::from_be_bytes([p[0], p[1]])
79 }
80 });
81 let mut s = String::new();
82 for c in core::char::decode_utf16(units) {
83 s.push(c.map_err(|_| Error::Invalid)?);
84 }
85 s
86 }
87 };
88 if text.len() > limit {
89 return Err(Error::Limit);
90 }
91 Ok((text, enc))
92}
93
94pub fn encode(text: &str, enc: Encoding) -> Vec<u8> {
96 let mut out = Vec::new();
97 match enc {
98 Encoding::Utf8 => out.extend_from_slice(text.as_bytes()),
99 Encoding::Utf8Bom => {
100 out.extend_from_slice(&[0xef, 0xbb, 0xbf]);
101 out.extend_from_slice(text.as_bytes());
102 }
103 Encoding::Utf16Le | Encoding::Utf16Be => {
104 out.extend_from_slice(if enc == Encoding::Utf16Le {
105 &[0xff, 0xfe]
106 } else {
107 &[0xfe, 0xff]
108 });
109 for u in text.encode_utf16() {
110 out.extend_from_slice(&if enc == Encoding::Utf16Le {
111 u.to_le_bytes()
112 } else {
113 u.to_be_bytes()
114 });
115 }
116 }
117 }
118 out
119}
120
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123#[non_exhaustive]
124pub enum Label {
125 Utf8,
127 Utf16Le,
129 Utf16Be,
131 Single(Charset),
133 Multi(MultiByte),
135 Replacement,
138}
139
140impl Label {
141 pub const fn name(self) -> &'static str {
144 match self {
145 Label::Utf8 => "UTF-8",
146 Label::Utf16Le => "UTF-16LE",
147 Label::Utf16Be => "UTF-16BE",
148 Label::Single(c) => c.name(),
149 Label::Multi(m) => m.name(),
150 Label::Replacement => "replacement",
151 }
152 }
153}
154
155pub fn from_code_page(cp: u16) -> Option<Label> {
160 match cp {
161 65001 => Some(Label::Utf8),
162 1200 => Some(Label::Utf16Le),
163 1201 => Some(Label::Utf16Be),
164 _ => Charset::from_code_page(cp).map(Label::Single).or_else(|| MultiByte::from_code_page(cp).map(Label::Multi)),
165 }
166}
167
168pub fn label(name: &str) -> Option<Label> {
172 let t = name.trim_matches(|c| matches!(c, '\t' | '\n' | '\x0C' | '\r' | ' '));
173 if t.is_empty() || t.len() > 32 || !t.is_ascii() {
175 return None;
176 }
177 let mut buf = [0u8; 32];
178 for (d, s) in buf.iter_mut().zip(t.bytes()) {
179 *d = s.to_ascii_lowercase();
180 }
181 crate::charsets::lookup(core::str::from_utf8(&buf[..t.len()]).ok()?)
182}
183
184pub fn decode_label(label: &str, bytes: &[u8], limit: usize) -> Result<String, Error> {
188 if bytes.len() > limit {
189 return Err(Error::Limit);
190 }
191 let (named, body) = if let Some(rest) = bytes.strip_prefix(&[0xef, 0xbb, 0xbf]) {
192 (Some(Label::Utf8), rest)
193 } else if let Some(rest) = bytes.strip_prefix(&[0xff, 0xfe]) {
194 (Some(Label::Utf16Le), rest)
195 } else if let Some(rest) = bytes.strip_prefix(&[0xfe, 0xff]) {
196 (Some(Label::Utf16Be), rest)
197 } else {
198 (self::label(label), bytes)
199 };
200 let named = named.ok_or(Error::Unsupported)?;
201 let cap = if named == Label::Replacement { 0 } else { body.len().min(limit) + body.len().min(limit) / 2 };
203 let mut text = String::with_capacity(cap);
204 Decoder::new(named).decode(body, true, &mut text);
205 if text.len() > limit {
206 return Err(Error::Limit);
207 }
208 Ok(text)
209}
210
211impl Charset {
212 pub fn from_label(name: &str) -> Option<Charset> {
216 match label(name)? {
217 Label::Single(c) => Some(c),
218 _ => None,
219 }
220 }
221
222 pub fn decode(self, bytes: &[u8]) -> String {
224 if bytes.is_ascii() {
225 return String::from(core::str::from_utf8(bytes).unwrap_or(""));
226 }
227 let t = self.table();
228 let mut s = String::with_capacity(bytes.len() + bytes.len() / 2);
229 for &b in bytes {
230 s.push(if b < 0x80 { b as char } else { char_of(t[b as usize - 0x80]).unwrap_or(char::REPLACEMENT_CHARACTER) });
231 }
232 s
233 }
234
235 pub fn decode_char(self, b: u8) -> Option<char> {
237 if b < 0x80 {
238 Some(b as char)
239 } else {
240 char_of(self.table()[b as usize - 0x80])
241 }
242 }
243
244 pub fn encode_char(self, c: char) -> Option<u8> {
246 let u = c as u32;
247 if u < 0x80 {
248 return Some(u as u8);
249 }
250 self.table().iter().position(|&v| v != 0 && v as u32 == u).map(|i| 0x80 + i as u8)
251 }
252
253 pub fn encode(self, text: &str) -> Result<Vec<u8>, Error> {
255 let mut out = Vec::with_capacity(text.len());
256 for c in text.chars() {
257 out.push(self.encode_char(c).ok_or(Error::Unmappable(c))?);
258 }
259 Ok(out)
260 }
261}
262
263fn char_of(v: u16) -> Option<char> {
264 if v == 0 {
265 None
266 } else {
267 char::from_u32(v as u32)
268 }
269}