Skip to content

Commit 4c62aa4

Browse files
committed
Auto merge of #150520 - malbarbo:case_get_unchecked, r=jhpratt
Avoid index check in char::to_lowercase and char::to_uppercase This generates a panic free code, with is helpful for smaller binary sizes.
2 parents 4862272 + 262426d commit 4c62aa4

2 files changed

Lines changed: 8 additions & 4 deletions

File tree

library/core/src/unicode/unicode_data.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -767,7 +767,8 @@ pub mod conversions {
767767
LOWERCASE_TABLE
768768
.binary_search_by(|&(key, _)| key.cmp(&c))
769769
.map(|i| {
770-
let u = LOWERCASE_TABLE[i].1;
770+
// SAFETY: i is the result of the binary search
771+
let u = unsafe { LOWERCASE_TABLE.get_unchecked(i) }.1;
771772
char::from_u32(u).map(|c| [c, '\0', '\0']).unwrap_or_else(|| {
772773
// SAFETY: Index comes from statically generated table
773774
unsafe { *LOWERCASE_TABLE_MULTI.get_unchecked((u & (INDEX_MASK - 1)) as usize) }
@@ -784,7 +785,8 @@ pub mod conversions {
784785
UPPERCASE_TABLE
785786
.binary_search_by(|&(key, _)| key.cmp(&c))
786787
.map(|i| {
787-
let u = UPPERCASE_TABLE[i].1;
788+
// SAFETY: i is the result of the binary search
789+
let u = unsafe { UPPERCASE_TABLE.get_unchecked(i) }.1;
788790
char::from_u32(u).map(|c| [c, '\0', '\0']).unwrap_or_else(|| {
789791
// SAFETY: Index comes from statically generated table
790792
unsafe { *UPPERCASE_TABLE_MULTI.get_unchecked((u & (INDEX_MASK - 1)) as usize) }

src/tools/unicode-table-generator/src/case_mapping.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,8 @@ pub fn to_lower(c: char) -> [char; 3] {
9191
LOWERCASE_TABLE
9292
.binary_search_by(|&(key, _)| key.cmp(&c))
9393
.map(|i| {
94-
let u = LOWERCASE_TABLE[i].1;
94+
// SAFETY: i is the result of the binary search
95+
let u = unsafe { LOWERCASE_TABLE.get_unchecked(i) }.1;
9596
char::from_u32(u).map(|c| [c, '\0', '\0']).unwrap_or_else(|| {
9697
// SAFETY: Index comes from statically generated table
9798
unsafe { *LOWERCASE_TABLE_MULTI.get_unchecked((u & (INDEX_MASK - 1)) as usize) }
@@ -108,7 +109,8 @@ pub fn to_upper(c: char) -> [char; 3] {
108109
UPPERCASE_TABLE
109110
.binary_search_by(|&(key, _)| key.cmp(&c))
110111
.map(|i| {
111-
let u = UPPERCASE_TABLE[i].1;
112+
// SAFETY: i is the result of the binary search
113+
let u = unsafe { UPPERCASE_TABLE.get_unchecked(i) }.1;
112114
char::from_u32(u).map(|c| [c, '\0', '\0']).unwrap_or_else(|| {
113115
// SAFETY: Index comes from statically generated table
114116
unsafe { *UPPERCASE_TABLE_MULTI.get_unchecked((u & (INDEX_MASK - 1)) as usize) }

0 commit comments

Comments
 (0)