Skip to content

Commit

Permalink
Add escape_default method to u8 and [u8]
Browse files Browse the repository at this point in the history
  • Loading branch information
clarfonthey committed Jan 17, 2021
1 parent 2e46cb3 commit 35ea315
Show file tree
Hide file tree
Showing 3 changed files with 124 additions and 0 deletions.
26 changes: 26 additions & 0 deletions library/core/src/num/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#![stable(feature = "rust1", since = "1.0.0")]

use crate::ascii;
use crate::intrinsics;
use crate::mem;
use crate::str::FromStr;
Expand Down Expand Up @@ -649,6 +650,31 @@ impl u8 {
pub const fn is_ascii_control(&self) -> bool {
matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
}

/// Returns an iterator that produces an escaped version of a `u8`,
/// treating it as an ASCII character.
///
/// The behavior is identical to [`ascii::escape_default`].
///
/// # Examples
///
/// ```
/// # #![feature(inherent_ascii_escape)]
///
/// assert_eq!("0", b'0'.escape_ascii().to_string());
/// assert_eq!("\\t", b'\t'.escape_ascii().to_string());
/// assert_eq!("\\r", b'\r'.escape_ascii().to_string());
/// assert_eq!("\\n", b'\n'.escape_ascii().to_string());
/// assert_eq!("\\'", b'\''.escape_ascii().to_string());
/// assert_eq!("\\\"", b'"'.escape_ascii().to_string());
/// assert_eq!("\\\\", b'\\'.escape_ascii().to_string());
/// assert_eq!("\\x9d", b'\x9d'.escape_ascii().to_string());
/// ```
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
#[inline]
pub fn escape_ascii(&self) -> ascii::EscapeDefault {
ascii::escape_default(*self)
}
}

#[lang = "u16"]
Expand Down
95 changes: 95 additions & 0 deletions library/core/src/slice/ascii.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
//! Operations on ASCII `[u8]`.

use crate::ascii;
use crate::fmt::{self, Write};
use crate::iter;
use crate::mem;
use crate::ops;

#[lang = "slice_u8"]
#[cfg(not(test))]
Expand Down Expand Up @@ -55,6 +59,97 @@ impl [u8] {
byte.make_ascii_lowercase();
}
}

/// Returns an iterator that produces an escaped version of this slice,
/// treating it as an ASCII string.
///
/// # Examples
///
/// ```
/// #![feature(inherent_ascii_escape)]
///
/// let s = b"0\t\r\n'\"\\\x9d";
/// let escaped = s.escape_ascii().to_string();
/// assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
/// ```
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
pub fn escape_ascii(&self) -> EscapeAscii<'_> {
EscapeAscii { inner: self.iter().flat_map(EscapeByte) }
}
}

impl_fn_for_zst! {
#[derive(Clone)]
struct EscapeByte impl Fn = |byte: &u8| -> ascii::EscapeDefault {
ascii::escape_default(*byte)
};
}

/// An iterator over the escaped version of a byte slice.
///
/// This `struct` is created by the [`[u8]::escape_ascii`] method. See its
/// documentation for more.
///
/// [`[u8]::escape_ascii`]: ../../std/primitive.slice.html#method.escape_ascii
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
#[derive(Clone)]
pub struct EscapeAscii<'a> {
inner: iter::FlatMap<super::Iter<'a, u8>, ascii::EscapeDefault, EscapeByte>,
}

#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::Iterator for EscapeAscii<'a> {
type Item = u8;
#[inline]
fn next(&mut self) -> Option<u8> {
self.inner.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
#[inline]
fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
where
Fold: FnMut(Acc, Self::Item) -> R,
R: ops::Try<Ok = Acc>,
{
self.inner.try_fold(init, fold)
}
#[inline]
fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
self.inner.fold(init, fold)
}
#[inline]
fn last(mut self) -> Option<u8> {
self.next_back()
}
}

#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::DoubleEndedIterator for EscapeAscii<'a> {
fn next_back(&mut self) -> Option<u8> {
self.inner.next_back()
}
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::ExactSizeIterator for EscapeAscii<'a> {}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::FusedIterator for EscapeAscii<'a> {}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> fmt::Display for EscapeAscii<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.clone().try_for_each(|b| f.write_char(b as char))
}
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> fmt::Debug for EscapeAscii<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("EscapeAscii { .. }")
}
}

/// Returns `true` if any byte in the word `v` is nonascii (>= 128). Snarfed
Expand Down
3 changes: 3 additions & 0 deletions library/core/src/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ pub use sort::heapsort;
#[stable(feature = "slice_get_slice", since = "1.28.0")]
pub use index::SliceIndex;

#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
pub use ascii::EscapeAscii;

#[lang = "slice"]
#[cfg(not(test))]
impl<T> [T] {
Expand Down

0 comments on commit 35ea315

Please sign in to comment.