Debian Codegraph @

third_party/rust/unix_str/src/lib.rs

raw
1 //! Strings that are compatible wuth Unix-like operating systems.
2 //!
3 //! * [`UnixString`] and [`UnixStr`] are useful when you need to with Unix strings.
4 //! Conversions between [`UnixString`], [`UnixStr`] and Rust strings work similarly
5 //! to those for `CString` and `CStr`.
6 //!
7 //! * [`UnixString`] represents an owned string in Unix's preferred
8 //! representation.
9 //!
10 //! * [`UnixStr`] represents a borrowed reference to a string in a format that
11 //! can be passed to a Unix-lie operating system. It can be converted into
12 //! a UTF-8 Rust string slice in a similar way to [`UnixString`].
13 //!
14 //! # Conversions
15 //!
16 //! [`UnixStr`] implements two methods, [`from_bytes`] and [`as_bytes`].
17 //! These do inexpensive conversions from and to UTF-8 byte slices.
18 //!
19 //! Additionally, [`UnixString`] provides [`from_vec`] and [`into_vec`] methods
20 //! that consume their arguments, and take or produce vectors of [`u8`].
21 //!
22 //! [`UnixString`]: struct.UnixString.html
23 //! [`UnixStr`]: struct.UnixStr.html
24 //! [`from_vec`]: struct.UnixString.html#method.from_vec
25 //! [`into_vec`]: struct.UnixString.html#method.into_vec
26 //! [`from_bytes`]: struct.UnixStrExt.html#method.from_bytes
27 //! [`as_bytes`]: struct.UnixStrExt.html#method.as_bytes
28
29 #![cfg_attr(feature = "shrink_to", feature(shrink_to))]
30 #![cfg_attr(feature = "toowned_clone_into", feature(toowned_clone_into))]
31 #![no_std]
32
33 #[cfg(feature = "alloc")]
34 extern crate alloc;
35
36 use core::cmp;
37 use core::fmt;
38 use core::hash::{Hash, Hasher};
39 use core::mem;
40
41 #[cfg(feature = "alloc")]
42 use alloc::borrow::{Borrow, Cow, ToOwned};
43 #[cfg(feature = "alloc")]
44 use alloc::boxed::Box;
45 #[cfg(feature = "alloc")]
46 use alloc::rc::Rc;
47 #[cfg(feature = "alloc")]
48 use alloc::string::String;
49 #[cfg(feature = "alloc")]
50 use alloc::sync::Arc;
51 #[cfg(feature = "alloc")]
52 use alloc::vec::Vec;
53 #[cfg(feature = "alloc")]
54 use core::ops;
55 #[cfg(feature = "alloc")]
56 use core::str::FromStr;
57
58 mod lossy;
59
60 mod sys;
61 #[cfg(feature = "alloc")]
62 use sys::Buf;
63 use sys::Slice;
64
65 mod sys_common;
66 use sys_common::AsInner;
67 #[cfg(feature = "alloc")]
68 use sys_common::{FromInner, IntoInner};
69
70 /// A type that can represent owned, mutable Unix strings, but is cheaply
71 /// inter-convertible with Rust strings.
72 ///
73 /// The need for this type arises from the fact that:
74 ///
75 /// * On Unix systems, strings are often arbitrary sequences of non-zero
76 /// bytes, in many cases interpreted as UTF-8.
77 ///
78 /// * In Rust, strings are always valid UTF-8, which may contain zeros.
79 ///
80 /// `UnixString` and [`UnixStr`] bridge this gap by simultaneously representing
81 /// Rust and platform-native string values, and in particular allowing a Rust
82 /// string to be converted into a “Unix” string with no cost if possible.
83 /// A consequence of this is that `UnixString` instances are *not* `NULL`
84 /// terminated; in order to pass to e.g., Unix system call, you should create
85 /// a `CStr`.
86 ///
87 /// `UnixString` is to [`&UnixStr`] as `String` is to `&str`: the former
88 /// in each pair are owned strings; the latter are borrowed references.
89 ///
90 /// Note, `UnixString` and [`UnixStr`] internally do not hold in the form native
91 /// to the platform: `UnixString`s are stored as a sequence of 8-bit values.
92 ///
93 /// # Creating an `UnixString`
94 ///
95 /// **From a Rust string**: `UnixString` implements `From<String>`, so you can
96 /// use `my_string.from` to create an `UnixString` from a normal Rust string.
97 ///
98 /// **From slices:** Just like you can start with an empty Rust [`String`]
99 /// and then [`push_str`][String.push_str] `&str` sub-string slices into it,
100 /// you can create an empty `UnixString` with the [`new`] method and then push
101 /// string slices into it with the [`push`] method.
102 ///
103 /// # Extracting a borrowed reference to the whole OS string
104 ///
105 /// You can use the [`as_unix_str`] method to get a [`&UnixStr`] from
106 /// a `UnixString`; this is effectively a borrowed reference to the whole
107 /// string.
108 ///
109 /// # Conversions
110 ///
111 /// See the [module's toplevel documentation about conversions][conversions]
112 /// for a discussion on the traits which `UnixString` implements for
113 /// [conversions] from/to native representations.
114 ///
115 /// [`UnixStr`]: struct.UnixStr.html
116 /// [`&UnixStr`]: struct.UnixStr.html
117 /// [`CStr`]: struct.CStr.html
118 /// [`new`]: #method.new
119 /// [`push`]: #method.push
120 /// [`as_unix_str`]: #method.as_unix_str
121 /// [conversions]: index.html#conversions
122 #[derive(Clone)]
123 #[cfg(feature = "alloc")]
124 pub struct UnixString {
125 inner: Buf,
126 }
127
128 /// Borrowed reference to a Unix string (see [`UnixString`]).
129 ///
130 /// This type represents a borrowed reference to a string in Unix's preferred
131 /// representation.
132 ///
133 /// `&UnixStr` is to [`UnixString`] as `&str` is to `String`: the former
134 /// in each pair are borrowed references; the latter are owned strings.
135 ///
136 /// See the [module's toplevel documentation about conversions][conversions]
137 /// for a discussion on the traits which `UnixStr` implements for [conversions]
138 /// from/to native representations.
139 ///
140 /// [`UnixString`]: struct.UnixString.html
141 /// [conversions]: index.html#conversions
142 // FIXME:
143 // `UnixStr::from_inner` current implementation relies on `UnixStr` being
144 // layout-compatible with `Slice`. When attribute privacy is implemented,
145 // `UnixStr` should be annotated as `#[repr(transparent)]`. Anyway, `UnixStr`
146 // representation and layout are considered implementation detail, are
147 // not documented and must not be relied upon.
148 pub struct UnixStr {
149 inner: Slice,
150 }
151
152 #[cfg(feature = "alloc")]
153 impl UnixString {
154 /// Constructs a new empty `UnixString`.
155 ///
156 /// # Examples
157 ///
158 /// ```
159 /// use unix_str::UnixString;
160 ///
161 /// let unix_string = UnixString::new();
162 /// ```
163 pub fn new() -> Self {
164 Self {
165 inner: Buf::from_string(String::new()),
166 }
167 }
168
169 /// Converts to an [`UnixStr`] slice.
170 ///
171 /// [`UnixStr`]: struct.UnixStr.html
172 ///
173 /// # Examples
174 ///
175 /// ```
176 /// use unix_str::{UnixString, UnixStr};
177 ///
178 /// let unix_string = UnixString::from("foo");
179 /// let unix_str = UnixStr::new("foo");
180 /// assert_eq!(unix_string.as_unix_str(), unix_str);
181 /// ```
182 pub fn as_unix_str(&self) -> &UnixStr {
183 self
184 }
185
186 /// Converts the `UnixString` into a `String` if it contains valid Unicode data.
187 ///
188 /// On failure, ownership of the original `UnixString` is returned.
189 ///
190 /// # Examples
191 ///
192 /// ```
193 /// use unix_str::UnixString;
194 ///
195 /// let unix_string = UnixString::from("foo");
196 /// let string = unix_string.into_string();
197 /// assert_eq!(string, Ok(String::from("foo")));
198 /// ```
199 pub fn into_string(self) -> Result<String, UnixString> {
200 self.inner
201 .into_string()
202 .map_err(|buf| UnixString { inner: buf })
203 }
204
205 /// Extends the string with the given [`&UnixStr`] slice.
206 ///
207 /// [`&UnixStr`]: struct.UnixStr.html
208 ///
209 /// # Examples
210 ///
211 /// ```
212 /// use unix_str::UnixString;
213 ///
214 /// let mut unix_string = UnixString::from("foo");
215 /// unix_string.push("bar");
216 /// assert_eq!(&unix_string, "foobar");
217 /// ```
218 pub fn push<T: AsRef<UnixStr>>(&mut self, s: T) {
219 self.inner.push_slice(&s.as_ref().inner)
220 }
221
222 /// Creates a new `UnixString` with the given capacity.
223 ///
224 /// The string will be able to hold exactly `capacity` length units of other
225 /// OS strings without reallocating. If `capacity` is 0, the string will not
226 /// allocate.
227 ///
228 /// See main `UnixString` documentation information about encoding.
229 ///
230 /// # Examples
231 ///
232 /// ```
233 /// use unix_str::UnixString;
234 ///
235 /// let mut unix_string = UnixString::with_capacity(10);
236 /// let capacity = unix_string.capacity();
237 ///
238 /// // This push is done without reallocating
239 /// unix_string.push("foo");
240 ///
241 /// assert_eq!(capacity, unix_string.capacity());
242 /// ```
243 pub fn with_capacity(capacity: usize) -> Self {
244 Self {
245 inner: Buf::with_capacity(capacity),
246 }
247 }
248
249 /// Truncates the `UnixString` to zero length.
250 ///
251 /// # Examples
252 ///
253 /// ```
254 /// use unix_str::UnixString;
255 ///
256 /// let mut unix_string = UnixString::from("foo");
257 /// assert_eq!(&unix_string, "foo");
258 ///
259 /// unix_string.clear();
260 /// assert_eq!(&unix_string, "");
261 /// ```
262 pub fn clear(&mut self) {
263 self.inner.clear()
264 }
265
266 /// Returns the capacity this `UnixString` can hold without reallocating.
267 ///
268 /// See `UnixString` introduction for information about encoding.
269 ///
270 /// # Examples
271 ///
272 /// ```
273 /// use unix_str::UnixString;
274 ///
275 /// let unix_string = UnixString::with_capacity(10);
276 /// assert!(unix_string.capacity() >= 10);
277 /// ```
278 pub fn capacity(&self) -> usize {
279 self.inner.capacity()
280 }
281
282 /// Reserves capacity for at least `additional` more capacity to be inserted
283 /// in the given `UnixString`.
284 ///
285 /// The collection may reserve more space to avoid frequent reallocations.
286 ///
287 /// # Examples
288 ///
289 /// ```
290 /// use unix_str::UnixString;
291 ///
292 /// let mut s = UnixString::new();
293 /// s.reserve(10);
294 /// assert!(s.capacity() >= 10);
295 /// ```
296 pub fn reserve(&mut self, additional: usize) {
297 self.inner.reserve(additional)
298 }
299
300 /// Reserves the minimum capacity for exactly `additional` more capacity to
301 /// be inserted in the given `UnixString`. Does nothing if the capacity is
302 /// already sufficient.
303 ///
304 /// Note that the allocator may give the collection more space than it
305 /// requests. Therefore, capacity can not be relied upon to be precisely
306 /// minimal. Prefer reserve if future insertions are expected.
307 ///
308 /// # Examples
309 ///
310 /// ```
311 /// use unix_str::UnixString;
312 ///
313 /// let mut s = UnixString::new();
314 /// s.reserve_exact(10);
315 /// assert!(s.capacity() >= 10);
316 /// ```
317 pub fn reserve_exact(&mut self, additional: usize) {
318 self.inner.reserve_exact(additional)
319 }
320
321 /// Shrinks the capacity of the `UnixString` to match its length.
322 ///
323 /// # Examples
324 ///
325 /// ```
326 /// use unix_str::UnixString;
327 ///
328 /// let mut s = UnixString::from("foo");
329 ///
330 /// s.reserve(100);
331 /// assert!(s.capacity() >= 100);
332 ///
333 /// s.shrink_to_fit();
334 /// assert_eq!(3, s.capacity());
335 /// ```
336 pub fn shrink_to_fit(&mut self) {
337 self.inner.shrink_to_fit()
338 }
339
340 /// Shrinks the capacity of the `UnixString` with a lower bound.
341 ///
342 /// The capacity will remain at least as large as both the length
343 /// and the supplied value.
344 ///
345 /// Panics if the current capacity is smaller than the supplied
346 /// minimum capacity.
347 ///
348 /// # Examples
349 ///
350 /// ```
351 /// #![feature(shrink_to)]
352 /// use std::ffi::UnixString;
353 ///
354 /// let mut s = UnixString::from("foo");
355 ///
356 /// s.reserve(100);
357 /// assert!(s.capacity() >= 100);
358 ///
359 /// s.shrink_to(10);
360 /// assert!(s.capacity() >= 10);
361 /// s.shrink_to(0);
362 /// assert!(s.capacity() >= 3);
363 /// ```
364 #[inline]
365 #[cfg(feature = "shrink_to")]
366 pub fn shrink_to(&mut self, min_capacity: usize) {
367 self.inner.shrink_to(min_capacity)
368 }
369
370 /// Converts this `UnixString` into a boxed [`UnixStr`].
371 ///
372 /// [`UnixStr`]: struct.UnixStr.html
373 ///
374 /// # Examples
375 ///
376 /// ```
377 /// use unix_str::{UnixString, UnixStr};
378 ///
379 /// let s = UnixString::from("hello");
380 ///
381 /// let b: Box<UnixStr> = s.into_boxed_unix_str();
382 /// ```
383 pub fn into_boxed_unix_str(self) -> Box<UnixStr> {
384 let rw = Box::into_raw(self.inner.into_box()) as *mut UnixStr;
385 unsafe { Box::from_raw(rw) }
386 }
387
388 /// Creates a `UnixString` from a byte vector.
389 ///
390 /// See the module documentation for an example.
391 ///
392 pub fn from_vec(vec: Vec<u8>) -> Self {
393 FromInner::from_inner(Buf { inner: vec })
394 }
395
396 /// Yields the underlying byte vector of this `UnixString`.
397 ///
398 /// See the module documentation for an example.
399 pub fn into_vec(self) -> Vec<u8> {
400 self.into_inner().inner
401 }
402 }
403
404 #[cfg(feature = "alloc")]
405 impl From<String> for UnixString {
406 /// Converts a `String` into a [`UnixString`].
407 ///
408 /// The conversion copies the data, and includes an allocation on the heap.
409 ///
410 /// [`UnixString`]: ../../std/ffi/struct.UnixString.html
411 fn from(s: String) -> Self {
412 UnixString {
413 inner: Buf::from_string(s),
414 }
415 }
416 }
417
418 #[cfg(feature = "alloc")]
419 impl<T: ?Sized + AsRef<UnixStr>> From<&T> for UnixString {
420 fn from(s: &T) -> Self {
421 s.as_ref().to_unix_string()
422 }
423 }
424
425 #[cfg(feature = "alloc")]
426 impl ops::Index<ops::RangeFull> for UnixString {
427 type Output = UnixStr;
428
429 #[inline]
430 fn index(&self, _index: ops::RangeFull) -> &UnixStr {
431 UnixStr::from_inner(self.inner.as_slice())
432 }
433 }
434
435 #[cfg(feature = "alloc")]
436 impl ops::IndexMut<ops::RangeFull> for UnixString {
437 #[inline]
438 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut UnixStr {
439 UnixStr::from_inner_mut(self.inner.as_mut_slice())
440 }
441 }
442
443 #[cfg(feature = "alloc")]
444 impl ops::Deref for UnixString {
445 type Target = UnixStr;
446
447 #[inline]
448 fn deref(&self) -> &UnixStr {
449 &self[..]
450 }
451 }
452
453 #[cfg(feature = "alloc")]
454 impl ops::DerefMut for UnixString {
455 #[inline]
456 fn deref_mut(&mut self) -> &mut UnixStr {
457 &mut self[..]
458 }
459 }
460
461 #[cfg(feature = "alloc")]
462 impl Default for UnixString {
463 /// Constructs an empty `UnixString`.
464 #[inline]
465 fn default() -> Self {
466 Self::new()
467 }
468 }
469
470 #[cfg(feature = "alloc")]
471 impl fmt::Debug for UnixString {
472 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
473 fmt::Debug::fmt(&**self, formatter)
474 }
475 }
476
477 #[cfg(feature = "alloc")]
478 impl PartialEq for UnixString {
479 fn eq(&self, other: &Self) -> bool {
480 &**self == &**other
481 }
482 }
483
484 #[cfg(feature = "alloc")]
485 impl PartialEq<str> for UnixString {
486 fn eq(&self, other: &str) -> bool {
487 &**self == other
488 }
489 }
490
491 #[cfg(feature = "alloc")]
492 impl PartialEq<UnixString> for str {
493 fn eq(&self, other: &UnixString) -> bool {
494 &**other == self
495 }
496 }
497
498 #[cfg(feature = "alloc")]
499 impl PartialEq<&str> for UnixString {
500 fn eq(&self, other: &&str) -> bool {
501 **self == **other
502 }
503 }
504
505 #[cfg(feature = "alloc")]
506 impl<'a> PartialEq<UnixString> for &'a str {
507 fn eq(&self, other: &UnixString) -> bool {
508 **other == **self
509 }
510 }
511
512 #[cfg(feature = "alloc")]
513 impl Eq for UnixString {}
514
515 #[cfg(feature = "alloc")]
516 impl PartialOrd for UnixString {
517 #[inline]
518 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
519 (&**self).partial_cmp(&**other)
520 }
521 #[inline]
522 fn lt(&self, other: &Self) -> bool {
523 &**self < &**other
524 }
525 #[inline]
526 fn le(&self, other: &Self) -> bool {
527 &**self <= &**other
528 }
529 #[inline]
530 fn gt(&self, other: &Self) -> bool {
531 &**self > &**other
532 }
533 #[inline]
534 fn ge(&self, other: &Self) -> bool {
535 &**self >= &**other
536 }
537 }
538
539 #[cfg(feature = "alloc")]
540 impl PartialOrd<str> for UnixString {
541 #[inline]
542 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
543 (&**self).partial_cmp(other)
544 }
545 }
546
547 #[cfg(feature = "alloc")]
548 impl Ord for UnixString {
549 #[inline]
550 fn cmp(&self, other: &Self) -> cmp::Ordering {
551 (&**self).cmp(&**other)
552 }
553 }
554
555 #[cfg(feature = "alloc")]
556 impl Hash for UnixString {
557 #[inline]
558 fn hash<H: Hasher>(&self, state: &mut H) {
559 (&**self).hash(state)
560 }
561 }
562
563 impl UnixStr {
564 /// Coerces into an `UnixStr` slice.
565 ///
566 /// # Examples
567 ///
568 /// ```
569 /// use unix_str::UnixStr;
570 ///
571 /// let unix_str = UnixStr::new("foo");
572 /// ```
573 #[inline]
574 pub fn new<S: AsRef<UnixStr> + ?Sized>(s: &S) -> &UnixStr {
575 s.as_ref()
576 }
577
578 #[inline]
579 fn from_inner(inner: &Slice) -> &UnixStr {
580 // Safety: UnixStr is just a wrapper of Slice,
581 // therefore converting &Slice to &UnixStr is safe.
582 unsafe { &*(inner as *const Slice as *const UnixStr) }
583 }
584
585 #[inline]
586 #[cfg(feature = "alloc")]
587 fn from_inner_mut(inner: &mut Slice) -> &mut UnixStr {
588 // Safety: UnixStr is just a wrapper of Slice,
589 // therefore converting &mut Slice to &mut UnixStr is safe.
590 // Any method that mutates UnixStr must be careful not to
591 // break platform-specific encoding, in particular Wtf8 on Windows.
592 unsafe { &mut *(inner as *mut Slice as *mut UnixStr) }
593 }
594
595 /// Yields a `&str` slice if the `UnixStr` is valid Unicode.
596 ///
597 /// This conversion may entail doing a check for UTF-8 validity.
598 ///
599 /// # Examples
600 ///
601 /// ```
602 /// use unix_str::UnixStr;
603 ///
604 /// let unix_str = UnixStr::new("foo");
605 /// assert_eq!(unix_str.to_str(), Some("foo"));
606 /// ```
607 pub fn to_str(&self) -> Option<&str> {
608 self.inner.to_str()
609 }
610
611 /// Converts an `UnixStr` to a `Cow<str>`.
612 ///
613 /// Any non-Unicode sequences are replaced with
614 /// `U+FFFD REPLACEMENT CHARACTER`.
615 ///
616 ///
617 /// # Examples
618 ///
619 /// Calling `to_string_lossy` on an `UnixStr` with invalid unicode:
620 ///
621 /// ```
622 /// use unix_str::UnixStr;
623 ///
624 /// // Here, the values 0x66 and 0x6f correspond to 'f' and 'o'
625 /// // respectively. The value 0x80 is a lone continuation byte, invalid
626 /// // in a UTF-8 sequence.
627 /// let source = [0x66, 0x6f, 0x80, 0x6f];
628 /// let unix_str = UnixStr::from_bytes(&source[..]);
629 ///
630 /// assert_eq!(unix_str.to_string_lossy(), "fo�o");
631 /// ```
632 #[cfg(feature = "alloc")]
633 pub fn to_string_lossy(&self) -> Cow<'_, str> {
634 self.inner.to_string_lossy()
635 }
636
637 /// Copies the slice into an owned [`UnixString`].
638 ///
639 /// [`UnixString`]: struct.UnixString.html
640 ///
641 /// # Examples
642 ///
643 /// ```
644 /// use unix_str::{UnixStr, UnixString};
645 ///
646 /// let unix_str = UnixStr::new("foo");
647 /// let unix_string = unix_str.to_unix_string();
648 /// assert_eq!(unix_string, UnixString::from("foo"));
649 /// ```
650 #[cfg(feature = "alloc")]
651 pub fn to_unix_string(&self) -> UnixString {
652 UnixString {
653 inner: self.inner.to_owned(),
654 }
655 }
656
657 /// Checks whether the `UnixStr` is empty.
658 ///
659 /// # Examples
660 ///
661 /// ```
662 /// use unix_str::UnixStr;
663 ///
664 /// let unix_str = UnixStr::new("");
665 /// assert!(unix_str.is_empty());
666 ///
667 /// let unix_str = UnixStr::new("foo");
668 /// assert!(!unix_str.is_empty());
669 /// ```
670 #[inline]
671 pub fn is_empty(&self) -> bool {
672 self.inner.inner.is_empty()
673 }
674
675 /// Returns the length of this `UnixStr`.
676 ///
677 /// Note that this does **not** return the number of bytes in the string in
678 /// OS string form.
679 ///
680 /// The length returned is that of the underlying storage used by `UnixStr`.
681 /// As discussed in the [`UnixString`] introduction, [`UnixString`] and
682 /// `UnixStr` store strings in a form best suited for cheap inter-conversion
683 /// between native-platform and Rust string forms, which may differ
684 /// significantly from both of them, including in storage size and encoding.
685 ///
686 /// This number is simply useful for passing to other methods, like
687 /// [`UnixString::with_capacity`] to avoid reallocations.
688 ///
689 /// [`UnixString`]: struct.UnixString.html
690 /// [`UnixString::with_capacity`]: struct.UnixString.html#method.with_capacity
691 ///
692 /// # Examples
693 ///
694 /// ```
695 /// use unix_str::UnixStr;
696 ///
697 /// let unix_str = UnixStr::new("");
698 /// assert_eq!(unix_str.len(), 0);
699 ///
700 /// let unix_str = UnixStr::new("foo");
701 /// assert_eq!(unix_str.len(), 3);
702 /// ```
703 pub fn len(&self) -> usize {
704 self.inner.inner.len()
705 }
706
707 /// Converts a `Box<UnixStr>` into an [`UnixString`] without copying
708 /// allocating.
709 ///
710 /// [`UnixString`]: struct.UnixString.html
711 #[cfg(feature = "alloc")]
712 pub fn into_unix_string(self: Box<UnixStr>) -> UnixString {
713 let boxed = unsafe { Box::from_raw(Box::into_raw(self) as *mut Slice) };
714 UnixString {
715 inner: Buf::from_box(boxed),
716 }
717 }
718
719 /// Gets the underlying byte representation.
720 ///
721 /// Note: it is *crucial* that this API is private, to avoid
722 /// revealing the internal, platform-specific encodings.
723 #[inline]
724 fn bytes(&self) -> &[u8] {
725 unsafe { &*(&self.inner as *const _ as *const [u8]) }
726 }
727
728 /// Converts this string to its ASCII lower case equivalent in-place.
729 ///
730 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z', but non-ASCII letters
731 /// are unchanged.
732 ///
733 /// To return a new lowercased value without modifying the existing one, use
734 /// [`to_ascii_lowercase`].
735 ///
736 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
737 ///
738 /// # Examples
739 ///
740 /// ```
741 /// use unix_str::UnixString;
742 ///
743 /// let mut s = UnixString::from("GRÜßE, JÜRGEN ❤");
744 ///
745 /// s.make_ascii_lowercase();
746 ///
747 /// assert_eq!("grÜße, jÜrgen ❤", s);
748 /// ```
749 #[cfg(feature = "unixstring_ascii")]
750 pub fn make_ascii_lowercase(&mut self) {
751 self.inner.make_ascii_lowercase()
752 }
753
754 /// Converts this string to its ASCII upper case equivalent in-place.
755 ///
756 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
757 /// but non-ASCII letters are unchanged.
758 ///
759 /// To return a new uppercased value without modifying the existing one, use
760 /// [`to_ascii_uppercase`].
761 ///
762 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
763 ///
764 /// # Examples
765 ///
766 /// ```
767 /// use unix_str::UnixString;
768 ///
769 /// let mut s = UnixString::from("Grüße, Jürgen ❤");
770 ///
771 /// s.make_ascii_uppercase();
772 ///
773 /// assert_eq!("GRüßE, JüRGEN ❤", s);
774 /// ```
775 #[cfg(feature = "unixstring_ascii")]
776 pub fn make_ascii_uppercase(&mut self) {
777 self.inner.make_ascii_uppercase()
778 }
779
780 /// Returns a copy of this string where each character is mapped to its
781 /// ASCII lower case equivalent.
782 ///
783 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
784 /// but non-ASCII letters are unchanged.
785 ///
786 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
787 ///
788 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
789 ///
790 /// # Examples
791 ///
792 /// ```
793 /// use unix_str::UnixString;
794 /// let s = UnixString::from("Grüße, Jürgen ❤");
795 ///
796 /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
797 /// ```
798 #[cfg(all(feature = "alloc", feature = "unixstring_ascii"))]
799 pub fn to_ascii_lowercase(&self) -> UnixString {
800 UnixString::from_inner(self.inner.to_ascii_lowercase())
801 }
802
803 /// Returns a copy of this string where each character is mapped to its
804 /// ASCII upper case equivalent.
805 ///
806 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
807 /// but non-ASCII letters are unchanged.
808 ///
809 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
810 ///
811 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
812 ///
813 /// # Examples
814 ///
815 /// ```
816 /// use unix_str::UnixString;
817 /// let s = UnixString::from("Grüße, Jürgen ❤");
818 ///
819 /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
820 /// ```
821 #[cfg(all(feature = "alloc", feature = "unixstring_ascii"))]
822 pub fn to_ascii_uppercase(&self) -> UnixString {
823 UnixString::from_inner(self.inner.to_ascii_uppercase())
824 }
825
826 /// Checks if all characters in this string are within the ASCII range.
827 ///
828 /// # Examples
829 ///
830 /// ```
831 /// use unix_str::UnixString;
832 ///
833 /// let ascii = UnixString::from("hello!\n");
834 /// let non_ascii = UnixString::from("Grüße, Jürgen ❤");
835 ///
836 /// assert!(ascii.is_ascii());
837 /// assert!(!non_ascii.is_ascii());
838 /// ```
839 #[cfg(feature = "unixstring_ascii")]
840 pub fn is_ascii(&self) -> bool {
841 self.inner.is_ascii()
842 }
843
844 /// Checks that two strings are an ASCII case-insensitive match.
845 ///
846 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
847 /// but without allocating and copying temporaries.
848 ///
849 /// # Examples
850 ///
851 /// ```
852 /// use unix_str::UnixString;
853 ///
854 /// assert!(UnixString::from("Ferris").eq_ignore_ascii_case("FERRIS"));
855 /// assert!(UnixString::from("Ferrös").eq_ignore_ascii_case("FERRöS"));
856 /// assert!(!UnixString::from("Ferrös").eq_ignore_ascii_case("FERRÖS"));
857 /// ```
858 #[cfg(feature = "unixstring_ascii")]
859 pub fn eq_ignore_ascii_case<S: ?Sized + AsRef<UnixStr>>(&self, other: &S) -> bool {
860 self.inner.eq_ignore_ascii_case(&other.as_ref().inner)
861 }
862
863 /// Creates a `UnixStr` from a byte slice.
864 ///
865 /// See the module documentation for an example.
866 pub fn from_bytes(slice: &[u8]) -> &Self {
867 unsafe { mem::transmute(slice) }
868 }
869
870 /// Gets the underlying byte view of the `UnixStr` slice.
871 ///
872 /// See the module documentation for an example.
873 pub fn as_bytes(&self) -> &[u8] {
874 &self.as_inner().inner
875 }
876 }
877
878 #[cfg(feature = "alloc")]
879 impl From<&UnixStr> for Box<UnixStr> {
880 fn from(s: &UnixStr) -> Self {
881 let rw = Box::into_raw(s.inner.into_box()) as *mut UnixStr;
882 unsafe { Box::from_raw(rw) }
883 }
884 }
885
886 #[cfg(feature = "alloc")]
887 impl From<Cow<'_, UnixStr>> for Box<UnixStr> {
888 #[inline]
889 fn from(cow: Cow<'_, UnixStr>) -> Self {
890 match cow {
891 Cow::Borrowed(s) => Box::from(s),
892 Cow::Owned(s) => Box::from(s),
893 }
894 }
895 }
896
897 #[cfg(feature = "alloc")]
898 impl From<Box<UnixStr>> for UnixString {
899 /// Converts a `Box<UnixStr>` into a `UnixString` without copying or
900 /// allocating.
901 ///
902 /// [`UnixStr`]: ../ffi/struct.UnixStr.html
903 fn from(boxed: Box<UnixStr>) -> Self {
904 boxed.into_unix_string()
905 }
906 }
907
908 #[cfg(feature = "alloc")]
909 impl From<UnixString> for Box<UnixStr> {
910 /// Converts a [`UnixString`] into a `Box<UnixStr>` without copying or
911 /// allocating.
912 ///
913 /// [`UnixString`]: ../ffi/struct.UnixString.html
914 fn from(s: UnixString) -> Self {
915 s.into_boxed_unix_str()
916 }
917 }
918
919 #[cfg(feature = "alloc")]
920 impl Clone for Box<UnixStr> {
921 #[inline]
922 fn clone(&self) -> Self {
923 self.to_unix_string().into_boxed_unix_str()
924 }
925 }
926
927 #[cfg(feature = "alloc")]
928 impl From<UnixString> for Arc<UnixStr> {
929 /// Converts a [`UnixString`] into a `Arc<UnixStr>` without copying or
930 /// allocating.
931 ///
932 /// [`UnixString`]: ../ffi/struct.UnixString.html
933 #[inline]
934 fn from(s: UnixString) -> Self {
935 let arc = s.inner.into_arc();
936 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const UnixStr) }
937 }
938 }
939
940 #[cfg(feature = "alloc")]
941 impl From<&UnixStr> for Arc<UnixStr> {
942 #[inline]
943 fn from(s: &UnixStr) -> Self {
944 let arc = s.inner.into_arc();
945 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const UnixStr) }
946 }
947 }
948
949 #[cfg(feature = "alloc")]
950 impl From<UnixString> for Rc<UnixStr> {
951 /// Converts a [`UnixString`] into a `Rc<UnixStr>` without copying or
952 /// allocating.
953 ///
954 /// [`UnixString`]: ../ffi/struct.UnixString.html
955 #[inline]
956 fn from(s: UnixString) -> Self {
957 let rc = s.inner.into_rc();
958 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const UnixStr) }
959 }
960 }
961
962 #[cfg(feature = "alloc")]
963 impl From<&UnixStr> for Rc<UnixStr> {
964 #[inline]
965 fn from(s: &UnixStr) -> Self {
966 let rc = s.inner.into_rc();
967 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const UnixStr) }
968 }
969 }
970
971 #[cfg(feature = "alloc")]
972 impl<'a> From<UnixString> for Cow<'a, UnixStr> {
973 #[inline]
974 fn from(s: UnixString) -> Self {
975 Cow::Owned(s)
976 }
977 }
978
979 #[cfg(feature = "alloc")]
980 impl<'a> From<&'a UnixStr> for Cow<'a, UnixStr> {
981 #[inline]
982 fn from(s: &'a UnixStr) -> Self {
983 Cow::Borrowed(s)
984 }
985 }
986
987 #[cfg(feature = "alloc")]
988 impl<'a> From<&'a UnixString> for Cow<'a, UnixStr> {
989 #[inline]
990 fn from(s: &'a UnixString) -> Self {
991 Cow::Borrowed(s.as_unix_str())
992 }
993 }
994
995 #[cfg(feature = "alloc")]
996 impl<'a> From<Cow<'a, UnixStr>> for UnixString {
997 #[inline]
998 fn from(s: Cow<'a, UnixStr>) -> Self {
999 s.into_owned()
1000 }
1001 }
1002
1003 #[cfg(feature = "alloc")]
1004 impl Default for Box<UnixStr> {
1005 fn default() -> Self {
1006 let rw = Box::into_raw(Slice::empty_box()) as *mut UnixStr;
1007 unsafe { Box::from_raw(rw) }
1008 }
1009 }
1010
1011 impl Default for &UnixStr {
1012 /// Creates an empty `UnixStr`.
1013 #[inline]
1014 fn default() -> Self {
1015 UnixStr::new("")
1016 }
1017 }
1018
1019 impl PartialEq for UnixStr {
1020 #[inline]
1021 fn eq(&self, other: &UnixStr) -> bool {
1022 self.bytes().eq(other.bytes())
1023 }
1024 }
1025
1026 impl PartialEq<str> for UnixStr {
1027 #[inline]
1028 fn eq(&self, other: &str) -> bool {
1029 *self == *UnixStr::new(other)
1030 }
1031 }
1032
1033 impl PartialEq<UnixStr> for str {
1034 #[inline]
1035 fn eq(&self, other: &UnixStr) -> bool {
1036 *other == *UnixStr::new(self)
1037 }
1038 }
1039
1040 impl Eq for UnixStr {}
1041
1042 impl PartialOrd for UnixStr {
1043 #[inline]
1044 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
1045 self.bytes().partial_cmp(other.bytes())
1046 }
1047 #[inline]
1048 fn lt(&self, other: &Self) -> bool {
1049 self.bytes().lt(other.bytes())
1050 }
1051 #[inline]
1052 fn le(&self, other: &Self) -> bool {
1053 self.bytes().le(other.bytes())
1054 }
1055 #[inline]
1056 fn gt(&self, other: &Self) -> bool {
1057 self.bytes().gt(other.bytes())
1058 }
1059 #[inline]
1060 fn ge(&self, other: &Self) -> bool {
1061 self.bytes().ge(other.bytes())
1062 }
1063 }
1064
1065 impl PartialOrd<str> for UnixStr {
1066 #[inline]
1067 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
1068 self.partial_cmp(Self::new(other))
1069 }
1070 }
1071
1072 // FIXME (#19470): cannot provide PartialOrd<UnixStr> for str until we
1073 // have more flexible coherence rules.
1074
1075 impl Ord for UnixStr {
1076 #[inline]
1077 fn cmp(&self, other: &Self) -> cmp::Ordering {
1078 self.bytes().cmp(other.bytes())
1079 }
1080 }
1081
1082 #[cfg(feature = "alloc")]
1083 macro_rules! impl_cmp {
1084 ($lhs:ty, $rhs: ty) => {
1085 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1086 #[inline]
1087 fn eq(&self, other: &$rhs) -> bool {
1088 <UnixStr as PartialEq>::eq(self, other)
1089 }
1090 }
1091
1092 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1093 #[inline]
1094 fn eq(&self, other: &$lhs) -> bool {
1095 <UnixStr as PartialEq>::eq(self, other)
1096 }
1097 }
1098
1099 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
1100 #[inline]
1101 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
1102 <UnixStr as PartialOrd>::partial_cmp(self, other)
1103 }
1104 }
1105
1106 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
1107 #[inline]
1108 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
1109 <UnixStr as PartialOrd>::partial_cmp(self, other)
1110 }
1111 }
1112 };
1113 }
1114
1115 #[cfg(feature = "alloc")]
1116 impl_cmp!(UnixString, UnixStr);
1117 #[cfg(feature = "alloc")]
1118 impl_cmp!(UnixString, &'a UnixStr);
1119 #[cfg(feature = "alloc")]
1120 impl_cmp!(Cow<'a, UnixStr>, UnixStr);
1121 #[cfg(feature = "alloc")]
1122 impl_cmp!(Cow<'a, UnixStr>, &'b UnixStr);
1123 #[cfg(feature = "alloc")]
1124 impl_cmp!(Cow<'a, UnixStr>, UnixString);
1125
1126 impl Hash for UnixStr {
1127 #[inline]
1128 fn hash<H: Hasher>(&self, state: &mut H) {
1129 self.bytes().hash(state)
1130 }
1131 }
1132
1133 impl fmt::Debug for UnixStr {
1134 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1135 fmt::Debug::fmt(&self.inner, formatter)
1136 }
1137 }
1138
1139 #[cfg(feature = "alloc")]
1140 impl Borrow<UnixStr> for UnixString {
1141 fn borrow(&self) -> &UnixStr {
1142 &self[..]
1143 }
1144 }
1145
1146 #[cfg(feature = "alloc")]
1147 impl ToOwned for UnixStr {
1148 type Owned = UnixString;
1149 fn to_owned(&self) -> Self::Owned {
1150 self.to_unix_string()
1151 }
1152 #[cfg(feature = "toowned_clone_into")]
1153 fn clone_into(&self, target: &mut Self::Owned) {
1154 self.inner.clone_into(&mut target.inner)
1155 }
1156 }
1157
1158 impl AsRef<UnixStr> for UnixStr {
1159 fn as_ref(&self) -> &UnixStr {
1160 self
1161 }
1162 }
1163
1164 #[cfg(feature = "alloc")]
1165 impl AsRef<UnixStr> for UnixString {
1166 #[inline]
1167 fn as_ref(&self) -> &UnixStr {
1168 self
1169 }
1170 }
1171
1172 impl AsRef<UnixStr> for str {
1173 #[inline]
1174 fn as_ref(&self) -> &UnixStr {
1175 UnixStr::from_inner(Slice::from_str(self))
1176 }
1177 }
1178
1179 #[cfg(feature = "alloc")]
1180 impl AsRef<UnixStr> for String {
1181 #[inline]
1182 fn as_ref(&self) -> &UnixStr {
1183 (&**self).as_ref()
1184 }
1185 }
1186
1187 #[cfg(feature = "alloc")]
1188 impl FromInner<Buf> for UnixString {
1189 fn from_inner(buf: Buf) -> UnixString {
1190 UnixString { inner: buf }
1191 }
1192 }
1193
1194 #[cfg(feature = "alloc")]
1195 impl IntoInner<Buf> for UnixString {
1196 fn into_inner(self) -> Buf {
1197 self.inner
1198 }
1199 }
1200
1201 impl AsInner<Slice> for UnixStr {
1202 #[inline]
1203 fn as_inner(&self) -> &Slice {
1204 &self.inner
1205 }
1206 }
1207
1208 #[cfg(feature = "alloc")]
1209 impl FromStr for UnixString {
1210 type Err = core::convert::Infallible;
1211
1212 fn from_str(s: &str) -> Result<Self, Self::Err> {
1213 Ok(UnixString::from(s))
1214 }
1215 }
1216
1217 #[cfg(test)]
1218 mod tests {
1219 use super::*;
1220 use sys_common::{AsInner, IntoInner};
1221
1222 use alloc::rc::Rc;
1223 use alloc::sync::Arc;
1224
1225 #[test]
1226 fn test_unix_string_with_capacity() {
1227 let unix_string = UnixString::with_capacity(0);
1228 assert_eq!(0, unix_string.inner.into_inner().capacity());
1229
1230 let unix_string = UnixString::with_capacity(10);
1231 assert_eq!(10, unix_string.inner.into_inner().capacity());
1232
1233 let mut unix_string = UnixString::with_capacity(0);
1234 unix_string.push("abc");
1235 assert!(unix_string.inner.into_inner().capacity() >= 3);
1236 }
1237
1238 #[test]
1239 fn test_unix_string_clear() {
1240 let mut unix_string = UnixString::from("abc");
1241 assert_eq!(3, unix_string.inner.as_inner().len());
1242
1243 unix_string.clear();
1244 assert_eq!(&unix_string, "");
1245 assert_eq!(0, unix_string.inner.as_inner().len());
1246 }
1247
1248 #[test]
1249 fn test_unix_string_capacity() {
1250 let unix_string = UnixString::with_capacity(0);
1251 assert_eq!(0, unix_string.capacity());
1252
1253 let unix_string = UnixString::with_capacity(10);
1254 assert_eq!(10, unix_string.capacity());
1255
1256 let mut unix_string = UnixString::with_capacity(0);
1257 unix_string.push("abc");
1258 assert!(unix_string.capacity() >= 3);
1259 }
1260
1261 #[test]
1262 fn test_unix_string_reserve() {
1263 let mut unix_string = UnixString::new();
1264 assert_eq!(unix_string.capacity(), 0);
1265
1266 unix_string.reserve(2);
1267 assert!(unix_string.capacity() >= 2);
1268
1269 for _ in 0..16 {
1270 unix_string.push("a");
1271 }
1272
1273 assert!(unix_string.capacity() >= 16);
1274 unix_string.reserve(16);
1275 assert!(unix_string.capacity() >= 32);
1276
1277 unix_string.push("a");
1278
1279 unix_string.reserve(16);
1280 assert!(unix_string.capacity() >= 33)
1281 }
1282
1283 #[test]
1284 fn test_unix_string_reserve_exact() {
1285 let mut unix_string = UnixString::new();
1286 assert_eq!(unix_string.capacity(), 0);
1287
1288 unix_string.reserve_exact(2);
1289 assert!(unix_string.capacity() >= 2);
1290
1291 for _ in 0..16 {
1292 unix_string.push("a");
1293 }
1294
1295 assert!(unix_string.capacity() >= 16);
1296 unix_string.reserve_exact(16);
1297 assert!(unix_string.capacity() >= 32);
1298
1299 unix_string.push("a");
1300
1301 unix_string.reserve_exact(16);
1302 assert!(unix_string.capacity() >= 33)
1303 }
1304
1305 #[test]
1306 fn test_unix_string_default() {
1307 let unix_string: UnixString = Default::default();
1308 assert_eq!("", &unix_string);
1309 }
1310
1311 #[test]
1312 fn test_unix_str_is_empty() {
1313 let mut unix_string = UnixString::new();
1314 assert!(unix_string.is_empty());
1315
1316 unix_string.push("abc");
1317 assert!(!unix_string.is_empty());
1318
1319 unix_string.clear();
1320 assert!(unix_string.is_empty());
1321 }
1322
1323 #[test]
1324 fn test_unix_str_len() {
1325 let mut unix_string = UnixString::new();
1326 assert_eq!(0, unix_string.len());
1327
1328 unix_string.push("abc");
1329 assert_eq!(3, unix_string.len());
1330
1331 unix_string.clear();
1332 assert_eq!(0, unix_string.len());
1333 }
1334
1335 #[test]
1336 fn test_unix_str_default() {
1337 let unix_str: &UnixStr = Default::default();
1338 assert_eq!("", unix_str);
1339 }
1340
1341 #[test]
1342 fn into_boxed() {
1343 let orig = "Hello, world!";
1344 let unix_str = UnixStr::new(orig);
1345 let boxed: Box<UnixStr> = Box::from(unix_str);
1346 let unix_string = unix_str.to_owned().into_boxed_unix_str().into_unix_string();
1347 assert_eq!(unix_str, &*boxed);
1348 assert_eq!(&*boxed, &*unix_string);
1349 assert_eq!(&*unix_string, unix_str);
1350 }
1351
1352 #[test]
1353 fn boxed_default() {
1354 let boxed = <Box<UnixStr>>::default();
1355 assert!(boxed.is_empty());
1356 }
1357
1358 #[test]
1359 #[cfg(feature = "toowned_clone_into")]
1360 fn test_unix_str_clone_into() {
1361 let mut unix_string = UnixString::with_capacity(123);
1362 unix_string.push("hello");
1363 let unix_str = UnixStr::new("bonjour");
1364 unix_str.clone_into(&mut unix_string);
1365 assert_eq!(unix_str, unix_string);
1366 assert!(unix_string.capacity() >= 123);
1367 }
1368
1369 #[test]
1370 fn into_rc() {
1371 let orig = "Hello, world!";
1372 let unix_str = UnixStr::new(orig);
1373 let rc: Rc<UnixStr> = Rc::from(unix_str);
1374 let arc: Arc<UnixStr> = Arc::from(unix_str);
1375
1376 assert_eq!(&*rc, unix_str);
1377 assert_eq!(&*arc, unix_str);
1378
1379 let rc2: Rc<UnixStr> = Rc::from(unix_str.to_owned());
1380 let arc2: Arc<UnixStr> = Arc::from(unix_str.to_owned());
1381
1382 assert_eq!(&*rc2, unix_str);
1383 assert_eq!(&*arc2, unix_str);
1384 }
1385 }