no_std_path 0.1.0

A no_std fork of the path module from https://github.com/rust-lang/rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! Minimal `OsStr` / `OsString` replacements for `no_std` environments.
//!
//! On Unix, `OsStr` is just `[u8]` and `OsString` is just `Vec<u8>`.
//! We replicate that here with newtype wrappers so the path module can
//! work without pulling in `std::ffi`.

use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::collections::TryReserveError;
use alloc::string::String;
use alloc::vec::Vec;
use core::borrow::Borrow;
use core::hash::{Hash, Hasher};
use core::ops;

/// Borrowed OS string slice (analogous to `std::ffi::OsStr`).
///
/// In this `no_std` crate the inner representation is simply `[u8]`.
#[repr(transparent)]
pub struct OsStr {
    inner: [u8],
}

/// Owned OS string (analogous to `std::ffi::OsString`).
///
/// In this `no_std` crate the inner representation is simply `Vec<u8>`.
#[derive(Clone, Default)]
pub struct OsString {
    inner: Vec<u8>,
}

// ---------------------------------------------------------------------------
// OsStr
// ---------------------------------------------------------------------------

impl OsStr {
    /// Wrap a `&str` as an `&OsStr`.
    #[inline]
    pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {
        s.as_ref()
    }

    /// View the encoded bytes of this OS string slice.
    #[inline]
    pub fn as_encoded_bytes(&self) -> &[u8] {
        &self.inner
    }

    /// Create an `&OsStr` from a byte slice **without** any validation.
    ///
    /// # Safety
    /// The caller must guarantee that the byte slice is a valid encoding
    /// for the platform. In this crate every byte sequence is valid.
    #[inline]
    pub unsafe fn from_encoded_bytes_unchecked(bytes: &[u8]) -> &OsStr {
        // SAFETY: OsStr is #[repr(transparent)] over [u8].
        unsafe { &*(bytes as *const [u8] as *const OsStr) }
    }

    /// Create an `&mut OsStr` from a mutable byte slice without validation.
    ///
    /// # Safety
    /// Same as [`from_encoded_bytes_unchecked`].
    #[inline]
    pub unsafe fn from_encoded_bytes_unchecked_mut(bytes: &mut [u8]) -> &mut OsStr {
        unsafe { &mut *(bytes as *mut [u8] as *mut OsStr) }
    }

    /// The length in bytes.
    #[inline]
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Whether the slice is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Convert to an owned `OsString`.
    #[inline]
    pub fn to_os_string(&self) -> OsString {
        OsString { inner: self.inner.to_vec() }
    }

    /// Try to convert to a UTF-8 `&str`.
    #[inline]
    pub fn to_str(&self) -> Option<&str> {
        core::str::from_utf8(&self.inner).ok()
    }

    /// Lossy conversion to a UTF-8 string, replacing invalid sequences
    /// with U+FFFD.
    pub fn to_string_lossy(&self) -> Cow<'_, str> {
        String::from_utf8_lossy(&self.inner)
    }

    /// Return a `Display` helper that prints the string lossily.
    #[inline]
    pub fn display(&self) -> Display<'_> {
        Display { inner: self }
    }

    /// Make all ASCII characters lowercase, in place.
    #[inline]
    pub fn make_ascii_lowercase(&mut self) {
        self.inner.make_ascii_lowercase();
    }

    /// Make all ASCII characters uppercase, in place.
    #[inline]
    pub fn make_ascii_uppercase(&mut self) {
        self.inner.make_ascii_uppercase();
    }
}

// --- trait impls for OsStr -------------------------------------------------

impl PartialEq for OsStr {
    #[inline]
    fn eq(&self, other: &OsStr) -> bool {
        self.inner == other.inner
    }
}

impl Eq for OsStr {}

