From ba7844a7fff0061e5b4528c2ecd5adf765145b70 Mon Sep 17 00:00:00 2001 From: Kevin Ballard Date: Wed, 14 May 2014 16:55:24 -0700 Subject: Change StrBuf::from_utf8() to return Result This allows the original vector to be recovered in the event that it is not UTF-8. [breaking-change] --- src/libstd/num/strconv.rs | 1 + src/libstd/strbuf.rs | 14 +++++++++----- 2 files changed, 10 insertions(+), 5 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/num/strconv.rs b/src/libstd/num/strconv.rs index 4769b17fb2b..63d6219ab8a 100644 --- a/src/libstd/num/strconv.rs +++ b/src/libstd/num/strconv.rs @@ -19,6 +19,7 @@ use num::{Float, FPNaN, FPInfinite, ToPrimitive}; use num; use ops::{Add, Sub, Mul, Div, Rem, Neg}; use option::{None, Option, Some}; +use result::ResultUnwrap; use slice::{CloneableVector, ImmutableVector, MutableVector}; use std::cmp::{Ord, Eq}; use str::{StrAllocating, StrSlice}; diff --git a/src/libstd/strbuf.rs b/src/libstd/strbuf.rs index 575de89fae2..de480ef1b7f 100644 --- a/src/libstd/strbuf.rs +++ b/src/libstd/strbuf.rs @@ -20,6 +20,7 @@ use mem; use option::{None, Option, Some}; use ptr::RawPtr; use ptr; +use result::{Result, Ok, Err}; use slice::{OwnedVector, Vector, CloneableVector}; use str::{CharRange, OwnedStr, Str, StrSlice, StrAllocating}; use str; @@ -72,14 +73,17 @@ impl StrBuf { } } - /// Tries to create a new string buffer from the given byte - /// vector, validating that the vector is UTF-8 encoded. + /// Returns the vector as a string buffer, if possible, taking care not to + /// copy it. + /// + /// Returns `Err` with the original vector if the vector contains invalid + /// UTF-8. #[inline] - pub fn from_utf8(vec: Vec) -> Option { + pub fn from_utf8(vec: Vec) -> Result> { if str::is_utf8(vec.as_slice()) { - Some(StrBuf { vec: vec }) + Ok(StrBuf { vec: vec }) } else { - None + Err(vec) } } -- cgit 1.4.1-3-g733a5