Use from instead of into in unescaping code.

The `T` type in these functions took me some time to understand, and I
find the explicit `T` in the use of `from` makes the code easier to
read, as does the `u8` annotation in `scan_escape`.
This commit is contained in:
Nicholas Nethercote 2024-01-23 10:37:27 +11:00
parent 4b4bdb575b
commit ef1e2228cf

View File

@ -222,7 +222,7 @@ fn scan_escape<T: From<u8> + From<char>>(
mode: Mode, mode: Mode,
) -> Result<T, EscapeError> { ) -> Result<T, EscapeError> {
// Previous character was '\\', unescape what follows. // Previous character was '\\', unescape what follows.
let res = match chars.next().ok_or(EscapeError::LoneSlash)? { let res: u8 = match chars.next().ok_or(EscapeError::LoneSlash)? {
'"' => b'"', '"' => b'"',
'n' => b'\n', 'n' => b'\n',
'r' => b'\r', 'r' => b'\r',
@ -249,10 +249,10 @@ fn scan_escape<T: From<u8> + From<char>>(
value as u8 value as u8
} }
'u' => return scan_unicode(chars, mode.is_unicode_escape_disallowed()).map(Into::into), 'u' => return scan_unicode(chars, mode.is_unicode_escape_disallowed()).map(T::from),
_ => return Err(EscapeError::InvalidEscape), _ => return Err(EscapeError::InvalidEscape),
}; };
Ok(res.into()) Ok(T::from(res))
} }
fn scan_unicode( fn scan_unicode(
@ -366,7 +366,7 @@ fn unescape_non_raw_common<F, T: From<u8> + From<char>>(src: &str, mode: Mode, c
} }
'"' => Err(EscapeError::EscapeOnlyChar), '"' => Err(EscapeError::EscapeOnlyChar),
'\r' => Err(EscapeError::BareCarriageReturn), '\r' => Err(EscapeError::BareCarriageReturn),
_ => ascii_check(c, chars_should_be_ascii).map(Into::into), _ => ascii_check(c, chars_should_be_ascii).map(T::from),
}; };
let end = src.len() - chars.as_str().len(); let end = src.len() - chars.as_str().len();
callback(start..end, res); callback(start..end, res);