]> git.lizzy.rs Git - rust.git/commitdiff
Change str::from_utf8_owned() to return Result
authorKevin Ballard <kevin@sb.org>
Wed, 14 May 2014 23:48:05 +0000 (16:48 -0700)
committerKevin Ballard <kevin@sb.org>
Thu, 15 May 2014 00:35:55 +0000 (17:35 -0700)
This allows the original vector to be recovered in the event that it is
not valid UTF-8.

[breaking-change]

src/doc/complement-cheatsheet.md
src/libstd/str.rs

index 804d878398bf9018f6bedee78346c5a6824c792f..5cd555cad8ea9e66517a809da0926bdd050c8a25 100644 (file)
@@ -60,7 +60,7 @@ To return an Owned String (~str) use the str helper function [`from_utf8_owned`]
 ~~~
 use std::str;
 
-let x: Option<~str> = str::from_utf8_owned(~[104u8,105u8]);
+let x: Result<~str,~[u8]> = str::from_utf8_owned(~[104u8,105u8]);
 let y: ~str = x.unwrap();
 ~~~
 
index fa4cf8e4427d0473b14e10fc5ebf1f1f8f35f101..5f117ca08213cc0a2eff988e395168f1bbd03bc1 100644 (file)
@@ -87,6 +87,7 @@ fn main() {
 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 @@ fn main() {
 */
 
 /// 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 @@ fn test_str_from_utf8() {
     #[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]