normalized_path/lib.rs
1//! Opinionated cross-platform, optionally case-insensitive path normalization.
2//!
3//! This crate provides [`PathElementCS`] (case-sensitive), [`PathElementCI`]
4//! (case-insensitive), and [`PathElement`] (runtime-selected) -- types that take a
5//! raw path element name, validate it, normalize it to a canonical form, and compute
6//! an OS-compatible presentation form.
7//!
8//! # Design goals and non-goals
9//!
10//! **Goals:**
11//!
12//! - The normalization procedure is identical on every platform -- the same input
13//! always produces the same normalized bytes regardless of the host OS.
14//! - If any supported OS considers two names equivalent (e.g. NFC vs NFD on macOS),
15//! they must normalize to the same value.
16//! - The normalized form is always in NFC (Unicode Normalization Form C), the
17//! most widely used and compact canonical form.
18//! - Normalization is idempotent: normalizing an already-normalized name always
19//! produces the same name unchanged.
20//! - The OS-compatible form of a name, when normalized again, produces the same
21//! normalized value as the original input (round-trip stability).
22//! - Every valid name is representable on every supported OS. Characters that
23//! would be rejected or silently altered (Windows forbidden characters, C0 controls)
24//! are mapped to visually similar safe alternatives.
25//! - If the OS automatically transforms a name (e.g. NFC↔NFD conversion,
26//! truncation at null bytes), normalizing the transformed name produces the
27//! same result as normalizing the original.
28//! - In case-insensitive mode, names differing only in case normalize identically,
29//! including edge cases from Turkish/Azerbaijani and Lithuanian casing rules
30//! (see step 9 below).
31//!
32//! **Non-goals:**
33//!
34//! - Not every name that a particular OS accepts is considered valid. Non-UTF-8
35//! byte sequences, names that normalize to empty (e.g. whitespace-only), and
36//! names that normalize to `.` or `..` (e.g. `" .. "`) are always rejected.
37//! - A name taken directly from the OS may produce a different OS-compatible form
38//! after normalization. For example, a file named `" hello.txt"` (leading space)
39//! will have the space trimmed, so its OS-compatible form is `"hello.txt"`.
40//! - The OS-compatible form is not guaranteed to be accepted by the OS. For
41//! example, it may exceed the OS's path element length limit, or on Apple
42//! platforms the filesystem may require names in Unicode Stream-Safe Text Format
43//! which the OS-compatible form does not enforce.
44//! - Windows 8.3 short file names (e.g. `PROGRA~1`) are not handled.
45//! - Visually similar names are not necessarily considered equal. For example,
46//! a regular space (U+0020) and a non-breaking space (U+00A0) produce different
47//! normalized forms despite looking identical, and the ligature `fi` (U+FB01) is
48//! distinct from the two-character sequence `fi`.
49//! - Fullwidth and ASCII variants of the same character (e.g. `A` vs `A`) are
50//! deliberately normalized to the same form. Users who need to distinguish
51//! them cannot use this crate.
52//! - In case-insensitive mode, Turkish İ (U+0130), dotless ı (U+0131), and
53//! ASCII I/i are all deliberately normalized to the same form. Users who
54//! need to distinguish them cannot use case-insensitive mode.
55//! - Invalid UTF-8 byte sequences in `from_bytes`/`from_os_str` are rejected.
56//! - Names containing unassigned Unicode code points are rejected. This makes it
57//! much more likely that normalization results for accepted names remain stable
58//! when upgrading to a future Unicode version (see [Unicode version](#unicode-version)).
59//! - Path separators and multi-component paths are not handled. This crate
60//! operates on a single path element (one name between separators). Support
61//! for full paths may be added in a future version.
62//! - Android versions before 6 (API level 23) are not supported. Earlier
63//! versions used Java Modified UTF-8 for filesystem paths, encoding
64//! supplementary characters as CESU-8 surrogate pairs.
65//!
66//! # Normalization pipeline
67//!
68//! Every path element name goes through the following steps during construction:
69//!
70//! 0. **UTF-8 validation** (only for `from_bytes`/`from_os_str`) --
71//! the input must be valid UTF-8; invalid byte sequences are rejected with
72//! [`ErrorKind::InvalidUtf8`].
73//!
74//! 1. **NFD decomposition** -- canonical decomposition to reorder combining marks.
75//! This is needed because macOS stores filenames in a form close to NFD, so an
76//! NFD input and an NFC input must produce the same result. Decomposing first
77//! ensures combining marks are in canonical order before subsequent steps.
78//!
79//! 2. **Whitespace trimming** -- strips leading and trailing characters with the Unicode
80//! `White_Space` property, plus the BOM (U+FEFF) and Control Pictures that correspond
81//! to whitespace control characters (U+2409--U+240D: HT, LF, VT, FF, CR).
82//! Many applications strip leading/trailing whitespace silently, and macOS
83//! automatically strips leading BOMs. Control Pictures are
84//! included because they are the mapped form of whitespace control characters
85//! (see step 4), so trimming must be consistent before and after mapping.
86//!
87//! 3. **Fullwidth-to-ASCII mapping** -- maps fullwidth forms (U+FF01--U+FF5E) to their
88//! ASCII equivalents (U+0021--U+007E). The Windows OS-compatibility step (see below)
89//! maps certain ASCII characters to fullwidth to avoid Windows restrictions. This
90//! step ensures that the OS-compatible form normalizes back to the same value.
91//!
92//! 4. **Control character mapping** -- maps C0 controls (U+0001--U+001F) and DEL (U+007F)
93//! to their Unicode Control Picture equivalents (U+2401--U+241F, U+2421). Control
94//! characters are invisible, can break terminals and tools, and some OSes reject
95//! or silently drop them. Mapping to visible Control Pictures preserves the
96//! information while making the name safe. (Null bytes are excluded — see step 5.)
97//!
98//! 5. **Validation** -- rejects empty strings, `.`, `..`, names containing `/`,
99//! names containing null bytes (`\0`), and names containing unassigned Unicode
100//! characters. The first group is universally special on all OSes and cannot be
101//! used as regular names. Unassigned characters are rejected to ensure
102//! normalization stability across Unicode versions (see
103//! [Unicode stability policies](#unicode-stability-policies)).
104//!
105//! 6. **NFC composition** -- canonical composition to produce the shortest equivalent
106//! form.
107//!
108//! In **case-insensitive** mode, four additional steps are applied after the above:
109//!
110//! 7. **NFD decomposition** (again, on the NFC result). Steps 7, 8, and 10
111//! implement the Unicode canonical caseless matching algorithm (Definition D145):
112//! *"A string X is a canonical caseless match for a string Y if and only if:
113//! NFD(toCasefold(NFD(X))) = NFD(toCasefold(NFD(Y)))"*. Step 9 extends this
114//! with a post-case-fold fixup for Turkish/Azerbaijani and Lithuanian casing.
115//!
116//! 8. **Unicode `toCasefold()`** -- locale-independent full case folding.
117//!
118//! 9. **Post-case-fold fixup** -- maps U+0131 (ı) to ASCII i, and strips
119//! U+0307 COMBINING DOT ABOVE after any `Soft_Dotted`
120//! character (e.g. i, j, Cyrillic і/ј), blocked by intervening starters or
121//! CCC=230 Above combiners (matching the Unicode `After_Soft_Dotted` condition).
122//! This neutralizes casing inconsistencies that `toCasefold()` alone misses:
123//! - **Dotless ı (U+0131):** `toCasefold()` treats ı as distinct from i
124//! (ı folds to itself), yet `toUppercase(ı)` = I even without locale
125//! tailoring, and I folds back to i -- creating a collision.
126//! - **Lithuanian casing rules:** when lowercasing I/J/Į with additional accents above,
127//! Lithuanian rules insert U+0307 to retain the visual dot (e.g.
128//! `lt_lowercase("J\u{0301}")` = `j\u{0307}\u{0301}`). Conversely,
129//! Lithuanian upper/titlecase removes U+0307 after soft-dotted characters
130//! (e.g. `lt_uppercase("j\u{0307}")` = `J`). Stripping U+0307 after
131//! soft-dotted characters ensures stability under both directions.
132//!
133//! 10. **NFC composition** (final) -- recompose after case folding to produce the
134//! canonical NFC output.
135//!
136//! # OS compatibility mapping
137//!
138//! Each `PathElementGeneric` also computes an **OS-compatible** form suitable for
139//! use as an actual path element name on the host operating system. It is derived
140//! from the case-sensitive normalized form, by applying the following additional
141//! steps:
142//!
143//! - **Windows**: the characters and patterns listed in the Windows
144//! [naming conventions](https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions)
145//! are handled by mapping them to visually similar fullwidth Unicode equivalents:
146//! forbidden characters (`< > : " \ | ? *`), the final trailing dot, and the first
147//! character of reserved device names (CON, PRN, AUX, NUL, COM0--COM9, LPT0--LPT9,
148//! and their superscript-digit variants).
149//! - **Apple (macOS/iOS)**: converted using [`CFStringGetFileSystemRepresentation`](https://developer.apple.com/documentation/corefoundation/cfstringgetfilesystemrepresentation(_:_:_:))
150//! as recommended by Apple's documentation (produces a representation similar to NFD).
151//! - **Other platforms**: the OS-compatible form is identical to the case-sensitive
152//! normalized form.
153//!
154//! # Types
155//!
156//! The core type is [`PathElementGeneric<'a, S>`], parameterized by a case-sensitivity
157//! marker `S`:
158//!
159//! - [`PathElementCS`] = `PathElementGeneric<'a, CaseSensitive>` -- compile-time
160//! case-sensitive path element.
161//! - [`PathElementCI`] = `PathElementGeneric<'a, CaseInsensitive>` -- compile-time
162//! case-insensitive path element.
163//! - [`PathElement`] = `PathElementGeneric<'a, CaseSensitivity>` -- runtime-selected
164//! case sensitivity via the [`CaseSensitivity`] enum.
165//!
166//! Use the typed aliases ([`PathElementCS`], [`PathElementCI`]) when the case sensitivity
167//! is known at compile time. These implement [`Hash`](core::hash::Hash), which the
168//! runtime-dynamic [`PathElement`] does not (since hashing elements with different
169//! sensitivities into the same map would violate hash/eq consistency).
170//!
171//! The zero-sized marker structs [`CaseSensitive`] and [`CaseInsensitive`] are used as
172//! type parameters, while the [`CaseSensitivity`] enum provides the same choice at runtime.
173//! All three types implement `Into<CaseSensitivity>`.
174//!
175//! # Examples
176//!
177//! ```
178//! # use normalized_path::{PathElementCS, PathElementCI};
179//! // NFD input (e + combining acute) composes to NFC (é), whitespace is trimmed
180//! let pe = PathElementCS::new(" cafe\u{0301}.txt ")?;
181//! assert_eq!(pe.original(), " cafe\u{0301}.txt ");
182//! assert_eq!(pe.normalized(), "caf\u{00E9}.txt");
183//!
184//! // Case-insensitive: German ß case-folds to "ss"
185//! let pe = PathElementCI::new("Stra\u{00DF}e.txt")?;
186//! assert_eq!(pe.original(), "Stra\u{00DF}e.txt");
187//! assert_eq!(pe.normalized(), "strasse.txt");
188//! # Ok::<(), normalized_path::Error>(())
189//! ```
190//!
191//! The OS-compatible form adapts names for the host filesystem. On Windows,
192//! forbidden characters and reserved device names are mapped to safe alternatives;
193//! on Apple, names are converted to a form close to NFD:
194//!
195//! ```
196//! # use normalized_path::PathElementCS;
197//! // A name with a Windows-forbidden character and an accented letter
198//! let pe = PathElementCS::new("caf\u{00E9} 10:30")?;
199//! assert_eq!(pe.normalized(), "caf\u{00E9} 10:30");
200//!
201//! #[cfg(target_os = "windows")]
202//! assert_eq!(pe.os_compatible(), "caf\u{00E9} 10\u{FF1A}30"); // : → fullwidth :
203//!
204//! #[cfg(target_vendor = "apple")]
205//! assert_eq!(pe.os_compatible(), "cafe\u{0301} 10:30"); // NFC → NFD
206//!
207//! #[cfg(not(any(target_os = "windows", target_vendor = "apple")))]
208//! assert_eq!(pe.os_compatible(), pe.normalized()); // unchanged
209//! # Ok::<(), normalized_path::Error>(())
210//! ```
211//!
212//! Equality is based on the normalized form, so different originals can compare equal:
213//!
214//! ```
215//! # use normalized_path::PathElementCS;
216//! // NFD (e + combining acute) and NFC (é) normalize to the same form
217//! let a = PathElementCS::new("cafe\u{0301}.txt")?;
218//! let b = PathElementCS::new("caf\u{00E9}.txt")?;
219//! assert_eq!(a, b);
220//! assert_ne!(a.original(), b.original());
221//! # Ok::<(), normalized_path::Error>(())
222//! ```
223//!
224//! The typed variants implement [`Hash`](core::hash::Hash), so they work in
225//! both hash-based and ordered collections:
226//!
227//! ```
228//! # use std::collections::{BTreeSet, HashSet};
229//! # use normalized_path::PathElementCI;
230//! // Turkish İ, dotless ı, ASCII I, and ASCII i all normalize to the same CI form
231//! let names = ["\u{0130}.txt", "\u{0131}.txt", "I.txt", "i.txt"];
232//! let set: HashSet<_> = names.iter().map(|n| PathElementCI::new(*n).unwrap()).collect();
233//! assert_eq!(set.len(), 1);
234//!
235//! let tree: BTreeSet<_> = names.iter().map(|n| PathElementCI::new(*n).unwrap()).collect();
236//! assert_eq!(tree.len(), 1);
237//! ```
238//!
239//! The runtime-dynamic [`PathElement`] works in ordered collections too, but
240//! comparing or ordering elements with **different** case sensitivities will panic:
241//!
242//! ```
243//! # use std::collections::BTreeSet;
244//! # use normalized_path::{PathElement, CaseSensitive, CaseInsensitive};
245//! // "ss", "SS", "sS", "Ss", sharp s (ß), capital sharp s (ẞ)
246//! let names = ["ss", "SS", "sS", "Ss", "\u{00DF}", "\u{1E9E}"];
247//!
248//! let cs: BTreeSet<_> = names.iter()
249//! .map(|n| PathElement::new(*n, CaseSensitive).unwrap())
250//! .collect();
251//! assert_eq!(cs.len(), 6); // case-sensitive: all distinct
252//!
253//! let ci: BTreeSet<_> = names.iter()
254//! .map(|n| PathElement::new(*n, CaseInsensitive).unwrap())
255//! .collect();
256//! assert_eq!(ci.len(), 1); // case-insensitive: all normalize to "ss"
257//! ```
258//!
259//! # Unicode version
260//!
261//! All Unicode operations (NFC, NFD, case folding, property lookups) use
262//! **Unicode 17.0.0**. Updating to a newer Unicode version is not considered a
263//! semver-breaking change as long as the normalization pipeline produces identical
264//! results for all strings consisting of characters assigned in the previous version.
265//! If a new Unicode version were to change normalization results for previously
266//! assigned characters, that update would be a semver-breaking change.
267//!
268//! This is unlikely — though not formally guaranteed — due to the following
269//! [Character Encoding Stability Policies](https://www.unicode.org/policies/stability_policy.html):
270//! - If a string contains only characters from a given version of Unicode, and it
271//! is put into a normalized form in accordance with that version of Unicode, then
272//! the results will be identical to the results of putting that string into a
273//! normalized form in accordance with any subsequent version of Unicode.
274//! - Once a character is assigned, its canonical combining class will not change.
275//! - Once a character is encoded, its properties may still be changed, but not in
276//! such a way as to change the fundamental identity of the character.
277//! - For each string S containing only assigned characters in a given Unicode
278//! version, `toCasefold(toNFKC(S))` under that version is identical to
279//! `toCasefold(toNFKC(S))` under any later version of Unicode.
280//!
281//! # `no_std` support
282//!
283//! This crate supports `no_std` environments. Disable the default `std` feature:
284//!
285//! ```toml
286//! [dependencies]
287//! normalized-path = { version = "...", default-features = false }
288//! ```
289//!
290//! The `std` feature enables `from_os_str` constructors and
291//! `os_str`/`into_os_str` accessors. The `alloc` crate is always required.
292
293#![cfg_attr(not(feature = "std"), no_std)]
294#![cfg_attr(docsrs, feature(doc_cfg))]
295#![warn(clippy::all, clippy::pedantic)]
296
297extern crate alloc;
298
299mod case_sensitivity;
300mod error;
301mod normalize;
302mod os;
303mod path_element;
304mod unicode;
305mod utils;
306
307pub use case_sensitivity::{CaseInsensitive, CaseSensitive, CaseSensitivity};
308pub use error::{Error, ErrorKind, Result};
309pub use path_element::{PathElement, PathElementCI, PathElementCS, PathElementGeneric};
310
311#[cfg(any(feature = "__test", test))]
312pub mod test_helpers {
313 pub use crate::error::ResultKind;
314 pub use crate::normalize::{
315 fixup_case_fold, is_whitespace_like, map_control_chars, map_fullwidth,
316 normalize_ci_from_normalized_cs, normalize_cs, trim_whitespace_like, validate_path_element,
317 };
318 pub use crate::os::{
319 apple_compatible_from_normalized_cs, apple_compatible_from_normalized_cs_fallback,
320 is_reserved_on_windows, windows_compatible_from_normalized_cs,
321 };
322 pub use crate::unicode::{case_fold, is_starter, is_whitespace, nfc, nfd};
323}