impl PartialOrd for OsStr {
    #[inline]
    fn partial_cmp(&self, other: &OsStr) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for OsStr {
    #[inline]
    fn cmp(&self, other: &OsStr) -> core::cmp::Ordering {
        self.inner.cmp(&other.inner)
    }
}

impl Hash for OsStr {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.inner.hash(state);
    }
}

impl core::fmt::Debug for OsStr {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        // Escape non-UTF-8 the same way Debug for str would
        write!(f, "\"")?;
        for chunk in self.inner.utf8_chunks() {
            // Display the valid UTF-8 part
            let valid = chunk.valid();
            for c in valid.chars() {
                write!(f, "{}", c.escape_debug())?;
            }
            // Display the invalid part as hex escapes
            for &b in chunk.invalid() {
                write!(f, "\\x{b:02x}")?;
            }
        }
        write!(f, "\"")
    }
}

impl core::fmt::Display for OsStr {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let lossy = self.to_string_lossy();
        f.write_str(&lossy)
    }
}

impl Default for &OsStr {
    #[inline]
    fn default() -> Self {
        // SAFETY: Empty slice is valid.
        unsafe { OsStr::from_encoded_bytes_unchecked(&[]) }
    }
}

impl AsRef<OsStr> for str {
    #[inline]
    fn as_ref(&self) -> &OsStr {
        // SAFETY: UTF-8 is always valid.
        unsafe { OsStr::from_encoded_bytes_unchecked(self.as_bytes()) }
    }
}

impl AsRef<OsStr> for String {
    #[inline]
    fn as_ref(&self) -> &OsStr {
        self.as_str().as_ref()
    }
}

impl AsRef<OsStr> for OsStr {
    #[inline]
    fn as_ref(&self) -> &OsStr {
        self
    }
}

impl AsRef<OsStr> for OsString {
    #[inline]
    fn as_ref(&self) -> &OsStr {
        self.as_os_str()
    }
}

impl alloc::borrow::ToOwned for OsStr {
    type Owned = OsString;

    #[inline]
    fn to_owned(&self) -> OsString {
        self.to_os_string()
    }

    #[inline]
    fn clone_into(&self, target: &mut OsString) {
        target.inner.clear();
        target.inner.extend_from_slice(&self.inner);
    }
}

impl PartialEq<str> for OsStr {
    #[inline]
    fn eq(&self, other: &str) -> bool {
        self.inner == *other.as_bytes()
    }
}

impl PartialEq<OsStr> for str {
    #[inline]
    fn eq(&self, other: &OsStr) -> bool {
        *self.as_bytes() == other.inner
    }
}

// ops::Index<ops::RangeFull> for OsStr -> &OsStr
impl ops::Index<ops::RangeFull> for OsStr {
    type Output = OsStr;
    #[inline]
    fn index(&self, _: ops::RangeFull) -> &OsStr {
        self
    }
}

// ---------------------------------------------------------------------------
// OsString
// ---------------------------------------------------------------------------

impl OsString {
    /// Create a new empty `OsString`.
    #[inline]
    pub const fn new() -> OsString {
        OsString { inner: Vec::new() }
    }

    /// Create an `OsString` with the given capacity.
    #[inline]
    pub fn with_capacity(capacity: usize) -> OsString {
        OsString { inner: Vec::with_capacity(capacity) }
    }

    /// Borrow as an `&OsStr`.
    #[inline]
    pub fn as_os_str(&self) -> &OsStr {
        // SAFETY: OsStr is repr(transparent) over [u8].
        unsafe { OsStr::from_encoded_bytes_unchecked(&self.inner) }
    }

    /// Borrow as a `&mut OsStr`.
    #[inline]
    pub fn as_mut_os_str(&mut self) -> &mut OsStr {
        unsafe { OsStr::from_encoded_bytes_unchecked_mut(&mut self.inner) }
    }

    /// Append the given `OsStr` to this string.
    #[inline]
    pub fn push<S: AsRef<OsStr>>(&mut self, s: S) {
        self.inner.extend_from_slice(s.as_ref().as_encoded_bytes());
    }

