Skip to content

Commit 8f4d1f3

Browse files
killerswannikomatsakis
authored andcommitted
Added str::from_bytes (which is UTF-8 safe)
1 parent 7608a06 commit 8f4d1f3

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/libcore/str.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ export eq, lteq, hash, is_empty, is_not_empty, is_whitespace, byte_len,
1313
push_char, is_utf8, from_chars, to_chars, char_len, char_len_range,
1414
char_at, bytes, is_ascii, shift_byte, pop_byte,
1515
unsafe_from_byte, unsafe_from_bytes, from_char, char_range_at,
16+
from_bytes,
1617
from_cstr, sbuf, as_buf, push_byte, utf8_char_width, safe_slice,
1718
contains, iter_chars, chars_iter, bytes_iter, words_iter, lines_iter,
1819
loop_chars, loop_chars_sub, escape, any, all, map, windowed;
@@ -191,6 +192,19 @@ fn unsafe_from_bytes(v: [const u8]) -> str unsafe {
191192
ret scopy;
192193
}
193194

195+
/*
196+
Function: from_bytes
197+
198+
Safely convert a vector of bytes to a UTF-8 string, or error
199+
*/
200+
fn from_bytes(vv: [u8]) -> result::t<str, str> {
201+
if is_utf8(vv) {
202+
ret result::ok(unsafe_from_bytes(vv));
203+
} else {
204+
ret result::err("vector doesn't contain valid UTF-8");
205+
}
206+
}
207+
194208
/*
195209
Function: unsafe_from_byte
196210
@@ -1594,6 +1608,23 @@ mod tests {
15941608
assert (b == "AAAAAAA");
15951609
}
15961610

1611+
#[test]
1612+
fn test_from_bytes() {
1613+
let ss = "ศไทย中华Việt Nam";
1614+
let bb = [0xe0_u8, 0xb8_u8, 0xa8_u8,
1615+
0xe0_u8, 0xb9_u8, 0x84_u8,
1616+
0xe0_u8, 0xb8_u8, 0x97_u8,
1617+
0xe0_u8, 0xb8_u8, 0xa2_u8,
1618+
0xe4_u8, 0xb8_u8, 0xad_u8,
1619+
0xe5_u8, 0x8d_u8, 0x8e_u8,
1620+
0x56_u8, 0x69_u8, 0xe1_u8,
1621+
0xbb_u8, 0x87_u8, 0x74_u8,
1622+
0x20_u8, 0x4e_u8, 0x61_u8,
1623+
0x6d_u8];
1624+
1625+
assert ss == result::get(from_bytes(bb));
1626+
}
1627+
15971628
#[test]
15981629
fn test_from_cstr() unsafe {
15991630
let a = [65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 0u8];

0 commit comments

Comments
 (0)