Skip to content

Commit c44042a

Browse files
committed
Improve IntoAsciiStrError
1 parent ea0613f commit c44042a

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

src/ascii_str.rs

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -365,7 +365,34 @@ pub struct IntoAsciiStrError {
365365
/// If less than 128, it was a byte >= 128
366366
not_ascii: char,
367367
}
368-
368+
impl IntoAsciiStrError {
369+
/// The index of the first non-ASCII byte or character.
370+
pub fn index(self) -> usize {
371+
self.index
372+
}
373+
/// Get the byte that caused the error.
374+
///
375+
/// If a str was being converted, the first byte in the utf8 encoding is returned.
376+
pub fn byte(self) -> u8 {
377+
if (self.not_ascii as u32) < 128 {
378+
self.not_ascii as u8 + 128
379+
} else {
380+
// char::encode_utf8() is unstable
381+
let mut s = String::with_capacity(4);
382+
s.push(self.not_ascii);
383+
s.bytes().next().unwrap()
384+
}
385+
}
386+
/// Get the char that caused conversions from a `str` to fail.
387+
///
388+
/// Returns `None` if the error was caused by a byte in a `[u8]`
389+
pub fn char(self) -> Option<char> {
390+
match self.not_ascii as u32 {
391+
0...127 => None, // byte in [u8]
392+
_ => Some(self.not_ascii),
393+
}
394+
}
395+
}
369396
impl fmt::Debug for IntoAsciiStrError {
370397
fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
371398
if (self.not_ascii as u32) < 128 {
@@ -386,7 +413,11 @@ impl fmt::Display for IntoAsciiStrError {
386413
}
387414
impl Error for IntoAsciiStrError {
388415
fn description(&self) -> &'static str {
389-
"one or more bytes (or chars if str) are not ASCII"
416+
if (self.not_ascii as u32) < 128 {
417+
"one or more bytes are not ASCII"
418+
} else {
419+
"one or more characters are not ASCII"
420+
}
390421
}
391422
}
392423

0 commit comments

Comments
 (0)