Skip to content

Commit 101e24a

Browse files
committed
Add assert_unsafe_precondition!()s to as_ascii_unchecked() methods
1 parent 7d9f437 commit 101e24a

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

library/core/src/char/methods.rs

+7
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use super::*;
44
use crate::panic::const_panic;
55
use crate::slice;
66
use crate::str::from_utf8_unchecked_mut;
7+
use crate::ub_checks::assert_unsafe_precondition;
78
use crate::unicode::printable::is_printable;
89
use crate::unicode::{self, conversions};
910

@@ -1212,6 +1213,12 @@ impl char {
12121213
#[unstable(feature = "ascii_char", issue = "110998")]
12131214
#[inline]
12141215
pub const unsafe fn as_ascii_unchecked(&self) -> ascii::Char {
1216+
assert_unsafe_precondition!(
1217+
check_library_ub,
1218+
"as_ascii_unchecked requires that the char is valid ASCII",
1219+
(it: &char = self) => it.is_ascii()
1220+
);
1221+
12151222
// SAFETY: the caller promised that this char is ASCII.
12161223
unsafe { ascii::Char::from_u8_unchecked(*self as u8) }
12171224
}

library/core/src/num/mod.rs

+6
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,12 @@ impl u8 {
502502
#[unstable(feature = "ascii_char", issue = "110998")]
503503
#[inline]
504504
pub const unsafe fn as_ascii_unchecked(&self) -> ascii::Char {
505+
assert_unsafe_precondition!(
506+
check_library_ub,
507+
"as_ascii_unchecked requires that the byte is valid ASCII",
508+
(it: &u8 = self) => it.is_ascii()
509+
);
510+
505511
// SAFETY: the caller promised that this byte is ASCII.
506512
unsafe { ascii::Char::from_u8_unchecked(*self) }
507513
}

library/core/src/str/mod.rs

+7
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use self::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher};
1717
use crate::char::{self, EscapeDebugExtArgs};
1818
use crate::ops::Range;
1919
use crate::slice::{self, SliceIndex};
20+
use crate::ub_checks::assert_unsafe_precondition;
2021
use crate::{ascii, mem};
2122

2223
pub mod pattern;
@@ -2644,6 +2645,12 @@ impl str {
26442645
#[must_use]
26452646
#[inline]
26462647
pub const unsafe fn as_ascii_unchecked(&self) -> &[ascii::Char] {
2648+
assert_unsafe_precondition!(
2649+
check_library_ub,
2650+
"as_ascii_unchecked requires that the string is valid ASCII",
2651+
(it: &str = self) => it.is_ascii()
2652+
);
2653+
26472654
// SAFETY: the caller promised that every byte of this string slice
26482655
// is ASCII.
26492656
unsafe { self.as_bytes().as_ascii_unchecked() }

0 commit comments

Comments
 (0)