@@ -39,6 +39,13 @@ use vec::{OwnedVector, OwnedCopyableVector};
39
39
40
40
#[ cfg( not( test) ) ] use cmp:: { Eq , Ord , Equiv , TotalEq } ;
41
41
42
+ /*
43
+ Section: Conditions
44
+ */
45
+ condition ! {
46
+ not_utf8: ( ~str ) -> ~str ;
47
+ }
48
+
42
49
/*
43
50
Section: Creating a string
44
51
*/
@@ -48,11 +55,20 @@ Section: Creating a string
48
55
*
49
56
* # Failure
50
57
*
51
- * Fails if invalid UTF-8
58
+ * Raises the `not_utf8` condition if invalid UTF-8
52
59
*/
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
+ }
56
72
}
57
73
58
74
/**
@@ -3563,9 +3579,10 @@ mod tests {
3563
3579
}
3564
3580
3565
3581
#[test]
3566
- #[should_fail]
3567
3582
#[ignore(cfg(windows))]
3568
3583
fn test_from_bytes_fail() {
3584
+ use str::not_utf8::cond;
3585
+
3569
3586
let bb = ~[0xff_u8, 0xb8_u8, 0xa8_u8,
3570
3587
0xe0_u8, 0xb9_u8, 0x84_u8,
3571
3588
0xe0_u8, 0xb8_u8, 0x97_u8,
@@ -3577,7 +3594,15 @@ mod tests {
3577
3594
0x20_u8, 0x4e_u8, 0x61_u8,
3578
3595
0x6d_u8];
3579
3596
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);
3581
3606
}
3582
3607
3583
3608
#[test]
0 commit comments