Skip to content

Commit 7d9f437

Browse files
author
sam skeoch
committed
Add as_ascii_unchecked() methods to char, str, and u8
1 parent 1b9efcd commit 7d9f437

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

library/core/src/char/methods.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1202,6 +1202,20 @@ impl char {
12021202
}
12031203
}
12041204

1205+
/// Converts this char into an [ASCII character](`ascii::Char`), without
1206+
/// checking whether it is valid.
1207+
///
1208+
/// # Safety
1209+
///
1210+
/// This char must be within the ASCII range, or else this is UB.
1211+
#[must_use]
1212+
#[unstable(feature = "ascii_char", issue = "110998")]
1213+
#[inline]
1214+
pub const unsafe fn as_ascii_unchecked(&self) -> ascii::Char {
1215+
// SAFETY: the caller promised that this char is ASCII.
1216+
unsafe { ascii::Char::from_u8_unchecked(*self as u8) }
1217+
}
1218+
12051219
/// Makes a copy of the value in its ASCII upper case equivalent.
12061220
///
12071221
/// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',

library/core/src/num/mod.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,20 @@ impl u8 {
492492
ascii::Char::from_u8(*self)
493493
}
494494

495+
/// Converts this byte to an [ASCII character](ascii::Char), without
496+
/// checking whether or not it's valid.
497+
///
498+
/// # Safety
499+
///
500+
/// This byte must be valid ASCII, or else this is UB.
501+
#[must_use]
502+
#[unstable(feature = "ascii_char", issue = "110998")]
503+
#[inline]
504+
pub const unsafe fn as_ascii_unchecked(&self) -> ascii::Char {
505+
// SAFETY: the caller promised that this byte is ASCII.
506+
unsafe { ascii::Char::from_u8_unchecked(*self) }
507+
}
508+
495509
/// Makes a copy of the value in its ASCII upper case equivalent.
496510
///
497511
/// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',

library/core/src/str/mod.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2634,6 +2634,21 @@ impl str {
26342634
self.as_bytes().as_ascii()
26352635
}
26362636

2637+
/// Converts this string slice into a slice of [ASCII characters](ascii::Char),
2638+
/// without checking whether they are valid.
2639+
///
2640+
/// # Safety
2641+
///
2642+
/// Every character in this string must be ASCII, or else this is UB.
2643+
#[unstable(feature = "ascii_char", issue = "110998")]
2644+
#[must_use]
2645+
#[inline]
2646+
pub const unsafe fn as_ascii_unchecked(&self) -> &[ascii::Char] {
2647+
// SAFETY: the caller promised that every byte of this string slice
2648+
// is ASCII.
2649+
unsafe { self.as_bytes().as_ascii_unchecked() }
2650+
}
2651+
26372652
/// Checks that two strings are an ASCII case-insensitive match.
26382653
///
26392654
/// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,

0 commit comments

Comments
 (0)