Skip to main content

satx_core/
names.rs

1//! Variable names to file names and back, and what a file holds
2//! (`kb/docs/saturnus-tx.md`, "File names"). The satx CLI and saturnus-tx
3//! (the web page, the desktop app) name files the same way.
4//!
5//! A variable becomes `NAME.hp` (a binary transfer file) or `NAME.txt`
6//! (the calculator's text form). Names arrive from `satx-core` in Unicode
7//! (`→`, `α`, `Σ`: its `charset`), which every file system takes; the few
8//! characters a file system refuses (`/ \ : * ? " < > |`), control
9//! characters, `%` itself and a trailing dot or space (Windows drops
10//! those) are written `%XX`, one per UTF-8 byte, and read back the same
11//! way. So is the first letter of a name Windows reserves for a device
12//! (`CON`, `PRN`, `AUX`, `NUL`, `COM1`-`COM9`, `LPT1`-`LPT9`, `COM¹`-`COM³`,
13//! `LPT¹`-`LPT³`, in any case,
14//! before the first dot): `AUX` becomes `%41UX.hp`. A file name goes back
15//! to a variable name without its extension.
16//!
17//! Names are kept as they are, case included. The calculator tells `A`
18//! from `a`; a case-insensitive file system (Windows, macOS by default)
19//! does not, so `A.hp` and `a.hp` collide in one folder: whoever writes
20//! files into a folder has to check for that.
21
22use crate::Model;
23use crate::error::{Error, Result};
24use crate::object::{AsciiHeader, BinaryHeader};
25
26/// How a variable is got.
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum Format {
29    /// An exact copy: a binary transfer file (`NAME.hp`).
30    Binary,
31    /// The calculator's text form (`NAME.txt`, flag -35 clear for the one
32    /// transfer).
33    Text,
34}
35
36/// What a file holds, as a put sends it.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum FileKind {
39    /// A binary transfer file (`HPHP48-x` or `HPHP49-x` header): sent as
40    /// is, in binary mode.
41    Binary,
42    /// The calculator's text form (`%%HP:` header): sent in text mode, the
43    /// calculator compiles it.
44    Text,
45    /// Anything else: the calculator stores it as a string.
46    Other,
47}
48
49impl FileKind {
50    /// What `data` holds, by its header.
51    pub fn of(data: &[u8]) -> FileKind {
52        if BinaryHeader::parse(data).is_some() {
53            FileKind::Binary
54        } else if AsciiHeader::parse(data).is_some() {
55            FileKind::Text
56        } else {
57            FileKind::Other
58        }
59    }
60}
61
62/// The file name of variable `name` got in `format`: `NAME.hp` or
63/// `NAME.txt`.
64pub fn file_name(name: &str, format: Format) -> String {
65    let extension = match format {
66        Format::Binary => "hp",
67        Format::Text => "txt",
68    };
69    format!("{}.{extension}", escape(name))
70}
71
72/// The variable name a put takes from `file_name`: without its extension
73/// (the last `.` and what follows, unless the name starts there), `%XX`
74/// read back; [`Error::FileName`] when that is not UTF-8.
75pub fn var_name(file_name: &str) -> Result<String> {
76    let stem = match file_name.rfind('.') {
77        Some(dot) if dot > 0 => &file_name[..dot],
78        _ => file_name,
79    };
80    unescape(stem).ok_or_else(|| Error::FileName(file_name.to_string()))
81}
82
83/// The folder name of directory `name` (`%XX` as in [`file_name`], no
84/// extension).
85pub fn folder_name(name: &str) -> String {
86    escape(name)
87}
88
89/// The directory name a folder named `folder` becomes: `%XX` read back,
90/// the whole name kept (a dot in it is no extension);
91/// [`Error::FileName`] when that is not UTF-8.
92pub fn dir_name(folder: &str) -> Result<String> {
93    unescape(folder).ok_or_else(|| Error::FileName(folder.to_string()))
94}
95
96/// The name of a backup file: the model, `backup`, the date and the time,
97/// `48GX-backup-2026-10-10-1432.hp`.
98pub fn backup_file_name(
99    model: Model,
100    year: u16,
101    month: u8,
102    day: u8,
103    hour: u8,
104    minute: u8,
105) -> String {
106    let model = match model {
107        Model::Hp48Sx => "48SX",
108        Model::Hp48Gx => "48GX",
109        Model::Hp49G => "49G",
110        _ => "HP",
111    };
112    format!("{model}-backup-{year:04}-{month:02}-{day:02}-{hour:02}{minute:02}.hp")
113}
114
115/// Whether Windows reserves `name` (its part before the first dot) for a
116/// device.
117fn reserved_on_windows(name: &str) -> bool {
118    let base = name
119        .split('.')
120        .next()
121        .unwrap_or_default()
122        .to_ascii_uppercase();
123    match base.as_str() {
124        "CON" | "PRN" | "AUX" | "NUL" => true,
125        _ => {
126            let digit = |prefix: &str| {
127                // 1 to 9, or the superscripts ¹ ² ³ Windows also reserves.
128                base.strip_prefix(prefix).is_some_and(|d| {
129                    let mut c = d.chars();
130                    matches!(
131                        (c.next(), c.next()),
132                        (Some('1'..='9' | '¹' | '²' | '³'), None)
133                    )
134                })
135            };
136            digit("COM") || digit("LPT")
137        }
138    }
139}
140
141/// `name` with what a file system refuses written `%XX`.
142pub fn escape(name: &str) -> String {
143    let refused = |c: char| {
144        c.is_control()
145            || matches!(
146                c,
147                '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' | '%'
148            )
149    };
150    let last = name.chars().count().saturating_sub(1);
151    let reserved = reserved_on_windows(name);
152    let mut out = String::with_capacity(name.len());
153    for (i, c) in name.chars().enumerate() {
154        if refused(c) || (i == last && matches!(c, '.' | ' ')) || (i == 0 && reserved) {
155            let mut buf = [0u8; 4];
156            for b in c.encode_utf8(&mut buf).bytes() {
157                out.push_str(&format!("%{b:02X}"));
158            }
159        } else {
160            out.push(c);
161        }
162    }
163    out
164}
165
166/// `%XX` (two hex digits) read back as the byte; any other `%` stays.
167/// `None` when the bytes are not UTF-8.
168pub fn unescape(name: &str) -> Option<String> {
169    let bytes = name.as_bytes();
170    let mut out = Vec::with_capacity(bytes.len());
171    let mut i = 0;
172    while let Some(&b) = bytes.get(i) {
173        let hex = bytes
174            .get(i + 1..i + 3)
175            .and_then(|h| std::str::from_utf8(h).ok())
176            .filter(|h| h.bytes().all(|d| d.is_ascii_hexdigit()))
177            .and_then(|h| u8::from_str_radix(h, 16).ok());
178        match (b, hex) {
179            (b'%', Some(byte)) => {
180                out.push(byte);
181                i += 3;
182            }
183            _ => {
184                out.push(b);
185                i += 1;
186            }
187        }
188    }
189    String::from_utf8(out).ok()
190}
191
192#[cfg(test)]
193#[allow(clippy::unwrap_used)]
194mod tests {
195    use super::*;
196
197    #[test]
198    fn unicode_names_stay_as_they_are() {
199        assert_eq!(file_name("A→B", Format::Binary), "A→B.hp");
200        assert_eq!(file_name("Σx²", Format::Text), "Σx².txt");
201        assert_eq!(var_name("A→B.hp").unwrap(), "A→B");
202        assert_eq!(var_name("αβ.txt").unwrap(), "αβ");
203    }
204
205    #[test]
206    fn refused_characters_round_trip_as_percent_codes() {
207        for name in ["A?B", "X|Y", "50%", "DOT.", "P*Q", "a\"b", "c:d", "x\u{1}"] {
208            let file = file_name(name, Format::Binary);
209            assert!(
210                !file[..file.len() - 3].contains(['?', '|', '*', '"', ':', '\u{1}']),
211                "{file}"
212            );
213            assert_eq!(var_name(&file).unwrap(), name, "{file}");
214        }
215        assert_eq!(escape("50%"), "50%25");
216        assert_eq!(escape("DOT."), "DOT%2E");
217        assert_eq!(escape("A.B"), "A.B");
218    }
219
220    #[test]
221    fn a_put_takes_the_name_without_the_extension() {
222        assert_eq!(var_name("NOTES.md").unwrap(), "NOTES");
223        assert_eq!(var_name("A.B.hp").unwrap(), "A.B");
224        assert_eq!(var_name("PLAIN").unwrap(), "PLAIN");
225        assert_eq!(var_name(".hidden").unwrap(), ".hidden");
226        // A stray `%` stays; a lowercase hex code reads back too.
227        assert_eq!(var_name("5%X.txt").unwrap(), "5%X");
228        assert_eq!(var_name("a%3fb.hp").unwrap(), "a?b");
229    }
230
231    #[test]
232    fn windows_device_names_are_escaped() {
233        for (name, file) in [
234            ("AUX", "%41UX.hp"),
235            ("con", "%63on.hp"),
236            ("Nul", "%4Eul.hp"),
237            ("COM1", "%43OM1.hp"),
238            ("lpt9", "%6Cpt9.hp"),
239            ("CON.X", "%43ON.X.hp"),
240            ("COM²", "%43OM².hp"),
241            ("lpt¹", "%6Cpt¹.hp"),
242        ] {
243            assert_eq!(file_name(name, Format::Binary), file);
244            assert_eq!(var_name(file).unwrap(), name);
245        }
246        for name in ["COM", "COM0", "COM10", "LPT", "CONS", "AUXB", "XCON"] {
247            assert_eq!(escape(name), name);
248        }
249    }
250
251    #[test]
252    fn a_percent_without_two_hex_digits_stays() {
253        // `%e` at the end has one digit only: no escape, kept as it is.
254        assert_eq!(var_name("tax%e.hp").unwrap(), "tax%e");
255        assert_eq!(unescape("tax%e"), Some("tax%e".to_string()));
256        assert_eq!(unescape("50%"), Some("50%".to_string()));
257    }
258
259    #[test]
260    fn percent_codes_that_are_not_utf8_are_refused() {
261        assert!(matches!(var_name("%FF.hp"), Err(Error::FileName(n)) if n == "%FF.hp"));
262        assert!(matches!(var_name("A%E2%86.hp"), Err(Error::FileName(_))));
263        assert_eq!(unescape("%E2%86%92"), Some("→".to_string()));
264    }
265
266    #[test]
267    fn folders_keep_their_dots_and_backups_their_model() {
268        assert_eq!(folder_name("A/B"), "A%2FB");
269        assert_eq!(dir_name("A.B").unwrap(), "A.B");
270        assert_eq!(dir_name("A%2FB").unwrap(), "A/B");
271        assert!(dir_name("%FF").is_err());
272        assert_eq!(
273            backup_file_name(Model::Hp48Gx, 2026, 10, 10, 14, 32),
274            "48GX-backup-2026-10-10-1432.hp"
275        );
276        assert_eq!(
277            backup_file_name(Model::Hp49G, 2026, 1, 2, 3, 4),
278            "49G-backup-2026-01-02-0304.hp"
279        );
280    }
281
282    #[test]
283    fn file_kinds_by_header() {
284        assert_eq!(FileKind::of(b"HPHP48-R\x2c\x2a"), FileKind::Binary);
285        assert_eq!(FileKind::of(b"HPHP49-C\x2c\x2a"), FileKind::Binary);
286        assert_eq!(
287            FileKind::of(b"%%HP: T(3)A(R)F(.);\r\n\"hi\""),
288            FileKind::Text
289        );
290        assert_eq!(FileKind::of(b"hello"), FileKind::Other);
291        assert_eq!(FileKind::of(b""), FileKind::Other);
292    }
293}