Skip to content

Commit cae5999

Browse files
committed
auto merge of #12317 : huonw/rust/utf16, r=alexcrichton
Iterators! Use them (in `is_utf16`), create them (in `utf16_items`). Handle errors gracefully (`from_utf16_lossy`) and `from_utf16` returning `Option<~str>` instead of failing. Add a pile of tests.
2 parents a25f447 + c9b4538 commit cae5999

File tree

3 files changed

+308
-51
lines changed

3 files changed

+308
-51
lines changed

src/libnative/io/file.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -571,7 +571,9 @@ pub fn readdir(p: &CString) -> IoResult<~[Path]> {
571571
else {
572572
let fp_vec = vec::from_buf(
573573
fp_buf, wcslen(fp_buf) as uint);
574-
let fp_str = str::from_utf16(fp_vec);
574+
let fp_trimmed = str::truncate_utf16_at_nul(fp_vec);
575+
let fp_str = str::from_utf16(fp_trimmed)
576+
.expect("rust_list_dir_wfd_fp_buf returned invalid UTF-16");
575577
paths.push(Path::new(fp_str));
576578
}
577579
more_files = FindNextFileW(find_handle, wfd_ptr as HANDLE);

src/libstd/os.rs

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,8 @@ pub fn getcwd() -> Path {
8888
fail!();
8989
}
9090
}
91-
Path::new(str::from_utf16(buf))
91+
Path::new(str::from_utf16(str::truncate_utf16_at_nul(buf))
92+
.expect("GetCurrentDirectoryW returned invalid UTF-16"))
9293
}
9394

9495
#[cfg(windows)]
@@ -124,7 +125,12 @@ pub mod win32 {
124125
}
125126
if k != 0 && done {
126127
let sub = buf.slice(0, k as uint);
127-
res = option::Some(str::from_utf16(sub));
128+
// We want to explicitly catch the case when the
129+
// closure returned invalid UTF-16, rather than
130+
// set `res` to None and continue.
131+
let s = str::from_utf16(sub)
132+
.expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
133+
res = option::Some(s)
128134
}
129135
}
130136
return res;
@@ -739,7 +745,8 @@ pub fn last_os_error() -> ~str {
739745
fail!("[{}] FormatMessage failure", errno());
740746
}
741747

742-
str::from_utf16(buf)
748+
str::from_utf16(str::truncate_utf16_at_nul(buf))
749+
.expect("FormatMessageW returned invalid UTF-16")
743750
}
744751
}
745752

@@ -828,8 +835,10 @@ fn real_args() -> ~[~str] {
828835
while *ptr.offset(len as int) != 0 { len += 1; }
829836

830837
// Push it onto the list.
831-
args.push(vec::raw::buf_as_slice(ptr, len,
832-
str::from_utf16));
838+
let opt_s = vec::raw::buf_as_slice(ptr, len, |buf| {
839+
str::from_utf16(str::truncate_utf16_at_nul(buf))
840+
});
841+
args.push(opt_s.expect("CommandLineToArgvW returned invalid UTF-16"));
833842
}
834843
}
835844

0 commit comments

Comments
 (0)