Skip to content

Commit

Permalink
Implement ToAsciiChar for i8, u16 and u32
Browse files Browse the repository at this point in the history
i8 is what c_char corresponds to on x86.
Together with the impl for u8 this means ToAsciiChar is always
implemented for c_char (on any relevant architecture).
  • Loading branch information
tormol authored and Thomas Bahn committed Aug 21, 2019
1 parent 1d6793b commit 828f954
Showing 1 changed file with 36 additions and 10 deletions.
46 changes: 36 additions & 10 deletions src/ascii_char.rs
Original file line number Diff line number Diff line change
Expand Up @@ -675,12 +675,18 @@ impl ToAsciiChar for AsciiChar {
impl ToAsciiChar for u8 {
#[inline]
fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
unsafe {
if self <= 0x7F {
return Ok(self.to_ascii_char_unchecked());
}
}
Err(ToAsciiCharError(()))
(self as u32).to_ascii_char()
}
#[inline]
unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
mem::transmute(self)
}
}

impl ToAsciiChar for i8 {
#[inline]
fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
(self as u32).to_ascii_char()
}
#[inline]
unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
Expand All @@ -690,13 +696,33 @@ impl ToAsciiChar for u8 {

impl ToAsciiChar for char {
#[inline]
fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
(self as u32).to_ascii_char()
}
#[inline]
unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
(self as u32).to_ascii_char_unchecked()
}
}

impl ToAsciiChar for u32 {
fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
unsafe {
if self as u32 <= 0x7F {
return Ok(self.to_ascii_char_unchecked());
match self {
0..=127 => Ok(self.to_ascii_char_unchecked()),
_ => Err(ToAsciiCharError(()))
}
}
Err(ToAsciiCharError(()))
}
#[inline]
unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
(self as u8).to_ascii_char_unchecked()
}
}

impl ToAsciiChar for u16 {
fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
(self as u32).to_ascii_char()
}
#[inline]
unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
Expand Down Expand Up @@ -758,7 +784,7 @@ mod tests {
assert_eq!(generic(A), Ok(A));
assert_eq!(generic(b'A'), Ok(A));
assert_eq!(generic('A'), Ok(A));
assert!(generic(200).is_err());
assert!(generic(200u16).is_err());
assert!(generic('λ').is_err());
}

Expand Down

0 comments on commit 828f954

Please sign in to comment.