Debian Codegraph @

src/ascii_string.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use alloc::borrow::{Borrow, BorrowMut, Cow, ToOwned};
2 use alloc::fmt;
3 use alloc::string::String;
4 use alloc::vec::Vec;
5 use alloc::boxed::Box;
6 use alloc::rc::Rc;
7 use alloc::sync::Arc;
8 #[cfg(feature = "std")]
9 use core::any::Any;
10 use core::iter::FromIterator;
11 use core::mem;
12 use core::ops::{Add, AddAssign, Deref, DerefMut, Index, IndexMut};
13 use core::str::FromStr;
14 #[cfg(feature = "std")]
15 use std::error::Error;
16 #[cfg(feature = "std")]
17 use std::ffi::{CStr, CString};
18
19 use ascii_char::AsciiChar;
20 use ascii_str::{AsAsciiStr, AsAsciiStrError, AsciiStr};
21
22 /// A growable string stored as an ASCII encoded buffer.
23 #[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
24 #[repr(transparent)]
25 pub struct AsciiString {
26 vec: Vec<AsciiChar>,
27 }
28
29 impl AsciiString {
30 /// Creates a new, empty ASCII string buffer without allocating.
31 ///
32 /// # Examples
33 /// ```
34 /// # use ascii::AsciiString;
35 /// let mut s = AsciiString::new();
36 /// ```
37 #[inline]
38 #[must_use]
39 pub const fn new() -> Self {
40 AsciiString { vec: Vec::new() }
41 }
42
43 /// Creates a new ASCII string buffer with the given capacity.
44 /// The string will be able to hold exactly `capacity` bytes without reallocating.
45 /// If `capacity` is 0, the ASCII string will not allocate.
46 ///
47 /// # Examples
48 /// ```
49 /// # use ascii::AsciiString;
50 /// let mut s = AsciiString::with_capacity(10);
51 /// ```
52 #[inline]
53 #[must_use]
54 pub fn with_capacity(capacity: usize) -> Self {
55 AsciiString {
56 vec: Vec::with_capacity(capacity),
57 }
58 }
59
60 /// Creates a new `AsciiString` from a length, capacity and pointer.
61 ///
62 /// # Safety
63 ///
64 /// This is highly unsafe, due to the number of invariants that aren't checked:
65 ///
66 /// * The memory at `buf` need to have been previously allocated by the same allocator this
67 /// library uses, with an alignment of 1.
68 /// * `length` needs to be less than or equal to `capacity`.
69 /// * `capacity` needs to be the correct value.
70 /// * `buf` must have `length` valid ascii elements and contain a total of `capacity` total,
71 /// possibly, uninitialized, elements.
72 /// * Nothing else must be using the memory `buf` points to.
73 ///
74 /// Violating these may cause problems like corrupting the allocator's internal data structures.
75 ///
76 /// # Examples
77 ///
78 /// Basic usage:
79 ///
80 /// ```
81 /// # use ascii::AsciiString;
82 /// use std::mem;
83 ///
84 /// unsafe {
85 /// let mut s = AsciiString::from_ascii("hello").unwrap();
86 /// let ptr = s.as_mut_ptr();
87 /// let len = s.len();
88 /// let capacity = s.capacity();
89 ///
90 /// mem::forget(s);
91 ///
92 /// let s = AsciiString::from_raw_parts(ptr, len, capacity);
93 ///
94 /// assert_eq!(AsciiString::from_ascii("hello").unwrap(), s);
95 /// }
96 /// ```
97 #[inline]
98 #[must_use]
99 pub unsafe fn from_raw_parts(buf: *mut AsciiChar, length: usize, capacity: usize) -> Self {
100 AsciiString {
101 // SAFETY: Caller guarantees that `buf` was previously allocated by this library,
102 // that `buf` contains `length` valid ascii elements and has a total capacity
103 // of `capacity` elements, and that nothing else is using the momory.
104 vec: unsafe { Vec::from_raw_parts(buf, length, capacity) },
105 }
106 }
107
108 /// Converts a vector of bytes to an `AsciiString` without checking for non-ASCII characters.
109 ///
110 /// # Safety
111 /// This function is unsafe because it does not check that the bytes passed to it are valid
112 /// ASCII characters. If this constraint is violated, it may cause memory unsafety issues with
113 /// future of the `AsciiString`, as the rest of this library assumes that `AsciiString`s are
114 /// ASCII encoded.
115 #[inline]
116 #[must_use]
117 pub unsafe fn from_ascii_unchecked<B>(bytes: B) -> Self
118 where
119 B: Into<Vec<u8>>,
120 {
121 let mut bytes = bytes.into();
122 // SAFETY: The caller guarantees all bytes are valid ascii bytes.
123 let ptr = bytes.as_mut_ptr().cast::<AsciiChar>();
124 let length = bytes.len();
125 let capacity = bytes.capacity();
126 mem::forget(bytes);
127
128 // SAFETY: We guarantee all invariants, as we got the
129 // pointer, length and capacity from a `Vec`,
130 // and we also guarantee the pointer is valid per
131 // the `SAFETY` notice above.
132 let vec = Vec::from_raw_parts(ptr, length, capacity);
133
134 Self { vec }
135 }
136
137 /// Converts anything that can represent a byte buffer into an `AsciiString`.
138 ///
139 /// # Errors
140 /// Returns the byte buffer if not all of the bytes are ASCII characters.
141 ///
142 /// # Examples
143 /// ```
144 /// # use ascii::AsciiString;
145 /// let foo = AsciiString::from_ascii("foo".to_string()).unwrap();
146 /// let err = AsciiString::from_ascii("Ŋ".to_string()).unwrap_err();
147 /// assert_eq!(foo.as_str(), "foo");
148 /// assert_eq!(err.into_source(), "Ŋ");
149 /// ```
150 pub fn from_ascii<B>(bytes: B) -> Result<AsciiString, FromAsciiError<B>>
151 where
152 B: Into<Vec<u8>> + AsRef<[u8]>,
153 {
154 match bytes.as_ref().as_ascii_str() {
155 // SAFETY: `as_ascii_str` guarantees all bytes are valid ascii bytes.
156 Ok(_) => Ok(unsafe { AsciiString::from_ascii_unchecked(bytes) }),
157 Err(e) => Err(FromAsciiError {
158 error: e,
159 owner: bytes,
160 }),
161 }
162 }
163
164 /// Pushes the given ASCII string onto this ASCII string buffer.
165 ///
166 /// # Examples
167 /// ```
168 /// # use ascii::{AsciiString, AsAsciiStr};
169 /// use std::str::FromStr;
170 /// let mut s = AsciiString::from_str("foo").unwrap();
171 /// s.push_str("bar".as_ascii_str().unwrap());
172 /// assert_eq!(s, "foobar".as_ascii_str().unwrap());
173 /// ```
174 #[inline]
175 pub fn push_str(&mut self, string: &AsciiStr) {
176 self.vec.extend(string.chars());
177 }
178
179 /// Inserts the given ASCII string at the given place in this ASCII string buffer.
180 ///
181 /// # Panics
182 ///
183 /// Panics if `idx` is larger than the `AsciiString`'s length.
184 ///
185 /// # Examples
186 /// ```
187 /// # use ascii::{AsciiString, AsAsciiStr};
188 /// use std::str::FromStr;
189 /// let mut s = AsciiString::from_str("abc").unwrap();
190 /// s.insert_str(1, "def".as_ascii_str().unwrap());
191 /// assert_eq!(&*s, "adefbc");
192 #[inline]
193 pub fn insert_str(&mut self, idx: usize, string: &AsciiStr) {
194 self.vec.reserve(string.len());
195 self.vec.splice(idx..idx, string.into_iter().copied());
196 }
197
198 /// Returns the number of bytes that this ASCII string buffer can hold without reallocating.
199 ///
200 /// # Examples
201 /// ```
202 /// # use ascii::AsciiString;
203 /// let s = String::with_capacity(10);
204 /// assert!(s.capacity() >= 10);
205 /// ```
206 #[inline]
207 #[must_use]
208 pub fn capacity(&self) -> usize {
209 self.vec.capacity()
210 }
211
212 /// Reserves capacity for at least `additional` more bytes to be inserted in the given
213 /// `AsciiString`. The collection may reserve more space to avoid frequent reallocations.
214 ///
215 /// # Panics
216 /// Panics if the new capacity overflows `usize`.
217 ///
218 /// # Examples
219 /// ```
220 /// # use ascii::AsciiString;
221 /// let mut s = AsciiString::new();
222 /// s.reserve(10);
223 /// assert!(s.capacity() >= 10);
224 /// ```
225 #[inline]
226 pub fn reserve(&mut self, additional: usize) {
227 self.vec.reserve(additional);
228 }
229
230 /// Reserves the minimum capacity for exactly `additional` more bytes to be inserted in the
231 /// given `AsciiString`. Does nothing if the capacity is already sufficient.
232 ///
233 /// Note that the allocator may give the collection more space than it requests. Therefore
234 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
235 /// insertions are expected.
236 ///
237 /// # Panics
238 /// Panics if the new capacity overflows `usize`.
239 ///
240 /// # Examples
241 /// ```
242 /// # use ascii::AsciiString;
243 /// let mut s = AsciiString::new();
244 /// s.reserve_exact(10);
245 /// assert!(s.capacity() >= 10);
246 /// ```
247 #[inline]
248
249 pub fn reserve_exact(&mut self, additional: usize) {
250 self.vec.reserve_exact(additional);
251 }
252
253 /// Shrinks the capacity of this ASCII string buffer to match it's length.
254 ///
255 /// # Examples
256 /// ```
257 /// # use ascii::AsciiString;
258 /// use std::str::FromStr;
259 /// let mut s = AsciiString::from_str("foo").unwrap();
260 /// s.reserve(100);
261 /// assert!(s.capacity() >= 100);
262 /// s.shrink_to_fit();
263 /// assert_eq!(s.capacity(), 3);
264 /// ```
265 #[inline]
266
267 pub fn shrink_to_fit(&mut self) {
268 self.vec.shrink_to_fit();
269 }
270
271 /// Adds the given ASCII character to the end of the ASCII string.
272 ///
273 /// # Examples
274 /// ```
275 /// # use ascii::{ AsciiChar, AsciiString};
276 /// let mut s = AsciiString::from_ascii("abc").unwrap();
277 /// s.push(AsciiChar::from_ascii('1').unwrap());
278 /// s.push(AsciiChar::from_ascii('2').unwrap());
279 /// s.push(AsciiChar::from_ascii('3').unwrap());
280 /// assert_eq!(s, "abc123");
281 /// ```
282 #[inline]
283
284 pub fn push(&mut self, ch: AsciiChar) {
285 self.vec.push(ch);
286 }
287
288 /// Shortens a ASCII string to the specified length.
289 ///
290 /// # Panics
291 /// Panics if `new_len` > current length.
292 ///
293 /// # Examples
294 /// ```
295 /// # use ascii::AsciiString;
296 /// let mut s = AsciiString::from_ascii("hello").unwrap();
297 /// s.truncate(2);
298 /// assert_eq!(s, "he");
299 /// ```
300 #[inline]
301
302 pub fn truncate(&mut self, new_len: usize) {
303 self.vec.truncate(new_len);
304 }
305
306 /// Removes the last character from the ASCII string buffer and returns it.
307 /// Returns `None` if this string buffer is empty.
308 ///
309 /// # Examples
310 /// ```
•311 /// # #![allow(bindings_with_variant_name)]
312 /// # use ascii::AsciiString;
313 /// let mut s = AsciiString::from_ascii("foo").unwrap();
314 /// assert_eq!(s.pop().map(|c| c.as_char()), Some('o'));
315 /// assert_eq!(s.pop().map(|c| c.as_char()), Some('o'));
316 /// assert_eq!(s.pop().map(|c| c.as_char()), Some('f'));
317 /// assert_eq!(s.pop(), None);
318 /// ```
319 #[inline]
320 #[must_use]
321 pub fn pop(&mut self) -> Option<AsciiChar> {
322 self.vec.pop()
323 }
324
325 /// Removes the ASCII character at position `idx` from the buffer and returns it.
326 ///
327 /// # Warning
328 /// This is an O(n) operation as it requires copying every element in the buffer.
329 ///
330 /// # Panics
331 /// If `idx` is out of bounds this function will panic.
332 ///
333 /// # Examples
334 /// ```
335 /// # use ascii::AsciiString;
336 /// let mut s = AsciiString::from_ascii("foo").unwrap();
337 /// assert_eq!(s.remove(0).as_char(), 'f');
338 /// assert_eq!(s.remove(1).as_char(), 'o');
339 /// assert_eq!(s.remove(0).as_char(), 'o');
340 /// ```
341 #[inline]
342 #[must_use]
343 pub fn remove(&mut self, idx: usize) -> AsciiChar {
344 self.vec.remove(idx)
345 }
346
347 /// Inserts an ASCII character into the buffer at position `idx`.
348 ///
349 /// # Warning
350 /// This is an O(n) operation as it requires copying every element in the buffer.
351 ///
352 /// # Panics
353 /// If `idx` is out of bounds this function will panic.
354 ///
355 /// # Examples
356 /// ```
357 /// # use ascii::{AsciiString,AsciiChar};
358 /// let mut s = AsciiString::from_ascii("foo").unwrap();
359 /// s.insert(2, AsciiChar::b);
360 /// assert_eq!(s, "fobo");
361 /// ```
362 #[inline]
363
364 pub fn insert(&mut self, idx: usize, ch: AsciiChar) {
365 self.vec.insert(idx, ch);
366 }
367
368 /// Returns the number of bytes in this ASCII string.
369 ///
370 /// # Examples
371 /// ```
372 /// # use ascii::AsciiString;
373 /// let s = AsciiString::from_ascii("foo").unwrap();
374 /// assert_eq!(s.len(), 3);
375 /// ```
376 #[inline]
377 #[must_use]
378 pub fn len(&self) -> usize {
379 self.vec.len()
380 }
381
382 /// Returns true if the ASCII string contains zero bytes.
383 ///
384 /// # Examples
385 /// ```
386 /// # use ascii::{AsciiChar, AsciiString};
387 /// let mut s = AsciiString::new();
388 /// assert!(s.is_empty());
389 /// s.push(AsciiChar::from_ascii('a').unwrap());
390 /// assert!(!s.is_empty());
391 /// ```
392 #[inline]
393 #[must_use]
394 pub fn is_empty(&self) -> bool {
395 self.len() == 0
396 }
397
398 /// Truncates the ASCII string, setting length (but not capacity) to zero.
399 ///
400 /// # Examples
401 /// ```
402 /// # use ascii::AsciiString;
403 /// let mut s = AsciiString::from_ascii("foo").unwrap();
404 /// s.clear();
405 /// assert!(s.is_empty());
406 /// ```
407 #[inline]
408
409 pub fn clear(&mut self) {
410 self.vec.clear();
411 }
412
413 /// Converts this [`AsciiString`] into a [`Box`]`<`[`AsciiStr`]`>`.
414 ///
415 /// This will drop any excess capacity
416 #[inline]
417 #[must_use]
418 pub fn into_boxed_ascii_str(self) -> Box<AsciiStr> {
419 let slice = self.vec.into_boxed_slice();
420 Box::from(slice)
421 }
422 }
423
424 impl Deref for AsciiString {
425 type Target = AsciiStr;
426
427 #[inline]
428 fn deref(&self) -> &AsciiStr {
429 self.vec.as_slice().as_ref()
430 }
431 }
432
433 impl DerefMut for AsciiString {
434 #[inline]
435 fn deref_mut(&mut self) -> &mut AsciiStr {
436 self.vec.as_mut_slice().as_mut()
437 }
438 }
439
440 impl PartialEq<str> for AsciiString {
441 #[inline]
442 fn eq(&self, other: &str) -> bool {
443 **self == *other
444 }
445 }
446
447 impl PartialEq<AsciiString> for str {
448 #[inline]
449 fn eq(&self, other: &AsciiString) -> bool {
450 **other == *self
451 }
452 }
453
454 macro_rules! impl_eq {
455 ($lhs:ty, $rhs:ty) => {
456 impl PartialEq<$rhs> for $lhs {
457 #[inline]
458 fn eq(&self, other: &$rhs) -> bool {
459 PartialEq::eq(&**self, &**other)
460 }
461 }
462 };
463 }
464
465 impl_eq! { AsciiString, String }
466 impl_eq! { String, AsciiString }
467 impl_eq! { &AsciiStr, String }
468 impl_eq! { String, &AsciiStr }
469 impl_eq! { &AsciiStr, AsciiString }
470 impl_eq! { AsciiString, &AsciiStr }
471 impl_eq! { &str, AsciiString }
472 impl_eq! { AsciiString, &str }
473
474 impl Borrow<AsciiStr> for AsciiString {
475 #[inline]
476 fn borrow(&self) -> &AsciiStr {
477 &**self
478 }
479 }
480
481 impl BorrowMut<AsciiStr> for AsciiString {
482 #[inline]
483 fn borrow_mut(&mut self) -> &mut AsciiStr {
484 &mut **self
485 }
486 }
487
488 impl From<Vec<AsciiChar>> for AsciiString {
489 #[inline]
490 fn from(vec: Vec<AsciiChar>) -> Self {
491 AsciiString { vec }
492 }
493 }
494
495 impl From<AsciiChar> for AsciiString {
496 #[inline]
497 fn from(ch: AsciiChar) -> Self {
498 AsciiString { vec: vec![ch] }
499 }
500 }
501
502 impl From<AsciiString> for Vec<u8> {
503 fn from(mut s: AsciiString) -> Vec<u8> {
504 // SAFETY: All ascii bytes are valid `u8`, as we are `repr(u8)`.
505 // Note: We forget `self` to avoid `self.vec` from being deallocated.
506 let ptr = s.vec.as_mut_ptr().cast::<u8>();
507 let length = s.vec.len();
508 let capacity = s.vec.capacity();
509 mem::forget(s);
510
511 // SAFETY: We guarantee all invariants due to getting `ptr`, `length`
512 // and `capacity` from a `Vec`. We also guarantee `ptr` is valid
513 // due to the `SAFETY` block above.
514 unsafe { Vec::from_raw_parts(ptr, length, capacity) }
515 }
516 }
517
518 impl From<AsciiString> for Vec<AsciiChar> {
519 fn from(s: AsciiString) -> Vec<AsciiChar> {
520 s.vec
521 }
522 }
523
524 impl<'a> From<&'a AsciiStr> for AsciiString {
525 #[inline]
526 fn from(s: &'a AsciiStr) -> Self {
527 s.to_ascii_string()
528 }
529 }
530
531 impl<'a> From<&'a [AsciiChar]> for AsciiString {
532 #[inline]
533 fn from(s: &'a [AsciiChar]) -> AsciiString {
534 s.iter().copied().collect()
535 }
536 }
537
538 impl From<AsciiString> for String {
539 #[inline]
540 fn from(s: AsciiString) -> String {
541 // SAFETY: All ascii bytes are `utf8`.
542 unsafe { String::from_utf8_unchecked(s.into()) }
543 }
544 }
545
546 impl From<Box<AsciiStr>> for AsciiString {
547 #[inline]
548 fn from(boxed: Box<AsciiStr>) -> Self {
549 boxed.into_ascii_string()
550 }
551 }
552
553 impl From<AsciiString> for Box<AsciiStr> {
554 #[inline]
555 fn from(string: AsciiString) -> Self {
556 string.into_boxed_ascii_str()
557 }
558 }
559
560 impl From<AsciiString> for Rc<AsciiStr> {
561 fn from(s: AsciiString) -> Rc<AsciiStr> {
562 let var: Rc<[AsciiChar]> = s.vec.into();
563 // SAFETY: AsciiStr is repr(transparent) and thus has the same layout as [AsciiChar]
564 unsafe { Rc::from_raw(Rc::into_raw(var) as *const AsciiStr) }
565 }
566 }
567
568 impl From<AsciiString> for Arc<AsciiStr> {
569 fn from(s: AsciiString) -> Arc<AsciiStr> {
570 let var: Arc<[AsciiChar]> = s.vec.into();
571 // SAFETY: AsciiStr is repr(transparent) and thus has the same layout as [AsciiChar]
572 unsafe { Arc::from_raw(Arc::into_raw(var) as *const AsciiStr) }
573 }
574 }
575
576 impl<'a> From<Cow<'a, AsciiStr>> for AsciiString {
577 fn from(cow: Cow<'a, AsciiStr>) -> AsciiString {
578 cow.into_owned()
579 }
580 }
581
582 impl From<AsciiString> for Cow<'static, AsciiStr> {
583 fn from(string: AsciiString) -> Cow<'static, AsciiStr> {
584 Cow::Owned(string)
585 }
586 }
587
588 impl<'a> From<&'a AsciiStr> for Cow<'a, AsciiStr> {
589 fn from(s: &'a AsciiStr) -> Cow<'a, AsciiStr> {
590 Cow::Borrowed(s)
591 }
592 }
593
594 impl AsRef<AsciiStr> for AsciiString {
595 #[inline]
596 fn as_ref(&self) -> &AsciiStr {
597 &**self
598 }
599 }
600
601 impl AsRef<[AsciiChar]> for AsciiString {
602 #[inline]
603 fn as_ref(&self) -> &[AsciiChar] {
604 &self.vec
605 }
606 }
607
608 impl AsRef<[u8]> for AsciiString {
609 #[inline]
610 fn as_ref(&self) -> &[u8] {
611 self.as_bytes()
612 }
613 }
614
615 impl AsRef<str> for AsciiString {
616 #[inline]
617 fn as_ref(&self) -> &str {
618 self.as_str()
619 }
620 }
621
622 impl AsMut<AsciiStr> for AsciiString {
623 #[inline]
624 fn as_mut(&mut self) -> &mut AsciiStr {
625 &mut *self
626 }
627 }
628
629 impl AsMut<[AsciiChar]> for AsciiString {
630 #[inline]
631 fn as_mut(&mut self) -> &mut [AsciiChar] {
632 &mut self.vec
633 }
634 }
635
636 impl FromStr for AsciiString {
637 type Err = AsAsciiStrError;
638
639 fn from_str(s: &str) -> Result<AsciiString, AsAsciiStrError> {
640 s.as_ascii_str().map(AsciiStr::to_ascii_string)
641 }
642 }
643
644 impl fmt::Display for AsciiString {
645 #[inline]
646 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
647 fmt::Display::fmt(&**self, f)
648 }
649 }
650
651 impl fmt::Debug for AsciiString {
652 #[inline]
653 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
654 fmt::Debug::fmt(&**self, f)
655 }
656 }
657
658 /// Please note that the `std::fmt::Result` returned by these methods does not support
659 /// transmission of an error other than that an error occurred.
660 impl fmt::Write for AsciiString {
661 fn write_str(&mut self, s: &str) -> fmt::Result {
662 if let Ok(astr) = AsciiStr::from_ascii(s) {
663 self.push_str(astr);
664 Ok(())
665 } else {
666 Err(fmt::Error)
667 }
668 }
669
670 fn write_char(&mut self, c: char) -> fmt::Result {
671 if let Ok(achar) = AsciiChar::from_ascii(c) {
672 self.push(achar);
673 Ok(())
674 } else {
675 Err(fmt::Error)
676 }
677 }
678 }
679
680 impl<A: AsRef<AsciiStr>> FromIterator<A> for AsciiString {
681 fn from_iter<I: IntoIterator<Item = A>>(iter: I) -> AsciiString {
682 let mut buf = AsciiString::new();
683 buf.extend(iter);
684 buf
685 }
686 }
687
688 impl<A: AsRef<AsciiStr>> Extend<A> for AsciiString {
689 fn extend<I: IntoIterator<Item = A>>(&mut self, iterable: I) {
690 let iterator = iterable.into_iter();
691 let (lower_bound, _) = iterator.size_hint();
692 self.reserve(lower_bound);
693 for item in iterator {
694 self.push_str(item.as_ref());
695 }
696 }
697 }
698
699 impl<'a> Add<&'a AsciiStr> for AsciiString {
700 type Output = AsciiString;
701
702 #[inline]
703 fn add(mut self, other: &AsciiStr) -> AsciiString {
704 self.push_str(other);
705 self
706 }
707 }
708
709 impl<'a> AddAssign<&'a AsciiStr> for AsciiString {
710 #[inline]
711 fn add_assign(&mut self, other: &AsciiStr) {
712 self.push_str(other);
713 }
714 }
715
716 #[allow(clippy::indexing_slicing)] // In `Index`, if it's out of bounds, panic is the default
717 impl<T> Index<T> for AsciiString
718 where
719 AsciiStr: Index<T>,
720 {
721 type Output = <AsciiStr as Index<T>>::Output;
722
723 #[inline]
724 fn index(&self, index: T) -> &<AsciiStr as Index<T>>::Output {
725 &(**self)[index]
726 }
727 }
728
729 #[allow(clippy::indexing_slicing)] // In `IndexMut`, if it's out of bounds, panic is the default
730 impl<T> IndexMut<T> for AsciiString
731 where
732 AsciiStr: IndexMut<T>,
733 {
734 #[inline]
735 fn index_mut(&mut self, index: T) -> &mut <AsciiStr as Index<T>>::Output {
736 &mut (**self)[index]
737 }
738 }
739
740 /// A possible error value when converting an `AsciiString` from a byte vector or string.
741 /// It wraps an `AsAsciiStrError` which you can get through the `ascii_error()` method.
742 ///
743 /// This is the error type for `AsciiString::from_ascii()` and
744 /// `IntoAsciiString::into_ascii_string()`. They will never clone or touch the content of the
745 /// original type; It can be extracted by the `into_source` method.
746 ///
747 /// #Examples
748 /// ```
749 /// # use ascii::IntoAsciiString;
750 /// let err = "bø!".to_string().into_ascii_string().unwrap_err();
751 /// assert_eq!(err.ascii_error().valid_up_to(), 1);
752 /// assert_eq!(err.into_source(), "bø!".to_string());
753 /// ```
754 #[derive(Clone, Copy, PartialEq, Eq)]
755 pub struct FromAsciiError<O> {
756 error: AsAsciiStrError,
757 owner: O,
758 }
759 impl<O> FromAsciiError<O> {
760 /// Get the position of the first non-ASCII byte or character.
761 #[inline]
762 #[must_use]
763 pub fn ascii_error(&self) -> AsAsciiStrError {
764 self.error
765 }
766 /// Get back the original, unmodified type.
767 #[inline]
768 #[must_use]
769 pub fn into_source(self) -> O {
770 self.owner
771 }
772 }
773 impl<O> fmt::Debug for FromAsciiError<O> {
774 #[inline]
775 fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
776 fmt::Debug::fmt(&self.error, fmtr)
777 }
778 }
779 impl<O> fmt::Display for FromAsciiError<O> {
780 #[inline]
781 fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
782 fmt::Display::fmt(&self.error, fmtr)
783 }
784 }
785 #[cfg(feature = "std")]
786 impl<O: Any> Error for FromAsciiError<O> {
787 #[inline]
788 #[allow(deprecated)] // TODO: Remove deprecation once the earliest version we support deprecates this method.
789 fn description(&self) -> &str {
790 self.error.description()
791 }
792 /// Always returns an `AsAsciiStrError`
793 fn cause(&self) -> Option<&dyn Error> {
794 Some(&self.error as &dyn Error)
795 }
796 }
797
798 /// Convert vectors into `AsciiString`.
799 pub trait IntoAsciiString: Sized {
800 /// Convert to `AsciiString` without checking for non-ASCII characters.
801 ///
802 /// # Safety
803 /// If `self` contains non-ascii characters, calling this function is
804 /// undefined behavior.
805 unsafe fn into_ascii_string_unchecked(self) -> AsciiString;
806
807 /// Convert to `AsciiString`.
808 ///
809 /// # Errors
810 /// If `self` contains non-ascii characters, this will return `Err`
811 fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>>;
812 }
813
814 impl IntoAsciiString for Vec<AsciiChar> {
815 #[inline]
816 unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
817 AsciiString::from(self)
818 }
819 #[inline]
820 fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
821 Ok(AsciiString::from(self))
822 }
823 }
824
825 impl<'a> IntoAsciiString for &'a [AsciiChar] {
826 #[inline]
827 unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
828 AsciiString::from(self)
829 }
830 #[inline]
831 fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
832 Ok(AsciiString::from(self))
833 }
834 }
835
836 impl<'a> IntoAsciiString for &'a AsciiStr {
837 #[inline]
838 unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
839 AsciiString::from(self)
840 }
841 #[inline]
842 fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
843 Ok(AsciiString::from(self))
844 }
845 }
846
847 macro_rules! impl_into_ascii_string {
848 ('a, $wider:ty) => {
849 impl<'a> IntoAsciiString for $wider {
850 #[inline]
851 unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
852 // SAFETY: Caller guarantees `self` only has valid ascii bytes
853 unsafe { AsciiString::from_ascii_unchecked(self) }
854 }
855
856 #[inline]
857 fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
858 AsciiString::from_ascii(self)
859 }
860 }
861 };
862
863 ($wider:ty) => {
864 impl IntoAsciiString for $wider {
865 #[inline]
866 unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
867 // SAFETY: Caller guarantees `self` only has valid ascii bytes
868 unsafe { AsciiString::from_ascii_unchecked(self) }
869 }
870
871 #[inline]
872 fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
873 AsciiString::from_ascii(self)
874 }
875 }
876 };
877 }
878
879 impl_into_ascii_string! {AsciiString}
880 impl_into_ascii_string! {Vec<u8>}
881 impl_into_ascii_string! {'a, &'a [u8]}
882 impl_into_ascii_string! {String}
883 impl_into_ascii_string! {'a, &'a str}
884
885 /// # Notes
886 /// The trailing null byte `CString` has will be removed during this conversion.
887 #[cfg(feature = "std")]
888 impl IntoAsciiString for CString {
889 #[inline]
890 unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
891 // SAFETY: Caller guarantees `self` only has valid ascii bytes
892 unsafe { AsciiString::from_ascii_unchecked(self.into_bytes()) }
893 }
894
895 fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
896 AsciiString::from_ascii(self.into_bytes_with_nul())
897 .map_err(|FromAsciiError { error, owner }| {
898 FromAsciiError {
899 // SAFETY: We don't discard the NULL byte from the original
900 // string, so we ensure that it's null terminated
901 owner: unsafe { CString::from_vec_unchecked(owner) },
902 error,
903 }
904 })
905 .map(|mut s| {
906 let nul = s.pop();
907 debug_assert_eq!(nul, Some(AsciiChar::Null));
908 s
909 })
910 }
911 }
912
913 /// Note that the trailing null byte will be removed in the conversion.
914 #[cfg(feature = "std")]
915 impl<'a> IntoAsciiString for &'a CStr {
916 #[inline]
917 unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
918 // SAFETY: Caller guarantees `self` only has valid ascii bytes
919 unsafe { AsciiString::from_ascii_unchecked(self.to_bytes()) }
920 }
921
922 fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
923 AsciiString::from_ascii(self.to_bytes_with_nul())
924 .map_err(|FromAsciiError { error, owner }| FromAsciiError {
925 // SAFETY: We don't discard the NULL byte from the original
926 // string, so we ensure that it's null terminated
927 owner: unsafe { CStr::from_ptr(owner.as_ptr().cast()) },
928 error,
929 })
930 .map(|mut s| {
931 let nul = s.pop();
932 debug_assert_eq!(nul, Some(AsciiChar::Null));
933 s
934 })
935 }
936 }
937
938 impl<'a, B> IntoAsciiString for Cow<'a, B>
939 where
940 B: 'a + ToOwned + ?Sized,
941 &'a B: IntoAsciiString,
942 <B as ToOwned>::Owned: IntoAsciiString,
943 {
944 #[inline]
945 unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
946 // SAFETY: Caller guarantees `self` only has valid ascii bytes
947 unsafe { IntoAsciiString::into_ascii_string_unchecked(self.into_owned()) }
948 }
949
950 fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
951 match self {
952 Cow::Owned(b) => {
953 IntoAsciiString::into_ascii_string(b).map_err(|FromAsciiError { error, owner }| {
954 FromAsciiError {
955 owner: Cow::Owned(owner),
956 error,
957 }
958 })
959 }
960 Cow::Borrowed(b) => {
961 IntoAsciiString::into_ascii_string(b).map_err(|FromAsciiError { error, owner }| {
962 FromAsciiError {
963 owner: Cow::Borrowed(owner),
964 error,
965 }
966 })
967 }
968 }
969 }
970 }
971
972 #[cfg(test)]
973 mod tests {
974 use super::{AsciiString, IntoAsciiString};
975 use alloc::str::FromStr;
976 use alloc::string::{String, ToString};
977 use alloc::vec::Vec;
978 use alloc::boxed::Box;
979 #[cfg(feature = "std")]
980 use std::ffi::CString;
981 use {AsciiChar, AsciiStr};
982
983 #[test]
984 fn into_string() {
985 let v = AsciiString::from_ascii(&[40_u8, 32, 59][..]).unwrap();
986 assert_eq!(Into::<String>::into(v), "( ;".to_string());
987 }
988
989 #[test]
990 fn into_bytes() {
991 let v = AsciiString::from_ascii(&[40_u8, 32, 59][..]).unwrap();
992 assert_eq!(Into::<Vec<u8>>::into(v), vec![40_u8, 32, 59]);
993 }
994
995 #[test]
996 fn from_ascii_vec() {
997 let vec = vec![
998 AsciiChar::from_ascii('A').unwrap(),
999 AsciiChar::from_ascii('B').unwrap(),
1000 ];
1001 assert_eq!(AsciiString::from(vec), AsciiString::from_str("AB").unwrap());
1002 }
1003
1004 #[test]
1005 #[cfg(feature = "std")]
1006 fn from_cstring() {
1007 let cstring = CString::new("baz").unwrap();
1008 let ascii_str = cstring.clone().into_ascii_string().unwrap();
1009 let expected_chars = &[AsciiChar::b, AsciiChar::a, AsciiChar::z];
1010 assert_eq!(ascii_str.len(), 3);
1011 assert_eq!(ascii_str.as_slice(), expected_chars);
1012
1013 // SAFETY: "baz" only contains valid ascii characters.
1014 let ascii_str_unchecked = unsafe { cstring.into_ascii_string_unchecked() };
1015 assert_eq!(ascii_str_unchecked.len(), 3);
1016 assert_eq!(ascii_str_unchecked.as_slice(), expected_chars);
1017
1018 let sparkle_heart_bytes = vec![240_u8, 159, 146, 150];
1019 let cstring = CString::new(sparkle_heart_bytes).unwrap();
1020 let cstr = &*cstring;
1021 let ascii_err = cstr.into_ascii_string().unwrap_err();
1022 assert_eq!(ascii_err.into_source(), &*cstring);
1023 }
1024
1025 #[test]
1026 #[cfg(feature = "std")]
1027 fn fmt_ascii_string() {
1028 let s = "abc".to_string().into_ascii_string().unwrap();
1029 assert_eq!(format!("{}", s), "abc".to_string());
1030 assert_eq!(format!("{:?}", s), "\"abc\"".to_string());
1031 }
1032
1033 #[test]
1034 fn write_fmt() {
1035 use alloc::{fmt, str};
1036
1037 let mut s0 = AsciiString::new();
1038 fmt::write(&mut s0, format_args!("Hello World")).unwrap();
1039 assert_eq!(s0, "Hello World");
1040
1041 let mut s1 = AsciiString::new();
1042 fmt::write(&mut s1, format_args!("{}", 9)).unwrap();
1043 assert_eq!(s1, "9");
1044
1045 let mut s2 = AsciiString::new();
1046 let sparkle_heart_bytes = [240, 159, 146, 150];
1047 let sparkle_heart = str::from_utf8(&sparkle_heart_bytes).unwrap();
1048 assert!(fmt::write(&mut s2, format_args!("{}", sparkle_heart)).is_err());
1049 }
1050
1051 #[test]
1052 fn to_and_from_box() {
1053 let string = "abc".into_ascii_string().unwrap();
1054 let converted: Box<AsciiStr> = Box::from(string.clone());
1055 let converted: AsciiString = converted.into();
1056 assert_eq!(string, converted);
1057 }
1058 }