]> git.proxmox.com Git - rustc.git/blobdiff - src/libstd/ascii.rs
Imported Upstream version 1.2.0+dfsg1
[rustc.git] / src / libstd / ascii.rs
index 77c2315194bb4e26aeb8fc78f208317992c5e757..9b94b7f7003ed62f521e37eae944b7848cf61f66 100644 (file)
 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
-//
-// ignore-lexer-test FIXME #15679
 
 //! Operations on ASCII strings and characters
 
-#![unstable = "unsure about placement and naming"]
+#![stable(feature = "rust1", since = "1.0.0")]
+
+use prelude::v1::*;
 
-use iter::IteratorExt;
-use ops::FnMut;
-use slice::SliceExt;
-use str::StrExt;
-use string::String;
-use vec::Vec;
+use ops::Range;
+use mem;
 
 /// Extension methods for ASCII-subset only operations on owned strings
-#[unstable = "would prefer to do this in a more general way"]
+#[unstable(feature = "owned_ascii_ext",
+           reason = "would prefer to do this in a more general way")]
 pub trait OwnedAsciiExt {
-    /// Convert the string to ASCII upper case:
+    /// Converts the string to ASCII upper case:
     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
     /// but non-ASCII letters are unchanged.
     fn into_ascii_uppercase(self) -> Self;
 
-    /// Convert the string to ASCII lower case:
+    /// Converts the string to ASCII lower case:
     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
     /// but non-ASCII letters are unchanged.
     fn into_ascii_lowercase(self) -> Self;
 }
 
