Skip to content

Commit d0f3cb0

Browse files
committed
Change str::from_utf8_owned() to return Result
This allows the original vector to be recovered in the event that it is not valid UTF-8. [breaking-change]
1 parent e441473 commit d0f3cb0

File tree

2 files changed

+11
-8
lines changed

2 files changed

+11
-8
lines changed

src/doc/complement-cheatsheet.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ To return an Owned String (~str) use the str helper function [`from_utf8_owned`]
6060
~~~
6161
use std::str;
6262
63-
let x: Option<~str> = str::from_utf8_owned(~[104u8,105u8]);
63+
let x: Result<~str,~[u8]> = str::from_utf8_owned(~[104u8,105u8]);
6464
let y: ~str = x.unwrap();
6565
~~~
6666

src/libstd/str.rs

+10-7
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ use iter::{Iterator, range, AdditiveIterator};
8787
use mem::transmute;
8888
use mem;
8989
use option::{None, Option, Some};
90+
use result::{Result, Ok, Err};
9091
use slice::Vector;
9192
use slice::{ImmutableVector, MutableVector, CloneableVector};
9293
use strbuf::StrBuf;
@@ -105,12 +106,14 @@ Section: Creating a string
105106
*/
106107

107108
/// Consumes a vector of bytes to create a new utf-8 string.
108-
/// Returns None if the vector contains invalid UTF-8.
109-
pub fn from_utf8_owned(vv: ~[u8]) -> Option<~str> {
109+
///
110+
/// Returns `Err` with the original vector if the vector contains invalid
111+
/// UTF-8.
112+
pub fn from_utf8_owned(vv: ~[u8]) -> Result<~str, ~[u8]> {
110113
if is_utf8(vv) {
111-
Some(unsafe { raw::from_utf8_owned(vv) })
114+
Ok(unsafe { raw::from_utf8_owned(vv) })
112115
} else {
113-
None
116+
Err(vv)
114117
}
115118
}
116119

@@ -2115,13 +2118,13 @@ mod tests {
21152118
#[test]
21162119
fn test_str_from_utf8_owned() {
21172120
let xs = bytes!("hello").to_owned();
2118-
assert_eq!(from_utf8_owned(xs), Some("hello".to_owned()));
2121+
assert_eq!(from_utf8_owned(xs), Ok("hello".to_owned()));
21192122

21202123
let xs = bytes!("ศไทย中华Việt Nam").to_owned();
2121-
assert_eq!(from_utf8_owned(xs), Some("ศไทย中华Việt Nam".to_owned()));
2124+
assert_eq!(from_utf8_owned(xs), Ok("ศไทย中华Việt Nam".to_owned()));
21222125

21232126
let xs = bytes!("hello", 0xff).to_owned();
2124-
assert_eq!(from_utf8_owned(xs), None);
2127+
assert_eq!(from_utf8_owned(xs), Err(bytes!("hello", 0xff).to_owned()));
21252128
}
21262129

21272130
#[test]

0 commit comments

Comments
 (0)