Skip to content

Commit 239b81f

Browse files
committedJun 8, 2013
std: Change str::from_bytes to raise a condition on invalid input
As per #4765
1 parent b8cf2f8 commit 239b81f

File tree

1 file changed

+31
-6
lines changed

1 file changed

+31
-6
lines changed
 

‎src/libstd/str.rs

+31-6
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,13 @@ use vec::{OwnedVector, OwnedCopyableVector};
3939

4040
#[cfg(not(test))] use cmp::{Eq, Ord, Equiv, TotalEq};
4141

42+
/*
43+
Section: Conditions
44+
*/
45+
condition! {
46+
not_utf8: (~str) -> ~str;
47+
}
48+
4249
/*
4350
Section: Creating a string
4451
*/
@@ -48,11 +55,20 @@ Section: Creating a string
4855
*
4956
* # Failure
5057
*
51-
* Fails if invalid UTF-8
58+
* Raises the `not_utf8` condition if invalid UTF-8
5259
*/
53-
pub fn from_bytes(vv: &const [u8]) -> ~str {
54-
assert!(is_utf8(vv));
55-
return unsafe { raw::from_bytes(vv) };
60+
61+
pub fn from_bytes(vv: &[u8]) -> ~str {
62+
use str::not_utf8::cond;
63+
64+
if !is_utf8(vv) {
65+
let first_bad_byte = vec::find(vv, |b| !is_utf8([*b])).get();
66+
cond.raise(fmt!("from_bytes: input is not UTF-8; first bad byte is %u",
67+
first_bad_byte as uint))
68+
}
69+
else {
70+
return unsafe { raw::from_bytes(vv) }
71+
}
5672
}
5773

5874
/**
@@ -3563,9 +3579,10 @@ mod tests {
35633579
}
35643580
35653581
#[test]
3566-
#[should_fail]
35673582
#[ignore(cfg(windows))]
35683583
fn test_from_bytes_fail() {
3584+
use str::not_utf8::cond;
3585+
35693586
let bb = ~[0xff_u8, 0xb8_u8, 0xa8_u8,
35703587
0xe0_u8, 0xb9_u8, 0x84_u8,
35713588
0xe0_u8, 0xb8_u8, 0x97_u8,
@@ -3577,7 +3594,15 @@ mod tests {
35773594
0x20_u8, 0x4e_u8, 0x61_u8,
35783595
0x6d_u8];
35793596
3580-
let _x = from_bytes(bb);
3597+
let mut error_happened = false;
3598+
let _x = do cond.trap(|err| {
3599+
assert_eq!(err, ~"from_bytes: input is not UTF-8; first bad byte is 255");
3600+
error_happened = true;
3601+
~""
3602+
}).in {
3603+
from_bytes(bb)
3604+
};
3605+
assert!(error_happened);
35813606
}
35823607
35833608
#[test]

0 commit comments

Comments
 (0)