@@ -154,7 +154,25 @@ impl<'a> ToBase64 for &'a [u8] {
154154pub trait FromBase64 {
155155 /// Converts the value of `self`, interpreted as base64 encoded data, into
156156 /// an owned vector of bytes, returning the vector.
157- fn from_base64 ( & self ) -> Result < ~[ u8 ] , ~str > ;
157+ fn from_base64 ( & self ) -> Result < ~[ u8 ] , FromBase64Error > ;
158+ }
159+
160+ /// Errors that can occur when decoding a base64 encoded string
161+ pub enum FromBase64Error {
162+ /// The input contained a character not part of the base64 format
163+ InvalidBase64Character ( char , uint ) ,
164+ /// The input had an invalid length
165+ InvalidBase64Length ,
166+ }
167+
168+ impl ToStr for FromBase64Error {
169+ fn to_str ( & self ) -> ~str {
170+ match * self {
171+ InvalidBase64Character ( ch, idx) =>
172+ format ! ( "Invalid character '{}' at position {}" , ch, idx) ,
173+ InvalidBase64Length => ~"Invalid length",
174+ }
175+ }
158176}
159177
160178impl < ' a > FromBase64 for & ' a str {
@@ -188,7 +206,7 @@ impl<'a> FromBase64 for &'a str {
188206 * }
189207 * ```
190208 */
191- fn from_base64 ( & self ) -> Result < ~[ u8 ] , ~ str > {
209+ fn from_base64 ( & self ) -> Result < ~[ u8 ] , FromBase64Error > {
192210 let mut r = ~[ ] ;
193211 let mut buf: u32 = 0 ;
194212 let mut modulus = 0 ;
@@ -205,8 +223,7 @@ impl<'a> FromBase64 for &'a str {
205223 '/' |'_' => buf |= 0x3F ,
206224 '\r' |'\n' => continue ,
207225 '=' => break ,
208- _ => return Err ( format ! ( "Invalid character '{}' at position {}" ,
209- self . char_at( idx) , idx) )
226+ _ => return Err ( InvalidBase64Character ( self . char_at ( idx) , idx) ) ,
210227 }
211228
212229 buf <<= 6 ;
@@ -221,8 +238,7 @@ impl<'a> FromBase64 for &'a str {
221238
222239 for ( idx, byte) in it {
223240 if ( byte as char ) != '=' {
224- return Err ( format ! ( "Invalid character '{}' at position {}" ,
225- self . char_at( idx) , idx) ) ;
241+ return Err ( InvalidBase64Character ( self . char_at ( idx) , idx) ) ;
226242 }
227243 }
228244
@@ -235,7 +251,7 @@ impl<'a> FromBase64 for &'a str {
235251 r. push ( ( buf >> 8 ) as u8 ) ;
236252 }
237253 0 => ( ) ,
238- _ => return Err ( ~" Invalid Base64 length" )
254+ _ => return Err ( InvalidBase64Length ) ,
239255 }
240256
241257 Ok ( r)
0 commit comments