1pub fn len(text: &str) -> usize {
7 text.encode_utf16().count()
8}
9
10pub fn utf16_index(text: &str, byte: usize) -> usize {
13 len(&text[..text.floor_char_boundary(byte)])
14}
15
16pub fn byte_index(text: &str, units: usize) -> usize {
19 let mut count = 0;
20 for (index, c) in text.char_indices() {
21 if count >= units {
22 return index;
23 }
24 count += c.len_utf16();
25 }
26 text.len()
27}
28
29pub fn slice(text: &str, start: usize, end: usize) -> String {
32 let units: Vec<u16> = text.encode_utf16().collect();
33 let end = end.min(units.len());
34 let start = start.min(end);
35 String::from_utf16_lossy(&units[start..end])
36}
37
38pub fn decode_utf8_stream(pending: &mut Vec<u8>, bytes: &[u8]) -> String {
42 pending.extend_from_slice(bytes);
43 let valid = match std::str::from_utf8(pending) {
44 Ok(text) => text.len(),
45 Err(error) if error.error_len().is_none() => error.valid_up_to(),
46 Err(_) => pending.len(),
47 };
48 let text = String::from_utf8_lossy(&pending[..valid]).into_owned();
49 pending.drain(..valid);
50 text
51}
52
53pub fn round(value: f64) -> f64 {
55 (value + 0.5).floor()
56}
57
58pub fn to_fixed(value: f64, digits: usize) -> String {
60 if !value.is_finite() {
61 return value.to_string();
62 }
63 if value < 0.0 {
64 let positive = to_fixed(-value, digits);
65 return if positive.bytes().all(|byte| matches!(byte, b'0' | b'.')) {
66 positive
67 } else {
68 format!("-{positive}")
69 };
70 }
71 let wide = format!("{value:.40}");
72 let (whole, fraction) = wide.split_once('.').unwrap_or((&wide, ""));
73 let mut number: Vec<u8> = whole
74 .bytes()
75 .chain(fraction.bytes().chain(std::iter::repeat(b'0')).take(digits))
76 .collect();
77 if fraction
78 .as_bytes()
79 .get(digits)
80 .is_some_and(|digit| *digit >= b'5')
81 {
82 let mut index = number.len();
83 loop {
84 if index == 0 {
85 number.insert(0, b'1');
86 break;
87 }
88 index -= 1;
89 if number[index] == b'9' {
90 number[index] = b'0';
91 } else {
92 number[index] += 1;
93 break;
94 }
95 }
96 }
97 let text = String::from_utf8_lossy(&number).into_owned();
98 if digits == 0 {
99 return text;
100 }
101 let split = text.len() - digits;
102 format!("{}.{}", &text[..split], &text[split..])
103}
104
105pub fn errno(kind: std::io::ErrorKind) -> Option<(&'static str, &'static str)> {
108 use std::io::ErrorKind;
109 Some(match kind {
110 ErrorKind::NotFound => ("ENOENT", "no such file or directory"),
111 ErrorKind::PermissionDenied => ("EACCES", "permission denied"),
112 ErrorKind::AlreadyExists => ("EEXIST", "file already exists"),
113 ErrorKind::IsADirectory => ("EISDIR", "illegal operation on a directory"),
114 ErrorKind::NotADirectory => ("ENOTDIR", "not a directory"),
115 _ => return None,
116 })
117}
118
119pub fn node_error(err: &std::io::Error, syscall: &str, path: &std::path::Path) -> String {
122 let path = path.display();
123 match errno(err.kind()) {
124 Some(("EISDIR", text)) if syscall == "read" => format!("EISDIR: {text}, read"),
126 Some((code, text)) => format!("{code}: {text}, {syscall} '{path}'"),
127 None => format!("{err}, {syscall} '{path}'"),
128 }
129}
130
131#[cfg(test)]
132mod tests {
133 use super::*;
134
135 #[test]
136 fn indices_convert_between_bytes_and_utf16() {
137 let text = "é😀x";
138 assert_eq!(utf16_index(text, 2), 1);
139 assert_eq!(utf16_index(text, 6), 3);
140 assert_eq!(byte_index(text, 3), 6);
141 assert_eq!(byte_index(text, 9), text.len());
142 }
143
144 #[test]
145 fn words_io_errors_as_node() {
146 let error = |kind| std::io::Error::from(kind);
147 let path = std::path::Path::new("/a/b");
148 assert_eq!(
149 node_error(&error(std::io::ErrorKind::NotFound), "open", path),
150 "ENOENT: no such file or directory, open '/a/b'"
151 );
152 assert_eq!(
153 node_error(&error(std::io::ErrorKind::IsADirectory), "read", path),
154 "EISDIR: illegal operation on a directory, read"
155 );
156 assert_eq!(
157 node_error(&error(std::io::ErrorKind::AlreadyExists), "mkdir", path),
158 "EEXIST: file already exists, mkdir '/a/b'"
159 );
160 assert_eq!(errno(std::io::ErrorKind::Other), None);
161 }
162
163 #[test]
164 fn counts_and_slices_utf16_units() {
165 assert_eq!(len("a😀"), 3);
166 assert_eq!(slice("a😀b", 0, 3), "a😀");
167 assert_eq!(slice("a😀b", 0, 2), "a\u{fffd}");
168 assert_eq!(slice("abc", 2, 10), "c");
169 }
170
171 #[test]
172 fn decodes_utf8_streams() {
173 let mut pending = Vec::new();
174 let euro = "€".as_bytes();
175 assert_eq!(decode_utf8_stream(&mut pending, &euro[..2]), "");
176 assert_eq!(decode_utf8_stream(&mut pending, &euro[2..]), "€");
177 assert_eq!(decode_utf8_stream(&mut pending, b"a\xffb"), "a\u{fffd}b");
178 assert!(pending.is_empty());
179 }
180
181 #[test]
182 fn rounds_like_javascript() {
183 assert_eq!(to_fixed(0.05, 1), "0.1");
184 assert_eq!(to_fixed(1.25, 1), "1.3");
185 assert_eq!(to_fixed(1.005, 2), "1.00");
186 assert_eq!(to_fixed(9.96, 1), "10.0");
187 assert_eq!(to_fixed(0.0, 1), "0.0");
188 assert_eq!(to_fixed(2.5, 0), "3");
189 assert_eq!(to_fixed(-1.25, 1), "-1.3");
190 assert_eq!(round(2.5), 3.0);
191 assert_eq!(round(-2.5), -2.0);
192 }
193}