Debian Codegraph @

rust/hg-core/src/encoding.rs

raw
1 //! Character transcoding support.
2
3 use core::str;
4 use std::borrow::Cow;
5
6 use unicode_width::UnicodeWidthStr as _;
7
8 use crate::errors::HgError;
9 use crate::utils::strings::Escaped;
10
11 /// String encoder and decoder.
12 #[derive(Copy, Clone, Debug)]
13 pub struct Encoder {
14 /// The user's local encoding.
15 local_encoding: Encoding,
16 /// What to do when decoding fails. (Encoding always uses
17 /// `Mode::Replace`).
18 decoding_mode: Mode,
19 /// Width to use for characters that can be interpreted either as narrow
20 /// or wide depending on the context.
21 pub ambiguous_width: Width,
22 }
23
24 /// Character encoding.
25 #[derive(Copy, Clone, Debug)]
26 pub enum Encoding {
27 Utf8,
28 Ascii,
29 }
30
31 /// Character decoding mode.
32 #[derive(Copy, Clone, Debug)]
33 pub enum Mode {
34 /// Produce an error message for invalid characters.
35 Strict,
36 /// Replace invalid characters with a special character.
37 Replace,
38 }
39
40 /// The width of a Unicode character.
41 #[derive(Copy, Clone, Debug)]
42 pub enum Width {
43 /// Narrow, taking up 1 terminal column.
44 Narrow,
45 /// Wide, taking up 2 terminal columns.
46 Wide,
47 }
48
49 impl Default for Encoder {
50 fn default() -> Self {
51 Self {
52 local_encoding: Encoding::Utf8,
53 decoding_mode: Mode::Strict,
54 ambiguous_width: Width::Narrow,
55 }
56 }
57 }
58
59 impl Encoder {
60 /// Creates an encoder from environment variables.
61 pub fn from_env() -> Result<Self, HgError> {
62 let default = Encoder::default();
63 let local_encoding = match std::env::var_os("HGENCODING") {
64 None => default.local_encoding,
65 Some(s)
66 if s.eq_ignore_ascii_case("utf-8")
67 || s.eq_ignore_ascii_case("utf8") =>
68 {
69 Encoding::Utf8
70 }
71 Some(s) if s.eq_ignore_ascii_case("ascii") => Encoding::Ascii,
72 Some(s) => {
73 return Err(HgError::unsupported(format!(
74 "HGENCODING value '{}' is not supported",
75 s.to_string_lossy()
76 )))
77 }
78 };
79 let decoding_mode = match std::env::var_os("HGENCODINGMODE") {
80 None => default.decoding_mode,
81 Some(s) if s == "strict" => Mode::Strict,
82 Some(s) if s == "replace" => Mode::Replace,
83 Some(s) => {
84 return Err(HgError::abort_simple(format!(
85 "HGENCODINGMODE value '{}' is not supported",
86 s.to_string_lossy()
87 )))
88 }
89 };
90 let ambiguous_width = match std::env::var_os("HGENCODINGAMBIGUOUS") {
91 None => default.ambiguous_width,
92 Some(s) if s == "narrow" => Width::Narrow,
93 Some(s) if s == "wide" => Width::Wide,
94 Some(s) => {
95 return Err(HgError::abort_simple(format!(
96 "HGENCODINGAMBIGUOUS value '{}' is not supported",
97 s.to_string_lossy()
98 )))
99 }
100 };
101 Ok(Self { local_encoding, decoding_mode, ambiguous_width })
102 }
103
104 /// Decodes an internal UTF-8 string from bytes.
105 pub fn decode_internal<'a>(
106 &self,
107 bytes: &'a [u8],
108 ) -> Result<&'a str, HgError> {
109 decode_utf8(bytes).map_err(HgError::corrupted)
110 }
111
112 /// Converts a string from internal UTF-8 to the local character encoding.
113 pub fn to_local<'a>(&self, str: &'a str) -> Cow<'a, [u8]> {
114 match self.local_encoding {
115 Encoding::Utf8 => Cow::Borrowed(str.as_bytes()),
116 Encoding::Ascii => {
117 if str.is_ascii() {
118 Cow::Borrowed(str.as_bytes())
119 } else {
120 Cow::Owned(codepoints_to_ascii_lossy(str).into_bytes())
121 }
122 }
123 }
124 }
125
126 /// Converts a string from the local character encoding to UTF-8.
127 pub fn from_local<'a>(
128 &self,
129 bytes: &'a [u8],
130 ) -> Result<Cow<'a, str>, HgError> {
131 match (self.local_encoding, self.decoding_mode) {
132 (Encoding::Utf8, Mode::Strict) => Ok(Cow::Borrowed(
133 decode_utf8(bytes).map_err(HgError::abort_simple)?,
134 )),
135 (Encoding::Utf8, Mode::Replace) => {
136 Ok(String::from_utf8_lossy(bytes))
137 }
138 (Encoding::Ascii, Mode::Strict) => Ok(Cow::Borrowed(
139 decode_ascii(bytes).map_err(HgError::abort_simple)?,
140 )),
141 (Encoding::Ascii, Mode::Replace) => {
142 Ok(Cow::Owned(bytes_to_ascii_lossy(bytes)))
143 }
144 }
145 }
146
147 /// Returns the column width of a string for display.
148 pub fn column_width(&self, str: &str) -> usize {
149 match self.ambiguous_width {
150 Width::Narrow => str.width(),
151 Width::Wide => str.width_cjk(),
152 }
153 }
154
155 /// Returns the column width if `bytes` can be decoded as UTF-8, otherwise
156 /// just returns the length in bytes.
157 pub fn column_width_bytes(&self, bytes: &[u8]) -> usize {
158 match str::from_utf8(bytes) {
159 Ok(str) => self.column_width(str),
160 Err(_) => bytes.len(),
161 }
162 }
163 }
164
165 /// Decodes bytes as UTF-8 or returns a detailed error message.
166 fn decode_utf8(bytes: &[u8]) -> Result<&str, String> {
167 str::from_utf8(bytes).map_err(|err| {
168 format!(
169 "invalid UTF-8 at offset {}: \"{}\"",
170 err.valid_up_to(),
171 str::from_utf8(&bytes.escaped_bytes()).unwrap()
172 )
173 })
174 }
175
176 /// Decodes bytes as ASCII or returns a detailed error message.
177 fn decode_ascii(bytes: &[u8]) -> Result<&str, String> {
178 // TODO: Use `as_ascii` https://github.com/rust-lang/rust/issues/110998
179 if bytes.is_ascii() {
180 // Safety: Just checked that it's ASCII.
181 let str = unsafe { str::from_utf8_unchecked(bytes) };
182 Ok(str)
183 } else {
184 Err(format!(
185 "invalid ASCII: \"{}\"",
186 str::from_utf8(&bytes.escaped_bytes()).unwrap()
187 ))
188 }
189 }
190
191 /// Replaces all non-ASCII codepoints with '?'.
192 fn codepoints_to_ascii_lossy(str: &str) -> String {
193 let mut ascii = String::new();
194 for char in str.chars() {
195 ascii.push(if char.is_ascii() { char } else { '?' });
196 }
197 ascii
198 }
199
200 /// Replaces all non-ASCII bytes with '?'.
201 fn bytes_to_ascii_lossy(bytes: &[u8]) -> String {
202 let mut ascii = String::new();
203 for &b in bytes {
204 ascii.push(if b.is_ascii() { b as char } else { '?' });
205 }
206 ascii
207 }
208
209 #[cfg(test)]
210 mod tests {
211 use super::*;
212
213 #[test]
214 fn test_decode_internal() {
215 let encoder = Encoder::default();
216 assert_eq!(encoder.decode_internal(b"").unwrap(), "");
217 assert_eq!(encoder.decode_internal(b"\xc3\xa9").unwrap(), "é");
218 match encoder.decode_internal(b"A\xc3") {
219 Ok(_) => panic!("expected an error"),
220 Err(HgError::CorruptedRepository(message, ..)) => {
221 assert_eq!(message, "invalid UTF-8 at offset 1: \"A\\xc3\"")
222 }
223 Err(_) => panic!("expected a CorruptedRepository error"),
224 }
225 }
226
227 #[test]
228 fn test_to_local() {
229 let encoder = Encoder::default();
230 assert_eq!(encoder.to_local("").as_ref(), b"");
231 assert_eq!(encoder.to_local("é").as_ref(), b"\xc3\xa9");
232 }
233
234 #[test]
235 fn test_from_local() {
236 let encoder = Encoder::default();
237 assert_eq!(encoder.from_local(b"").unwrap(), "");
238 assert_eq!(encoder.from_local(b"\xc3\xa9").unwrap(), "é");
239 match encoder.from_local(b"A\xc3") {
240 Ok(_) => panic!("expected an error"),
241 Err(HgError::Abort { message, .. }) => {
242 assert_eq!(message, "invalid UTF-8 at offset 1: \"A\\xc3\"")
243 }
244 Err(_) => panic!("expected a CorruptedRepository error"),
245 }
246 }
247
248 #[test]
249 fn test_from_local_replace() {
250 let encoder =
251 Encoder { decoding_mode: Mode::Replace, ..Default::default() };
252 assert_eq!(encoder.from_local(b"A\xc3").unwrap(), "A\u{fffd}");
253 }
254
255 #[test]
256 fn test_column_width() {
257 let encoder = Encoder::default();
258 assert_eq!(encoder.column_width(""), 0);
259 assert_eq!(encoder.column_width("a"), 1);
260 assert_eq!(encoder.column_width("ab"), 2);
261 assert_eq!(encoder.column_width("été"), 3);
262 assert_eq!(encoder.column_width("\u{1f496}"), 2);
263 }
264
265 #[test]
266 fn test_column_width_ambiguous() {
267 let narrow_encoder =
268 Encoder { ambiguous_width: Width::Narrow, ..Default::default() };
269 assert_eq!(narrow_encoder.column_width("\u{2606}"), 1);
270
271 let wide_encoder =
272 Encoder { ambiguous_width: Width::Wide, ..Default::default() };
273 assert_eq!(wide_encoder.column_width("\u{2606}"), 2);
274 }
275
276 #[test]
277 fn test_column_width_bytes() {
278 let encoder = Encoder::default();
279 assert_eq!(encoder.column_width_bytes(b""), 0);
280 assert_eq!(encoder.column_width_bytes("été".as_bytes()), 3);
281 assert_eq!(encoder.column_width_bytes(b"A\xc3"), 2);
282 }
283 }