    /// Try to convert into a `String`.
    #[inline]
    pub fn into_string(self) -> Result<String, OsString> {
        String::from_utf8(self.inner).map_err(|e| OsString { inner: e.into_bytes() })
    }

    /// Truncate to `len` bytes.
    #[inline]
    pub fn truncate(&mut self, len: usize) {
        self.inner.truncate(len);
    }

    /// Reserve capacity for at least `additional` more bytes.
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        self.inner.reserve(additional);
    }

    /// Reserve capacity for exactly `additional` more bytes.
    #[inline]
    pub fn reserve_exact(&mut self, additional: usize) {
        self.inner.reserve_exact(additional);
    }

    /// Try to reserve capacity for at least `additional` more bytes.
    #[inline]
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.inner.try_reserve(additional)
    }

    /// Try to reserve capacity for exactly `additional` more bytes.
    #[inline]
    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.inner.try_reserve_exact(additional)
    }

    /// Shrink capacity to fit the current length.
    #[inline]
    pub fn shrink_to_fit(&mut self) {
        self.inner.shrink_to_fit();
    }

    /// Shrink capacity to at least `min_capacity`.
    #[inline]
    pub fn shrink_to(&mut self, min_capacity: usize) {
        self.inner.shrink_to(min_capacity);
    }

    /// Return the current capacity in bytes.
    #[inline]
    pub fn capacity(&self) -> usize {
        self.inner.capacity()
    }

    /// Clear the string.
    #[inline]
    pub fn clear(&mut self) {
        self.inner.clear();
    }

    /// The length in bytes.
    #[inline]
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Whether the string is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// View the encoded bytes.
    #[inline]
    pub fn as_encoded_bytes(&self) -> &[u8] {
        &self.inner
    }

    /// Consume and leak, returning a `&'a mut OsStr`.
    #[inline]
    pub fn leak<'a>(self) -> &'a mut OsStr {
        let leaked = self.inner.leak();
        // SAFETY: OsStr is repr(transparent) over [u8].
        unsafe { OsStr::from_encoded_bytes_unchecked_mut(leaked) }
    }

    /// Consume into a boxed `OsStr`.
    #[inline]
    pub fn into_boxed_os_str(self) -> Box<OsStr> {
        let boxed: Box<[u8]> = self.inner.into_boxed_slice();
        let raw = Box::into_raw(boxed) as *mut OsStr;
        // SAFETY: OsStr is repr(transparent) over [u8].
        unsafe { Box::from_raw(raw) }
    }

    /// Extend from a raw byte slice without validation.
    ///
    /// # Safety
    /// The caller must ensure the resulting OsString remains valid.
    /// In this crate every byte sequence is valid, so this is always safe
    /// from a validity standpoint, but we keep the signature for API compat.
    #[inline]
    pub unsafe fn extend_from_slice_unchecked(&mut self, slice: &[u8]) {
        self.inner.extend_from_slice(slice);
    }
}

// --- trait impls for OsString ----------------------------------------------

impl ops::Deref for OsString {
    type Target = OsStr;

    #[inline]
    fn deref(&self) -> &OsStr {
        self.as_os_str()
    }
}

impl ops::DerefMut for OsString {
    #[inline]
    fn deref_mut(&mut self) -> &mut OsStr {
        self.as_mut_os_str()
    }
}

impl Borrow<OsStr> for OsString {
    #[inline]
    fn borrow(&self) -> &OsStr {
        self.as_os_str()
    }
}

impl PartialEq for OsString {
    #[inline]
    fn eq(&self, other: &OsString) -> bool {
        self.as_os_str() == other.as_os_str()
    }
}

impl Eq for OsString {}

