Skip to main content

strate_fs_abstraction/
unicode.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Unicode string handling for Windows.
24//!
25//! Windows uses UTF-16 (wide strings) for all kernel APIs. This module
26//! provides utilities for converting between UTF-8 and UTF-16, and for
27//! working with Windows UNICODE_STRING structures.
28
29use crate::error::{FsError, FsResult};
30
31/// Maximum length for a Windows path component (characters).
32pub const MAX_COMPONENT_LENGTH: usize = 255;
33
34/// Maximum length for a full Windows path (characters).
35pub const MAX_PATH_LENGTH: usize = 32767;
36
37/// UNICODE_STRING structure for Windows kernel APIs.
38///
39/// This is a counted Unicode string, not null-terminated.
40#[repr(C)]
41#[derive(Debug, Clone, Copy)]
42pub struct UnicodeString {
43    /// Length of the string in bytes (not including any null terminator).
44    pub length: u16,
45    /// Maximum size of the Buffer in bytes.
46    pub maximum_length: u16,
47    /// Pointer to the wide string buffer.
48    pub buffer: *mut u16,
49}
50
51impl UnicodeString {
52    /// Creates a `UnicodeString` from a slice of wide characters.
53    ///
54    /// # Safety
55    ///
56    /// The buffer must remain valid for the lifetime of this structure.
57    pub const unsafe fn from_slice(slice: &[u16]) -> Self {
58        Self {
59            length: (slice.len() * 2) as u16,
60            maximum_length: (slice.len() * 2) as u16,
61            buffer: slice.as_ptr() as *mut u16,
62        }
63    }
64
65    /// Returns the string as a slice of wide characters.
66    ///
67    /// # Safety
68    ///
69    /// The buffer pointer must be valid.
70    pub unsafe fn as_slice(&self) -> &[u16] {
71        if self.buffer.is_null() {
72            return &[];
73        }
74        let char_count = (self.length / 2) as usize;
75        // SAFETY: Caller ensures buffer is valid
76        unsafe { core::slice::from_raw_parts(self.buffer, char_count) }
77    }
78
79    /// Returns `true` if the string is empty.
80    pub const fn is_empty(&self) -> bool {
81        self.length == 0
82    }
83
84    /// Returns the length in characters (not bytes).
85    pub const fn char_len(&self) -> usize {
86        (self.length / 2) as usize
87    }
88}
89
90/// In-place wide string buffer for stack allocation.
91///
92/// This avoids heap allocation for common path operations.
93#[repr(C)]
94pub struct WideStringBuffer<const N: usize> {
95    buffer: [u16; N],
96    len: usize,
97}
98
99impl<const N: usize> WideStringBuffer<N> {
100    /// Creates an empty buffer.
101    pub const fn new() -> Self {
102        Self {
103            buffer: [0; N],
104            len: 0,
105        }
106    }
107
108    /// Creates from a UTF-8 string.
109    pub fn from_utf8(s: &str) -> FsResult<Self> {
110        let mut result = Self::new();
111        result.push_utf8(s)?;
112        Ok(result)
113    }
114
115    /// Appends a UTF-8 string.
116    pub fn push_utf8(&mut self, s: &str) -> FsResult<()> {
117        for c in s.encode_utf16() {
118            if self.len >= N {
119                return Err(FsError::StringTooLong);
120            }
121            self.buffer[self.len] = c;
122            self.len += 1;
123        }
124        Ok(())
125    }
126
127    /// Appends a null terminator if there's room.
128    pub fn push_null(&mut self) -> FsResult<()> {
129        if self.len >= N {
130            return Err(FsError::StringTooLong);
131        }
132        self.buffer[self.len] = 0;
133        self.len += 1;
134        Ok(())
135    }
136
137    /// Returns the buffer as a slice.
138    pub fn as_slice(&self) -> &[u16] {
139        &self.buffer[..self.len]
140    }
141
142    /// Returns the buffer as a null-terminated slice (includes the null).
143    pub fn as_slice_with_null(&mut self) -> FsResult<&[u16]> {
144        self.push_null()?;
145        Ok(&self.buffer[..self.len])
146    }
147
148    /// Returns as a UNICODE_STRING.
149    pub fn as_unicode_string(&self) -> UnicodeString {
150        UnicodeString {
151            length: (self.len * 2) as u16,
152            maximum_length: (N * 2) as u16,
153            buffer: self.buffer.as_ptr() as *mut u16,
154        }
155    }
156
157    /// Returns the length in characters.
158    pub const fn len(&self) -> usize {
159        self.len
160    }
161
162    /// Returns `true` if empty.
163    pub const fn is_empty(&self) -> bool {
164        self.len == 0
165    }
166
167    /// Clears the buffer.
168    pub fn clear(&mut self) {
169        self.len = 0;
170    }
171
172    /// Returns capacity in characters.
173    pub const fn capacity(&self) -> usize {
174        N
175    }
176}
177
178impl<const N: usize> Default for WideStringBuffer<N> {
179    /// Implements default.
180    fn default() -> Self {
181        Self::new()
182    }
183}
184
185/// Wrapper for heap-allocated wide strings.
186///
187/// Only available with the `alloc` feature.
188#[cfg(feature = "alloc")]
189pub struct WindowsString {
190    buffer: alloc::vec::Vec<u16>,
191}
192
193#[cfg(feature = "alloc")]
194impl WindowsString {
195    /// Creates a new empty WindowsString.
196    pub fn new() -> Self {
197        Self {
198            buffer: alloc::vec::Vec::new(),
199        }
200    }
201
202    /// Creates from a UTF-8 string.
203    pub fn from_utf8(utf8: &str) -> FsResult<Self> {
204        let wide: alloc::vec::Vec<u16> = utf8
205            .encode_utf16()
206            .chain(core::iter::once(0)) // Null terminator
207            .collect();
208
209        if wide.len() > MAX_PATH_LENGTH {
210            return Err(FsError::StringTooLong);
211        }
212
213        Ok(Self { buffer: wide })
214    }
215
216    /// Creates a UNICODE_STRING pointing to this buffer.
217    pub fn as_unicode_string(&self) -> UnicodeString {
218        let len = if self.buffer.is_empty() {
219            0
220        } else {
221            // Length excludes null terminator
222            (self.buffer.len() - 1) * 2
223        };
224
225        UnicodeString {
226            length: len as u16,
227            maximum_length: (self.buffer.len() * 2) as u16,
228            buffer: self.buffer.as_ptr() as *mut u16,
229        }
230    }
231
232    /// Returns the buffer as a slice (including null terminator).
233    pub fn as_slice(&self) -> &[u16] {
234        &self.buffer
235    }
236
237    /// Returns the length in characters (excluding null terminator).
238    pub fn len(&self) -> usize {
239        if self.buffer.is_empty() {
240            0
241        } else {
242            self.buffer.len() - 1
243        }
244    }
245
246    /// Returns `true` if empty.
247    pub fn is_empty(&self) -> bool {
248        self.buffer.len() <= 1
249    }
250}
251
252#[cfg(feature = "alloc")]
253impl Default for WindowsString {
254    /// Implements default.
255    fn default() -> Self {
256        Self::new()
257    }
258}
259
260/// Compares two wide strings case-insensitively (ASCII only).
261///
262/// For proper Unicode case folding, use Windows APIs like
263/// `RtlCompareUnicodeString`.
264pub fn ascii_iequals(a: &[u16], b: &[u16]) -> bool {
265    if a.len() != b.len() {
266        return false;
267    }
268    for (ca, cb) in a.iter().zip(b.iter()) {
269        let ca_lower = if *ca >= 'A' as u16 && *ca <= 'Z' as u16 {
270            ca + 32
271        } else {
272            *ca
273        };
274        let cb_lower = if *cb >= 'A' as u16 && *cb <= 'Z' as u16 {
275            cb + 32
276        } else {
277            *cb
278        };
279        if ca_lower != cb_lower {
280            return false;
281        }
282    }
283    true
284}
285
286/// Validates that a string contains only valid filename characters.
287///
288/// Invalid characters: \ / : * ? " < > |
289pub fn is_valid_filename(s: &[u16]) -> bool {
290    const INVALID: [u16; 9] = [
291        '\\' as u16,
292        '/' as u16,
293        ':' as u16,
294        '*' as u16,
295        '?' as u16,
296        '"' as u16,
297        '<' as u16,
298        '>' as u16,
299        '|' as u16,
300    ];
301
302    for c in s {
303        if *c == 0 || INVALID.contains(c) {
304            return false;
305        }
306    }
307    true
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313
314    #[test]
315    /// Implements test wide buffer utf8.
316    fn test_wide_buffer_utf8() {
317        let mut buf = WideStringBuffer::<64>::from_utf8("Hello").unwrap();
318        assert_eq!(buf.len(), 5);
319        buf.push_utf8(" World").unwrap();
320        assert_eq!(buf.len(), 11);
321    }
322
323    #[test]
324    /// Implements test wide buffer overflow.
325    fn test_wide_buffer_overflow() {
326        let result = WideStringBuffer::<3>::from_utf8("Hello");
327        assert!(result.is_err());
328    }
329
330    #[test]
331    /// Implements test ascii iequals.
332    fn test_ascii_iequals() {
333        let a = [
334            b'H' as u16,
335            b'e' as u16,
336            b'l' as u16,
337            b'l' as u16,
338            b'o' as u16,
339        ];
340        let b = [
341            b'h' as u16,
342            b'E' as u16,
343            b'L' as u16,
344            b'L' as u16,
345            b'O' as u16,
346        ];
347        assert!(ascii_iequals(&a, &b));
348    }
349
350    #[test]
351    /// Implements test is valid filename.
352    fn test_is_valid_filename() {
353        let valid = [b't' as u16, b'e' as u16, b's' as u16, b't' as u16];
354        assert!(is_valid_filename(&valid));
355
356        let invalid = [b't' as u16, b'*' as u16];
357        assert!(!is_valid_filename(&invalid));
358    }
359}