Skip to content

Commit 7cfbe54

Browse files
committed
assert!() instead of panic!() for expected invariant
1 parent 3103f5f commit 7cfbe54

File tree

1 file changed

+30
-32
lines changed

1 file changed

+30
-32
lines changed

library/std/src/sys/windows/stdio.rs

+30-32
Original file line numberDiff line numberDiff line change
@@ -78,43 +78,41 @@ fn write(
7878
return ret;
7979
}
8080

81-
match incomplete_utf8.len {
82-
0 => {}
83-
1..=3 => {
84-
if data[0] >> 6 != 0b10 {
85-
incomplete_utf8.len = 0;
86-
// not a continuation byte - reject
81+
if incomplete_utf8.len > 0 {
82+
assert!(
83+
incomplete_utf8.len < 4,
84+
"Unexpected number of bytes for incomplete UTF-8 codepoint."
85+
);
86+
if data[0] >> 6 != 0b10 {
87+
incomplete_utf8.len = 0;
88+
// not a continuation byte - reject
89+
return Err(io::Error::new_const(
90+
io::ErrorKind::InvalidData,
91+
&"Windows stdio in console mode does not support writing non-UTF-8 byte sequences",
92+
));
93+
}
94+
incomplete_utf8.bytes[incomplete_utf8.len as usize] = data[0];
95+
incomplete_utf8.len += 1;
96+
let char_width = utf8_char_width(incomplete_utf8.bytes[0]);
97+
if (incomplete_utf8.len as usize) < char_width {
98+
// more bytes needed
99+
return Ok(1);
100+
}
101+
let s = str::from_utf8(&incomplete_utf8.bytes[0..incomplete_utf8.len as usize]);
102+
incomplete_utf8.len = 0;
103+
match s {
104+
Ok(s) => {
105+
assert_eq!(char_width, s.len());
106+
let written = write_valid_utf8_to_console(handle, s)?;
107+
assert_eq!(written, s.len()); // guaranteed by write_valid_utf8_to_console() for single codepoint writes
108+
return Ok(1);
109+
}
110+
Err(_) => {
87111
return Err(io::Error::new_const(
88112
io::ErrorKind::InvalidData,
89113
&"Windows stdio in console mode does not support writing non-UTF-8 byte sequences",
90114
));
91115
}
92-
incomplete_utf8.bytes[incomplete_utf8.len as usize] = data[0];
93-
incomplete_utf8.len += 1;
94-
let char_width = utf8_char_width(incomplete_utf8.bytes[0]);
95-
if (incomplete_utf8.len as usize) < char_width {
96-
// more bytes needed
97-
return Ok(1);
98-
}
99-
let s = str::from_utf8(&incomplete_utf8.bytes[0..incomplete_utf8.len as usize]);
100-
incomplete_utf8.len = 0;
101-
match s {
102-
Ok(s) => {
103-
assert_eq!(char_width, s.len());
104-
let written = write_valid_utf8_to_console(handle, s)?;
105-
assert_eq!(written, s.len()); // guaranteed by write_valid_utf8_to_console() for single codepoint writes
106-
return Ok(1);
107-
}
108-
Err(_) => {
109-
return Err(io::Error::new_const(
110-
io::ErrorKind::InvalidData,
111-
&"Windows stdio in console mode does not support writing non-UTF-8 byte sequences",
112-
));
113-
}
114-
}
115-
}
116-
_ => {
117-
panic!("Unexpected number of incomplete UTF-8 chars.");
118116
}
119117
}
120118

0 commit comments

Comments
 (0)