diff options
| author | Kevin Ballard <kevin@sb.org> | 2014-05-14 16:48:05 -0700 |
|---|---|---|
| committer | Kevin Ballard <kevin@sb.org> | 2014-05-14 17:35:55 -0700 |
| commit | d0f3cb05df41b14b58553fab6a533e0e4c947b06 (patch) | |
| tree | 911de97c3495219eaff1e4def891ed0d2b8ec0a2 /src/libstd | |
| parent | e4414739a5897ff2a4b35de5f7e1436b6e3f3f10 (diff) | |
| download | rust-d0f3cb05df41b14b58553fab6a533e0e4c947b06.tar.gz rust-d0f3cb05df41b14b58553fab6a533e0e4c947b06.zip | |
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]
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/str.rs | 17 |
1 files changed, 10 insertions, 7 deletions
diff --git a/src/libstd/str.rs b/src/libstd/str.rs index fa4cf8e4427..5f117ca0821 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -87,6 +87,7 @@ use iter::{Iterator, range, AdditiveIterator}; use mem::transmute; use mem; use option::{None, Option, Some}; +use result::{Result, Ok, Err}; use slice::Vector; use slice::{ImmutableVector, MutableVector, CloneableVector}; use strbuf::StrBuf; @@ -105,12 +106,14 @@ Section: Creating a string */ /// Consumes a vector of bytes to create a new utf-8 string. -/// Returns None if the vector contains invalid UTF-8. -pub fn from_utf8_owned(vv: ~[u8]) -> Option<~str> { +/// +/// Returns `Err` with the original vector if the vector contains invalid +/// UTF-8. +pub fn from_utf8_owned(vv: ~[u8]) -> Result<~str, ~[u8]> { if is_utf8(vv) { - Some(unsafe { raw::from_utf8_owned(vv) }) + Ok(unsafe { raw::from_utf8_owned(vv) }) } else { - None + Err(vv) } } @@ -2115,13 +2118,13 @@ mod tests { #[test] fn test_str_from_utf8_owned() { let xs = bytes!("hello").to_owned(); - assert_eq!(from_utf8_owned(xs), Some("hello".to_owned())); + assert_eq!(from_utf8_owned(xs), Ok("hello".to_owned())); let xs = bytes!("ศไทย中华Việt Nam").to_owned(); - assert_eq!(from_utf8_owned(xs), Some("ศไทย中华Việt Nam".to_owned())); + assert_eq!(from_utf8_owned(xs), Ok("ศไทย中华Việt Nam".to_owned())); let xs = bytes!("hello", 0xff).to_owned(); - assert_eq!(from_utf8_owned(xs), None); + assert_eq!(from_utf8_owned(xs), Err(bytes!("hello", 0xff).to_owned())); } #[test] |