impl PartialOrd for OsString {
    #[inline]
    fn partial_cmp(&self, other: &OsString) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for OsString {
    #[inline]
    fn cmp(&self, other: &OsString) -> core::cmp::Ordering {
        self.as_os_str().cmp(other.as_os_str())
    }
}

impl Hash for OsString {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_os_str().hash(state);
    }
}

impl core::fmt::Debug for OsString {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Debug::fmt(self.as_os_str(), f)
    }
}

impl core::fmt::Display for OsString {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Display::fmt(self.as_os_str(), f)
    }
}

impl From<String> for OsString {
    #[inline]
    fn from(s: String) -> OsString {
        OsString { inner: s.into_bytes() }
    }
}

impl From<&str> for OsString {
    #[inline]
    fn from(s: &str) -> OsString {
        OsString { inner: s.as_bytes().to_vec() }
    }
}

impl From<Box<OsStr>> for OsString {
    #[inline]
    fn from(boxed: Box<OsStr>) -> OsString {
        let raw = Box::into_raw(boxed) as *mut [u8];
        let inner = unsafe { Box::from_raw(raw) };
        OsString { inner: inner.into_vec() }
    }
}

impl From<OsString> for alloc::sync::Arc<OsStr> {
    fn from(s: OsString) -> alloc::sync::Arc<OsStr> {
        let arc: alloc::sync::Arc<[u8]> = alloc::sync::Arc::from(s.inner);
        // SAFETY: OsStr is repr(transparent) over [u8].
        unsafe { alloc::sync::Arc::from_raw(alloc::sync::Arc::into_raw(arc) as *const OsStr) }
    }
}

impl From<&OsStr> for alloc::sync::Arc<OsStr> {
    fn from(s: &OsStr) -> alloc::sync::Arc<OsStr> {
        let arc: alloc::sync::Arc<[u8]> = alloc::sync::Arc::from(&s.inner);
        unsafe { alloc::sync::Arc::from_raw(alloc::sync::Arc::into_raw(arc) as *const OsStr) }
    }
}

impl From<OsString> for alloc::rc::Rc<OsStr> {
    fn from(s: OsString) -> alloc::rc::Rc<OsStr> {
        let rc: alloc::rc::Rc<[u8]> = alloc::rc::Rc::from(s.inner);
        unsafe { alloc::rc::Rc::from_raw(alloc::rc::Rc::into_raw(rc) as *const OsStr) }
    }
}

impl From<&OsStr> for alloc::rc::Rc<OsStr> {
    fn from(s: &OsStr) -> alloc::rc::Rc<OsStr> {
        let rc: alloc::rc::Rc<[u8]> = alloc::rc::Rc::from(&s.inner);
        unsafe { alloc::rc::Rc::from_raw(alloc::rc::Rc::into_raw(rc) as *const OsStr) }
    }
}

impl AsRef<crate::Path> for OsStr {
    #[inline]
    fn as_ref(&self) -> &crate::Path {
        crate::Path::new(self)
    }
}

impl AsRef<crate::Path> for OsString {
    #[inline]
    fn as_ref(&self) -> &crate::Path {
        crate::Path::new(self)
    }
}

impl From<crate::PathBuf> for OsString {
    #[inline]
    fn from(path_buf: crate::PathBuf) -> OsString {
        path_buf.into_os_string()
    }
}

impl From<OsString> for crate::PathBuf {
    #[inline]
    fn from(s: OsString) -> crate::PathBuf {
        crate::PathBuf::from_os_string(s)
    }
}

// ---------------------------------------------------------------------------
// Display helper (used by Path::display)
// ---------------------------------------------------------------------------

/// A helper struct for lossy display of an `OsStr`.
pub struct Display<'a> {
    inner: &'a OsStr,
}

impl<'a> core::fmt::Debug for Display<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Debug::fmt(self.inner, f)
    }
}

impl<'a> core::fmt::Display for Display<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let lossy = self.inner.to_string_lossy();
        f.pad(&lossy)
    }
}