about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorSteven Fackler <sfackler@gmail.com>2013-08-05 01:25:15 -0400
committerSteven Fackler <sfackler@gmail.com>2013-08-06 09:58:36 -0700
commite6176513842da1dd9e17d8536e7d76125a1bc610 (patch)
treef35216eac5f258b099066d02a9252248bea79bf8 /src
parent858e166119d81e76b8909da880b3b3d0e25718c3 (diff)
Removed convenience encoding trait impls
Encoding should really only be done from [u8]<->str. The extra
convenience implementations don't really have a place, especially since
they're so trivial.

Also improved error messages in FromBase64.
Diffstat (limited to 'src')
-rw-r--r--src/libextra/base64.rs125
-rw-r--r--src/libextra/hex.rs92
2 files changed, 63 insertions, 154 deletions
diff --git a/src/libextra/base64.rs b/src/libextra/base64.rs
index d6ab36ca721..b4431004bd7 100644
--- a/src/libextra/base64.rs
+++ b/src/libextra/base64.rs
@@ -150,29 +150,6 @@ impl<'self> ToBase64 for &'self [u8] {
     }
 }
 
-impl<'self> ToBase64 for &'self str {
-    /**
-     * Convert any string (literal, `@`, `&`, or `~`) to base64 encoding.
-     *
-     *
-     * # Example
-     *
-     * ~~~ {.rust}
-     * extern mod extra;
-     * use extra::base64::{ToBase64, standard};
-     *
-     * fn main () {
-     *     let str = "Hello, World".to_base64(standard);
-     *     printfln!("%s", str);
-     * }
-     * ~~~
-     *
-     */
-    fn to_base64(&self, config: Config) -> ~str {
-        self.as_bytes().to_base64(config)
-    }
-}
-
 /// A trait for converting from base64 encoded values.
 pub trait FromBase64 {
     /// Converts the value of `self`, interpreted as base64 encoded data, into
@@ -180,22 +157,31 @@ pub trait FromBase64 {
     fn from_base64(&self) -> Result<~[u8], ~str>;
 }
 
-impl<'self> FromBase64 for &'self [u8] {
+impl<'self> FromBase64 for &'self str {
     /**
-     * Convert base64 `u8` vector into u8 byte values.
-     * Every 4 encoded characters is converted into 3 octets, modulo padding.
+     * Convert any base64 encoded string (literal, `@`, `&`, or `~`)
+     * to the byte values it encodes.
+     *
+     * You can use the `from_bytes` function in `std::str`
+     * to turn a `[u8]` into a string with characters corresponding to those
+     * values.
      *
      * # Example
      *
+     * This converts a string literal to base64 and back.
+     *
      * ~~~ {.rust}
      * extern mod extra;
      * use extra::base64::{ToBase64, FromBase64, standard};
+     * use std::str;
      *
      * fn main () {
-     *     let str = [52,32].to_base64(standard);
-     *     printfln!("%s", str);
-     *     let bytes = str.from_base64();
+     *     let hello_str = "Hello, World".to_base64(standard);
+     *     printfln!("%s", hello_str);
+     *     let bytes = hello_str.from_base64();
      *     printfln!("%?", bytes);
+     *     let result_str = str::from_bytes(bytes);
+     *     printfln!("%s", result_str);
      * }
      * ~~~
      */
@@ -204,12 +190,11 @@ impl<'self> FromBase64 for &'self [u8] {
         let mut buf: u32 = 0;
         let mut modulus = 0;
 
-        let mut it = self.iter();
-        for &byte in it {
-            let ch = byte as char;
+        let mut it = self.byte_iter().enumerate();
+        for (idx, byte) in it {
             let val = byte as u32;
 
-            match ch {
+            match byte as char {
                 'A'..'Z' => buf |= val - 0x41,
                 'a'..'z' => buf |= val - 0x47,
                 '0'..'9' => buf |= val + 0x04,
@@ -217,7 +202,8 @@ impl<'self> FromBase64 for &'self [u8] {
                 '/'|'_' => buf |= 0x3F,
                 '\r'|'\n' => loop,
                 '=' => break,
-                _ => return Err(~"Invalid Base64 character")
+                _ => return Err(fmt!("Invalid character '%c' at position %u",
+                                     self.char_at(idx), idx))
             }
 
             buf <<= 6;
@@ -230,8 +216,11 @@ impl<'self> FromBase64 for &'self [u8] {
             }
         }
 
-        if !it.all(|&byte| {byte as char == '='}) {
-            return Err(~"Invalid Base64 character");
+        for (idx, byte) in it {
+            if (byte as char) != '=' {
+                return Err(fmt!("Invalid character '%c' at position %u",
+                                self.char_at(idx), idx));
+            }
         }
 
         match modulus {
@@ -250,39 +239,6 @@ impl<'self> FromBase64 for &'self [u8] {
     }
 }
 
-impl<'self> FromBase64 for &'self str {
-    /**
-     * Convert any base64 encoded string (literal, `@`, `&`, or `~`)
-     * to the byte values it encodes.
-     *
-     * You can use the `from_bytes` function in `std::str`
-     * to turn a `[u8]` into a string with characters corresponding to those
-     * values.
-     *
-     * # Example
-     *
-     * This converts a string literal to base64 and back.
-     *
-     * ~~~ {.rust}
-     * extern mod extra;
-     * use extra::base64::{ToBase64, FromBase64, standard};
-     * use std::str;
-     *
-     * fn main () {
-     *     let hello_str = "Hello, World".to_base64(standard);
-     *     printfln!("%s", hello_str);
-     *     let bytes = hello_str.from_base64();
-     *     printfln!("%?", bytes);
-     *     let result_str = str::from_bytes(bytes);
-     *     printfln!("%s", result_str);
-     * }
-     * ~~~
-     */
-    fn from_base64(&self) -> Result<~[u8], ~str> {
-        self.as_bytes().from_base64()
-    }
-}
-
 #[cfg(test)]
 mod test {
     use test::BenchHarness;
@@ -290,27 +246,28 @@ mod test {
 
     #[test]
     fn test_to_base64_basic() {
-        assert_eq!("".to_base64(STANDARD), ~"");
-        assert_eq!("f".to_base64(STANDARD), ~"Zg==");
-        assert_eq!("fo".to_base64(STANDARD), ~"Zm8=");
-        assert_eq!("foo".to_base64(STANDARD), ~"Zm9v");
-        assert_eq!("foob".to_base64(STANDARD), ~"Zm9vYg==");
-        assert_eq!("fooba".to_base64(STANDARD), ~"Zm9vYmE=");
-        assert_eq!("foobar".to_base64(STANDARD), ~"Zm9vYmFy");
+        assert_eq!("".as_bytes().to_base64(STANDARD), ~"");
+        assert_eq!("f".as_bytes().to_base64(STANDARD), ~"Zg==");
+        assert_eq!("fo".as_bytes().to_base64(STANDARD), ~"Zm8=");
+        assert_eq!("foo".as_bytes().to_base64(STANDARD), ~"Zm9v");
+        assert_eq!("foob".as_bytes().to_base64(STANDARD), ~"Zm9vYg==");
+        assert_eq!("fooba".as_bytes().to_base64(STANDARD), ~"Zm9vYmE=");
+        assert_eq!("foobar".as_bytes().to_base64(STANDARD), ~"Zm9vYmFy");
     }
 
     #[test]
     fn test_to_base64_line_break() {
         assert!(![0u8, 1000].to_base64(Config {line_length: None, ..STANDARD})
                 .contains("\r\n"));
-        assert_eq!("foobar".to_base64(Config {line_length: Some(4), ..STANDARD}),
+        assert_eq!("foobar".as_bytes().to_base64(Config {line_length: Some(4),
+                                                         ..STANDARD}),
                    ~"Zm9v\r\nYmFy");
     }
 
     #[test]
     fn test_to_base64_padding() {
-        assert_eq!("f".to_base64(Config {pad: false, ..STANDARD}), ~"Zg");
-        assert_eq!("fo".to_base64(Config {pad: false, ..STANDARD}), ~"Zm8");
+        assert_eq!("f".as_bytes().to_base64(Config {pad: false, ..STANDARD}), ~"Zg");
+        assert_eq!("fo".as_bytes().to_base64(Config {pad: false, ..STANDARD}), ~"Zm8");
     }
 
     #[test]
@@ -344,7 +301,7 @@ mod test {
     #[test]
     fn test_from_base64_invalid_char() {
         assert!("Zm$=".from_base64().is_err())
-            assert!("Zg==$".from_base64().is_err());
+        assert!("Zg==$".from_base64().is_err());
     }
 
     #[test]
@@ -368,20 +325,20 @@ mod test {
     }
 
     #[bench]
-    pub fn to_base64(bh: & mut BenchHarness) {
+    pub fn bench_to_base64(bh: & mut BenchHarness) {
         let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
                  ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
         do bh.iter {
-            s.to_base64(STANDARD);
+            s.as_bytes().to_base64(STANDARD);
         }
         bh.bytes = s.len() as u64;
     }
 
     #[bench]
-    pub fn from_base64(bh: & mut BenchHarness) {
+    pub fn bench_from_base64(bh: & mut BenchHarness) {
         let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
                  ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
-        let b = s.to_base64(STANDARD);
+        let b = s.as_bytes().to_base64(STANDARD);
         do bh.iter {
             b.from_base64();
         }
diff --git a/src/libextra/hex.rs b/src/libextra/hex.rs
index ddd1276a987..2a6a8a52055 100644
--- a/src/libextra/hex.rs
+++ b/src/libextra/hex.rs
@@ -50,29 +50,6 @@ impl<'self> ToHex for &'self [u8] {
     }
 }
 
-impl<'self> ToHex for &'self str {
-    /**
-     * Convert any string (literal, `@`, `&`, or `~`) to hexadecimal encoding.
-     *
-     *
-     * # Example
-     *
-     * ~~~ {.rust}
-     * extern mod extra;
-     * use extra::ToHex;
-     *
-     * fn main () {
-     *     let str = "Hello, World".to_hex();
-     *     printfln!("%s", str);
-     * }
-     * ~~~
-     *
-     */
-    fn to_hex(&self) -> ~str {
-        self.as_bytes().to_hex()
-    }
-}
-
 /// A trait for converting hexadecimal encoded values
 pub trait FromHex {
     /// Converts the value of `self`, interpreted as hexadecimal encoded data,
@@ -80,23 +57,31 @@ pub trait FromHex {
     fn from_hex(&self) -> Result<~[u8], ~str>;
 }
 
-impl<'self> FromHex for &'self [u8] {
+impl<'self> FromHex for &'self str {
     /**
-     * Convert hexadecimal `u8` vector into u8 byte values.
-     * Every 2 encoded characters is converted into 1 octet.
-     * Whitespace is ignored.
+     * Convert any hexadecimal encoded string (literal, `@`, `&`, or `~`)
+     * to the byte values it encodes.
+     *
+     * You can use the `from_bytes` function in `std::str`
+     * to turn a `[u8]` into a string with characters corresponding to those
+     * values.
      *
      * # Example
      *
+     * This converts a string literal to hexadecimal and back.
+     *
      * ~~~ {.rust}
      * extern mod extra;
-     * use extra::hex::{ToHex, FromHex};
+     * use extra::hex::{FromHex, ToHex};
+     * use std::str;
      *
      * fn main () {
-     *     let str = [52,32].to_hex();
-     *     printfln!("%s", str);
-     *     let bytes = str.from_hex().get();
+     *     let hello_str = "Hello, World".to_hex();
+     *     printfln!("%s", hello_str);
+     *     let bytes = hello_str.from_hex().get();
      *     printfln!("%?", bytes);
+     *     let result_str = str::from_bytes(bytes);
+     *     printfln!("%s", result_str);
      * }
      * ~~~
      */
@@ -106,7 +91,7 @@ impl<'self> FromHex for &'self [u8] {
         let mut modulus = 0;
         let mut buf = 0u8;
 
-        for (idx, &byte) in self.iter().enumerate() {
+        for (idx, byte) in self.byte_iter().enumerate() {
             buf <<= 4;
 
             match byte as char {
@@ -117,8 +102,8 @@ impl<'self> FromHex for &'self [u8] {
                     buf >>= 4;
                     loop
                 }
-                _ => return Err(fmt!("Invalid byte '%c' found at position %u",
-                                     byte as char, idx))
+                _ => return Err(fmt!("Invalid character '%c' at position %u",
+                                     self.char_at(idx), idx))
             }
 
             modulus += 1;
@@ -135,39 +120,6 @@ impl<'self> FromHex for &'self [u8] {
     }
 }
 
-impl<'self> FromHex for &'self str {
-    /**
-     * Convert any hexadecimal encoded string (literal, `@`, `&`, or `~`)
-     * to the byte values it encodes.
-     *
-     * You can use the `from_bytes` function in `std::str`
-     * to turn a `[u8]` into a string with characters corresponding to those
-     * values.
-     *
-     * # Example
-     *
-     * This converts a string literal to hexadecimal and back.
-     *
-     * ~~~ {.rust}
-     * extern mod extra;
-     * use extra::hex::{FromHex, ToHex};
-     * use std::str;
-     *
-     * fn main () {
-     *     let hello_str = "Hello, World".to_hex();
-     *     printfln!("%s", hello_str);
-     *     let bytes = hello_str.from_hex().get();
-     *     printfln!("%?", bytes);
-     *     let result_str = str::from_bytes(bytes);
-     *     printfln!("%s", result_str);
-     * }
-     * ~~~
-     */
-    fn from_hex(&self) -> Result<~[u8], ~str> {
-        self.as_bytes().from_hex()
-    }
-}
-
 #[cfg(test)]
 mod tests {
     use test::BenchHarness;
@@ -175,7 +127,7 @@ mod tests {
 
     #[test]
     pub fn test_to_hex() {
-        assert_eq!("foobar".to_hex(), ~"666f6f626172");
+        assert_eq!("foobar".as_bytes().to_hex(), ~"666f6f626172");
     }
 
     #[test]
@@ -223,7 +175,7 @@ mod tests {
         let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
                  ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
         do bh.iter {
-            s.to_hex();
+            s.as_bytes().to_hex();
         }
         bh.bytes = s.len() as u64;
     }
@@ -232,7 +184,7 @@ mod tests {
     pub fn bench_from_hex(bh: & mut BenchHarness) {
         let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
                  ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
-        let b = s.to_hex();
+        let b = s.as_bytes().to_hex();
         do bh.iter {
             b.from_hex();
         }