-/// Extension methods for ASCII-subset only operations on string slices
-#[unstable = "would prefer to do this in a more general way"]
-pub trait AsciiExt<T = Self> {
-    /// Check if within the ASCII range.
+/// Extension methods for ASCII-subset only operations on string slices.
+#[stable(feature = "rust1", since = "1.0.0")]
+pub trait AsciiExt {
+    /// Container type for copied ASCII characters.
+    #[stable(feature = "rust1", since = "1.0.0")]
+    type Owned;
+
+    /// Checks if within the ASCII range.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::ascii::AsciiExt;
+    ///
+    /// let ascii = 'a';
+    /// let utf8 = '❤';
+    ///
+    /// assert_eq!(true, ascii.is_ascii());
+    /// assert_eq!(false, utf8.is_ascii())
+    /// ```
+    #[stable(feature = "rust1", since = "1.0.0")]
     fn is_ascii(&self) -> bool;
 
-    /// Makes a copy of the string in ASCII upper case:
+    /// Makes a copy of the string in ASCII upper case.
+    ///
     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
     /// but non-ASCII letters are unchanged.
-    fn to_ascii_uppercase(&self) -> T;
-
-    /// Makes a copy of the string in ASCII lower case:
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::ascii::AsciiExt;
+    ///
+    /// let ascii = 'a';
+    /// let utf8 = '❤';
+    ///
+    /// assert_eq!('A', ascii.to_ascii_uppercase());
+    /// assert_eq!('❤', utf8.to_ascii_uppercase());
+    /// ```
+    #[stable(feature = "rust1", since = "1.0.0")]
+    fn to_ascii_uppercase(&self) -> Self::Owned;
+
+    /// Makes a copy of the string in ASCII lower case.
+    ///
     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
     /// but non-ASCII letters are unchanged.
-    fn to_ascii_lowercase(&self) -> T;
-
-    /// Check that two strings are an ASCII case-insensitive match.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::ascii::AsciiExt;
+    ///
+    /// let ascii = 'A';
+    /// let utf8 = '❤';
+    ///
+    /// assert_eq!('a', ascii.to_ascii_lowercase());
+    /// assert_eq!('❤', utf8.to_ascii_lowercase());
+    /// ```
+    #[stable(feature = "rust1", since = "1.0.0")]
+    fn to_ascii_lowercase(&self) -> Self::Owned;
+
+    /// Checks that two strings are an ASCII case-insensitive match.
+    ///
     /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
     /// but without allocating and copying temporary strings.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::ascii::AsciiExt;
+    ///
+    /// let ascii1 = 'A';
+    /// let ascii2 = 'a';
+    /// let ascii3 = 'A';
+    /// let ascii4 = 'z';
+    ///
+    /// assert_eq!(true, ascii1.eq_ignore_ascii_case(&ascii2));
+    /// assert_eq!(true, ascii1.eq_ignore_ascii_case(&ascii3));
+    /// assert_eq!(false, ascii1.eq_ignore_ascii_case(&ascii4));
+    /// ```
+    #[stable(feature = "rust1", since = "1.0.0")]
     fn eq_ignore_ascii_case(&self, other: &Self) -> bool;
+
+    /// Converts this type to its ASCII upper case equivalent in-place.
+    ///
+    /// See `to_ascii_uppercase` for more information.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # #![feature(ascii)]
+    /// use std::ascii::AsciiExt;
+    ///
+    /// let mut ascii = 'a';
+    ///
+    /// ascii.make_ascii_uppercase();
+    ///
+    /// assert_eq!('A', ascii);
+    /// ```
+    #[unstable(feature = "ascii")]
+    fn make_ascii_uppercase(&mut self);
+
+    /// Converts this type to its ASCII lower case equivalent in-place.
+    ///
+    /// See `to_ascii_lowercase` for more information.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # #![feature(ascii)]
+    /// use std::ascii::AsciiExt;
+    ///
+    /// let mut ascii = 'A';
+    ///
+    /// ascii.make_ascii_lowercase();
+    ///
+    /// assert_eq!('a', ascii);
+    /// ```
+    #[unstable(feature = "ascii")]
+    fn make_ascii_lowercase(&mut self);
 }
 
-#[unstable = "would prefer to do this in a more general way"]
-impl AsciiExt<String> for str {
+#[stable(feature = "rust1", since = "1.0.0")]
+impl AsciiExt for str {
+    type Owned = String;
+
     #[inline]
     fn is_ascii(&self) -> bool {
         self.bytes().all(|b| b.is_ascii())
@@ -66,23 +165,30 @@ impl AsciiExt<String> for str {
 
     #[inline]
     fn to_ascii_uppercase(&self) -> String {
-        // Vec<u8>::to_ascii_uppercase() preserves the UTF-8 invariant.
-        unsafe { String::from_utf8_unchecked(self.as_bytes().to_ascii_uppercase()) }
+        self.to_string().into_ascii_uppercase()
     }
 
     #[inline]
     fn to_ascii_lowercase(&self) -> String {
-        // Vec<u8>::to_ascii_lowercase() preserves the UTF-8 invariant.
-        unsafe { String::from_utf8_unchecked(self.as_bytes().to_ascii_lowercase()) }
+        self.to_string().into_ascii_lowercase()
     }
 
     #[inline]
     fn eq_ignore_ascii_case(&self, other: &str) -> bool {
         self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
     }
+
+    fn make_ascii_uppercase(&mut self) {
+        let me: &mut [u8] = unsafe { mem::transmute(self) };
+        me.make_ascii_uppercase()
+    }
+
+    fn make_ascii_lowercase(&mut self) {
+        let me: &mut [u8] = unsafe { mem::transmute(self) };
+        me.make_ascii_lowercase()
+    }
 }
 
-#[unstable = "would prefer to do this in a more general way"]
 impl OwnedAsciiExt for String {
     #[inline]
     fn into_ascii_uppercase(self) -> String {
@@ -97,8 +203,9 @@ impl OwnedAsciiExt for String {
     }
 }
 
-#[unstable = "would prefer to do this in a more general way"]
-impl AsciiExt<Vec<u8>> for [u8] {
+#[stable(feature = "rust1", since = "1.0.0")]
+impl AsciiExt for [u8] {
+    type Owned = Vec<u8>;
     #[inline]
     fn is_ascii(&self) -> bool {
         self.iter().all(|b| b.is_ascii())
@@ -106,67 +213,71 @@ impl AsciiExt<Vec<u8>> for [u8] {
 
     #[inline]
     fn to_ascii_uppercase(&self) -> Vec<u8> {
-        self.iter().map(|b| b.to_ascii_uppercase()).collect()
+        self.to_vec().into_ascii_uppercase()
     }
 
     #[inline]
     fn to_ascii_lowercase(&self) -> Vec<u8> {
-        self.iter().map(|b| b.to_ascii_lowercase()).collect()
+        self.to_vec().into_ascii_lowercase()
     }
 
     #[inline]
     fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
         self.len() == other.len() &&
-        self.iter().zip(other.iter()).all(|(a, b)| {
+        self.iter().zip(other).all(|(a, b)| {
             a.eq_ignore_ascii_case(b)
         })
     }
+
+    fn make_ascii_uppercase(&mut self) {
+        for byte in self {
+            byte.make_ascii_uppercase();
+        }
+    }
+
+    fn make_ascii_lowercase(&mut self) {
+        for byte in self {
+            byte.make_ascii_lowercase();
+        }
+    }
 }
 
-#[unstable = "would prefer to do this in a more general way"]
 impl OwnedAsciiExt for Vec<u8> {
     #[inline]
     fn into_ascii_uppercase(mut self) -> Vec<u8> {
-        for byte in self.iter_mut() {
-            *byte = byte.to_ascii_uppercase();
-        }
+        self.make_ascii_uppercase();
         self
     }
 
     #[inline]
     fn into_ascii_lowercase(mut self) -> Vec<u8> {
-        for byte in self.iter_mut() {
-            *byte = byte.to_ascii_lowercase();
-        }
+        self.make_ascii_lowercase();
         self
     }
 }
 
-#[unstable = "would prefer to do this in a more general way"]
+#[stable(feature = "rust1", since = "1.0.0")]
 impl AsciiExt for u8 {
+    type Owned = u8;
     #[inline]
-    fn is_ascii(&self) -> bool {
-        *self & 128 == 0u8
-    }
-
+    fn is_ascii(&self) -> bool { *self & 128 == 0 }
     #[inline]
-    fn to_ascii_uppercase(&self) -> u8 {
-        ASCII_UPPERCASE_MAP[*self as uint]
-    }
-
+    fn to_ascii_uppercase(&self) -> u8 { ASCII_UPPERCASE_MAP[*self as usize] }
     #[inline]
-    fn to_ascii_lowercase(&self) -> u8 {
-        ASCII_LOWERCASE_MAP[*self as uint]
-    }
-
+    fn to_ascii_lowercase(&self) -> u8 { ASCII_LOWERCASE_MAP[*self as usize] }
     #[inline]
     fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
         self.to_ascii_lowercase() == other.to_ascii_lowercase()
     }
+    #[inline]
+    fn make_ascii_uppercase(&mut self) { *self = self.to_ascii_uppercase(); }
+    #[inline]
+    fn make_ascii_lowercase(&mut self) { *self = self.to_ascii_lowercase(); }
 }
 
-#[unstable = "would prefer to do this in a more general way"]
+#[stable(feature = "rust1", since = "1.0.0")]
 impl AsciiExt for char {
+    type Owned = char;
     #[inline]
     fn is_ascii(&self) -> bool {
         *self as u32 <= 0x7F
@@ -194,9 +305,22 @@ impl AsciiExt for char {
     fn eq_ignore_ascii_case(&self, other: &char) -> bool {
         self.to_ascii_lowercase() == other.to_ascii_lowercase()
     }
+
+    #[inline]
+    fn make_ascii_uppercase(&mut self) { *self = self.to_ascii_uppercase(); }
+    #[inline]
+    fn make_ascii_lowercase(&mut self) { *self = self.to_ascii_lowercase(); }
 }
 
-/// Returns a 'default' ASCII and C++11-like literal escape of a `u8`
+/// An iterator over the escaped version of a byte, constructed via
+/// `std::ascii::escape_default`.
+#[stable(feature = "rust1", since = "1.0.0")]
+pub struct EscapeDefault {
+    range: Range<usize>,
+    data: [u8; 4],
+}
+
+/// Returns an iterator that produces an escaped version of a `u8`.
 ///
 /// The default is chosen with a bias toward producing literals that are
 /// legal in a variety of languages, including C++11 and similar C-family
@@ -205,33 +329,60 @@ impl AsciiExt for char {
 /// - Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
 /// - Single-quote, double-quote and backslash chars are backslash-escaped.
 /// - Any other chars in the range [0x20,0x7e] are not escaped.
-/// - Any other chars are given hex escapes.
+/// - Any other chars are given hex escapes of the form '\xNN'.
 /// - Unicode escapes are never generated by this function.
-#[unstable = "needs to be updated to use an iterator"]
-pub fn escape_default<F>(c: u8, mut f: F) where
-    F: FnMut(u8),
-{
-    match c {
-        b'\t' => { f(b'\\'); f(b't'); }
-        b'\r' => { f(b'\\'); f(b'r'); }
-        b'\n' => { f(b'\\'); f(b'n'); }
-        b'\\' => { f(b'\\'); f(b'\\'); }
-        b'\'' => { f(b'\\'); f(b'\''); }
-        b'"'  => { f(b'\\'); f(b'"'); }
-        b'\x20' ... b'\x7e' => { f(c); }
-        _ => {
-            f(b'\\');
-            f(b'x');
-            for &offset in [4u, 0u].iter() {
-                match ((c as i32) >> offset) & 0xf {
-                    i @ 0 ... 9 => f(b'0' + (i as u8)),
-                    i => f(b'a' + (i as u8 - 10)),
-                }
-            }
+///
+/// # Examples
+///
+/// ```
+/// use std::ascii;
+///
+/// let escaped = ascii::escape_default(b'0').next().unwrap();
+/// assert_eq!(b'0', escaped);
+///
+/// let mut escaped = ascii::escape_default(b'\t');
+///
+/// assert_eq!(b'\\', escaped.next().unwrap());
+/// assert_eq!(b't', escaped.next().unwrap());
+/// ```
+#[stable(feature = "rust1", since = "1.0.0")]
+pub fn escape_default(c: u8) -> EscapeDefault {
+    let (data, len) = match c {
+        b'\t' => ([b'\\', b't', 0, 0], 2),
+        b'\r' => ([b'\\', b'r', 0, 0], 2),
+        b'\n' => ([b'\\', b'n', 0, 0], 2),
+        b'\\' => ([b'\\', b'\\', 0, 0], 2),
+        b'\'' => ([b'\\', b'\'', 0, 0], 2),
+        b'"' => ([b'\\', b'"', 0, 0], 2),
+        b'\x20' ... b'\x7e' => ([c, 0, 0, 0], 1),
+        _ => ([b'\\', b'x', hexify(c >> 4), hexify(c & 0xf)], 4),
+    };
+
+    return EscapeDefault { range: (0.. len), data: data };
+
+    fn hexify(b: u8) -> u8 {
+        match b {
+            0 ... 9 => b'0' + b,
+            _ => b'a' + b - 10,
         }
     }
 }
 
+#[stable(feature = "rust1", since = "1.0.0")]
+impl Iterator for EscapeDefault {
+    type Item = u8;
+    fn next(&mut self) -> Option<u8> { self.range.next().map(|i| self.data[i]) }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.range.size_hint() }
+}
+#[stable(feature = "rust1", since = "1.0.0")]
+impl DoubleEndedIterator for EscapeDefault {
+    fn next_back(&mut self) -> Option<u8> {
+        self.range.next_back().map(|i| self.data[i])
+    }
+}
+#[stable(feature = "rust1", since = "1.0.0")]
+impl ExactSizeIterator for EscapeDefault {}
+
 static ASCII_LOWERCASE_MAP: [u8; 256] = [
     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
     0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
@@ -328,7 +479,6 @@ mod tests {
         assert!("".is_ascii());
         assert!("a".is_ascii());
         assert!(!"\u{2009}".is_ascii());
-
     }
 
     #[test]
@@ -336,13 +486,11 @@ mod tests {
         assert_eq!("url()URL()uRl()ürl".to_ascii_uppercase(), "URL()URL()URL()üRL");
         assert_eq!("hıKß".to_ascii_uppercase(), "HıKß");
 
-        let mut i = 0;
-        while i <= 500 {
+        for i in 0..501 {
             let upper = if 'a' as u32 <= i && i <= 'z' as u32 { i + 'A' as u32 - 'a' as u32 }
                         else { i };
             assert_eq!((from_u32(i).unwrap()).to_string().to_ascii_uppercase(),
                        (from_u32(upper).unwrap()).to_string());
-            i += 1;
         }
     }
 
@@ -352,13 +500,11 @@ mod tests {
         // Dotted capital I, Kelvin sign, Sharp S.
         assert_eq!("HİKß".to_ascii_lowercase(), "hİKß");
 
-        let mut i = 0;
-        while i <= 500 {
+        for i in 0..501 {
             let lower = if 'A' as u32 <= i && i <= 'Z' as u32 { i + 'a' as u32 - 'A' as u32 }
                         else { i };
             assert_eq!((from_u32(i).unwrap()).to_string().to_ascii_lowercase(),
                        (from_u32(lower).unwrap()).to_string());
-            i += 1;
         }
     }
 
@@ -368,13 +514,11 @@ mod tests {
                    "URL()URL()URL()üRL".to_string());
         assert_eq!(("hıKß".to_string()).into_ascii_uppercase(), "HıKß");
 
-        let mut i = 0;
-        while i <= 500 {
+        for i in 0..501 {
             let upper = if 'a' as u32 <= i && i <= 'z' as u32 { i + 'A' as u32 - 'a' as u32 }
                         else { i };
             assert_eq!((from_u32(i).unwrap()).to_string().into_ascii_uppercase(),
                        (from_u32(upper).unwrap()).to_string());
-            i += 1;
         }
     }
 
@@ -385,13 +529,11 @@ mod tests {
         // Dotted capital I, Kelvin sign, Sharp S.
         assert_eq!(("HİKß".to_string()).into_ascii_lowercase(), "hİKß");
 
-        let mut i = 0;
-        while i <= 500 {
+        for i in 0..501 {
             let lower = if 'A' as u32 <= i && i <= 'Z' as u32 { i + 'a' as u32 - 'A' as u32 }
                         else { i };
             assert_eq!((from_u32(i).unwrap()).to_string().into_ascii_lowercase(),
                        (from_u32(lower).unwrap()).to_string());
-            i += 1;
         }
     }
 
@@ -405,14 +547,11 @@ mod tests {
         assert!(!"K".eq_ignore_ascii_case("k"));
         assert!(!"ß".eq_ignore_ascii_case("s"));
 
-        let mut i = 0;
-        while i <= 500 {
-            let c = i;
-            let lower = if 'A' as u32 <= c && c <= 'Z' as u32 { c + 'a' as u32 - 'A' as u32 }
-                        else { c };
+        for i in 0..501 {
+            let lower = if 'A' as u32 <= i && i <= 'Z' as u32 { i + 'a' as u32 - 'A' as u32 }
+                        else { i };
             assert!((from_u32(i).unwrap()).to_string().eq_ignore_ascii_case(
-                    (from_u32(lower).unwrap()).to_string().as_slice()));
-            i += 1;
+                    &from_u32(lower).unwrap().to_string()));
         }
     }
 }