Skip to content

Commit 041e170

Browse files
committed
use of wmemchr for faster searching in [u16]
1 parent 76b1198 commit 041e170

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

src/libstd/sys/windows/mod.rs

+12-2
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,20 @@ pub fn decode_error_kind(errno: i32) -> ErrorKind {
8181
}
8282
}
8383

84+
pub fn wmemchr(needle: u16, haystack: &[u16]) -> Option<usize> {
85+
extern "C" {
86+
fn wmemchr(s: *const u16, c: u16, n: usize) -> *mut u16;
87+
}
88+
let len = haystack.len();
89+
let ptr = haystack.as_ptr();
90+
let p = unsafe { wmemchr(ptr, needle, len) };
91+
if p.is_null() { None } else { Some((p as usize - ptr as usize) / 2) }
92+
}
93+
8494
pub fn to_u16s<S: AsRef<OsStr>>(s: S) -> crate::io::Result<Vec<u16>> {
8595
fn inner(s: &OsStr) -> crate::io::Result<Vec<u16>> {
8696
let mut maybe_result: Vec<u16> = s.encode_wide().collect();
87-
if maybe_result.iter().any(|&u| u == 0) {
97+
if wmemchr(0, &maybe_result).is_some() {
8898
return Err(crate::io::Error::new(
8999
ErrorKind::InvalidInput,
90100
"strings passed to WinAPI cannot contain NULs",
@@ -214,7 +224,7 @@ fn wide_char_to_multi_byte(
214224
}
215225

216226
pub fn truncate_utf16_at_nul(v: &[u16]) -> &[u16] {
217-
match v.iter().position(|c| *c == 0) {
227+
match wmemchr(0, v) {
218228
// don't include the 0
219229
Some(i) => &v[..i],
220230
None => v,

0 commit comments

Comments
 (0)