Skip to content

Commit 828f954

Browse files
tormolThomas Bahn
authored andcommitted
Implement ToAsciiChar for i8, u16 and u32
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).
1 parent 1d6793b commit 828f954

File tree

1 file changed

+36
-10
lines changed

1 file changed

+36
-10
lines changed

src/ascii_char.rs

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -675,12 +675,18 @@ impl ToAsciiChar for AsciiChar {
675675
impl ToAsciiChar for u8 {
676676
#[inline]
677677
fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
678-
unsafe {
679-
if self <= 0x7F {
680-
return Ok(self.to_ascii_char_unchecked());
681-
}
682-
}
683-
Err(ToAsciiCharError(()))
678+
(self as u32).to_ascii_char()
679+
}
680+
#[inline]
681+
unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
682+
mem::transmute(self)
683+
}
684+
}
685+
686+
impl ToAsciiChar for i8 {
687+
#[inline]
688+
fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
689+
(self as u32).to_ascii_char()
684690
}
685691
#[inline]
686692
unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
@@ -690,13 +696,33 @@ impl ToAsciiChar for u8 {
690696

691697
impl ToAsciiChar for char {
692698
#[inline]
699+
fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
700+
(self as u32).to_ascii_char()
701+
}
702+
#[inline]
703+
unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
704+
(self as u32).to_ascii_char_unchecked()
705+
}
706+
}
707+
708+
impl ToAsciiChar for u32 {
693709
fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
694710
unsafe {
695-
if self as u32 <= 0x7F {
696-
return Ok(self.to_ascii_char_unchecked());
711+
match self {
712+
0..=127 => Ok(self.to_ascii_char_unchecked()),
713+
_ => Err(ToAsciiCharError(()))
697714
}
698715
}
699-
Err(ToAsciiCharError(()))
716+
}
717+
#[inline]
718+
unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
719+
(self as u8).to_ascii_char_unchecked()
720+
}
721+
}
722+
723+
impl ToAsciiChar for u16 {
724+
fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
725+
(self as u32).to_ascii_char()
700726
}
701727
#[inline]
702728
unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
@@ -758,7 +784,7 @@ mod tests {
758784
assert_eq!(generic(A), Ok(A));
759785
assert_eq!(generic(b'A'), Ok(A));
760786
assert_eq!(generic('A'), Ok(A));
761-
assert!(generic(200).is_err());
787+
assert!(generic(200u16).is_err());
762788
assert!(generic('λ').is_err());
763789
}
764790

0 commit comments

Comments
 (0)