Deprecate `str::from_utf8_owned`

Use `String::from_utf8` instead

[breaking-change]
This commit is contained in:
Adolfo Ochagavía 2014-06-30 16:41:30 +02:00
parent 1704ebb798
commit 211f1caa29
28 changed files with 80 additions and 86 deletions

View File

@ -8,7 +8,6 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::str;
use std::io::process::{ProcessExit, Command, Process, ProcessOutput};
use std::dynamic_lib::DynamicLibrary;
@ -25,7 +24,7 @@ fn add_target_env(cmd: &mut Command, lib_path: &str, aux_path: Option<&str>) {
// Add the new dylib search path var
let var = DynamicLibrary::envvar();
let newpath = DynamicLibrary::create_path(path.as_slice());
let newpath = str::from_utf8(newpath.as_slice()).unwrap().to_string();
let newpath = String::from_utf8(newpath).unwrap();
cmd.env(var.to_string(), newpath);
}
@ -55,8 +54,8 @@ pub fn run(lib_path: &str,
Some(Result {
status: status,
out: str::from_utf8(output.as_slice()).unwrap().to_string(),
err: str::from_utf8(error.as_slice()).unwrap().to_string()
out: String::from_utf8(output).unwrap(),
err: String::from_utf8(error).unwrap()
})
},
Err(..) => None

View File

@ -158,7 +158,7 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
match props.pp_exact { Some(_) => 1, None => 2 };
let src = File::open(testfile).read_to_end().unwrap();
let src = str::from_utf8(src.as_slice()).unwrap().to_string();
let src = String::from_utf8(src.clone()).unwrap();
let mut srcs = vec!(src);
let mut round = 0;
@ -185,10 +185,10 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
Some(ref file) => {
let filepath = testfile.dir_path().join(file);
let s = File::open(&filepath).read_to_end().unwrap();
str::from_utf8(s.as_slice()).unwrap().to_string()
}
None => { (*srcs.get(srcs.len() - 2u)).clone() }
};
String::from_utf8(s).unwrap()
}
None => { (*srcs.get(srcs.len() - 2u)).clone() }
};
let mut actual = (*srcs.get(srcs.len() - 1u)).clone();
if props.pp_exact.is_some() {
@ -582,8 +582,8 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path)
process.wait_with_output().unwrap();
(status,
str::from_utf8(output.as_slice()).unwrap().to_string(),
str::from_utf8(error.as_slice()).unwrap().to_string())
String::from_utf8(output).unwrap(),
String::from_utf8(error).unwrap())
},
Err(e) => {
fatal(format!("Failed to setup Python process for \

View File

@ -107,6 +107,7 @@ Section: Creating a string
/// let string = str::from_utf8_owned(hello_vec);
/// assert_eq!(string, Ok("hello".to_string()));
/// ```
#[deprecated = "Replaced by `String::from_utf8`"]
pub fn from_utf8_owned(vv: Vec<u8>) -> Result<String, Vec<u8>> {
String::from_utf8(vv)
}
@ -139,9 +140,7 @@ pub fn from_byte(b: u8) -> String {
/// assert_eq!(string.as_slice(), "b");
/// ```
pub fn from_char(ch: char) -> String {
let mut buf = String::new();
buf.push_char(ch);
buf
String::from_char(ch)
}
/// Convert a vector of chars to a string
@ -2175,19 +2174,6 @@ String::from_str("\u1111\u1171\u11b6"));
assert_eq!(from_utf8(xs), None);
}
#[test]
fn test_str_from_utf8_owned() {
let xs = Vec::from_slice(b"hello");
assert_eq!(from_utf8_owned(xs), Ok(String::from_str("hello")));
let xs = Vec::from_slice("ศไทย中华Việt Nam".as_bytes());
assert_eq!(from_utf8_owned(xs), Ok(String::from_str("ศไทย中华Việt Nam")));
let xs = Vec::from_slice(b"hello\xFF");
assert_eq!(from_utf8_owned(xs),
Err(Vec::from_slice(b"hello\xFF")));
}
#[test]
fn test_str_from_utf8_lossy() {
let xs = b"hello";

View File

@ -75,6 +75,14 @@ impl String {
///
/// Returns `Err` with the original vector if the vector contains invalid
/// UTF-8.
///
/// # Example
///
/// ```rust
/// let hello_vec = vec![104, 101, 108, 108, 111];
/// let string = String::from_utf8(hello_vec);
/// assert_eq!(string, Ok("hello".to_string()));
/// ```
#[inline]
pub fn from_utf8(vec: Vec<u8>) -> Result<String, Vec<u8>> {
if str::is_utf8(vec.as_slice()) {
@ -391,6 +399,19 @@ mod tests {
});
}
#[test]
fn test_str_from_utf8() {
let xs = Vec::from_slice(b"hello");
assert_eq!(String::from_utf8(xs), Ok("hello".to_string()));
let xs = Vec::from_slice("ศไทย中华Việt Nam".as_bytes());
assert_eq!(String::from_utf8(xs), Ok("ศไทย中华Việt Nam".to_string()));
let xs = Vec::from_slice(b"hello\xFF");
assert_eq!(String::from_utf8(xs),
Err(Vec::from_slice(b"hello\xFF")));
}
#[test]
fn test_push_bytes() {
let mut s = String::from_str("ABC");

View File

@ -575,7 +575,6 @@ struct P {a: int, b: f64}
#[test]
fn test_repr() {
use std::str;
use std::io::stdio::println;
use std::char::is_alphabetic;
use std::mem::swap;
@ -584,7 +583,7 @@ fn test_repr() {
fn exact_test<T>(t: &T, e:&str) {
let mut m = io::MemWriter::new();
write_repr(&mut m as &mut io::Writer, t).unwrap();
let s = str::from_utf8(m.unwrap().as_slice()).unwrap().to_string();
let s = String::from_utf8(m.unwrap()).unwrap();
assert_eq!(s.as_slice(), e);
}

View File

@ -163,7 +163,7 @@ fn gen_text(n: uint) -> String {
*b = '\n' as u8
}
}
str::from_utf8(bytes.as_slice()).unwrap().to_string()
String::from_utf8(bytes).unwrap()
}
throughput!(easy0_32, easy0(), 32)

View File

@ -380,8 +380,7 @@ pub mod write {
sess.note(format!("{}", &cmd).as_slice());
let mut note = prog.error.clone();
note.push_all(prog.output.as_slice());
sess.note(str::from_utf8(note.as_slice()).unwrap()
.as_slice());
sess.note(str::from_utf8(note.as_slice()).unwrap());
sess.abort_if_errors();
}
},
@ -1177,8 +1176,7 @@ fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool,
sess.note(format!("{}", &cmd).as_slice());
let mut output = prog.error.clone();
output.push_all(prog.output.as_slice());
sess.note(str::from_utf8(output.as_slice()).unwrap()
.as_slice());
sess.note(str::from_utf8(output.as_slice()).unwrap());
sess.abort_if_errors();
}
},

View File

@ -82,8 +82,7 @@ fn run_compiler(args: &[String]) {
let ifile = matches.free.get(0).as_slice();
if ifile == "-" {
let contents = io::stdin().read_to_end().unwrap();
let src = str::from_utf8(contents.as_slice()).unwrap()
.to_string();
let src = String::from_utf8(contents).unwrap();
(StrInput(src), None)
} else {
(FileInput(Path::new(ifile)), Some(Path::new(ifile)))

View File

@ -1922,5 +1922,5 @@ pub fn encoded_ty(tcx: &ty::ctxt, t: ty::t) -> String {
tcx: tcx,
abbrevs: &RefCell::new(HashMap::new())
}, t);
str::from_utf8_owned(Vec::from_slice(wr.get_ref())).unwrap().to_string()
str::from_utf8(wr.get_ref()).unwrap().to_string()
}

View File

@ -460,7 +460,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::IoResult<String>
try!(write!(&mut w, "]}};"));
Ok(str::from_utf8(w.unwrap().as_slice()).unwrap().to_string())
Ok(String::from_utf8(w.unwrap()).unwrap())
}
fn write_shared(cx: &Context,

View File

@ -429,7 +429,7 @@ fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
let mut encoder = json::Encoder::new(&mut w as &mut io::Writer);
krate.encode(&mut encoder).unwrap();
}
str::from_utf8_owned(w.unwrap()).unwrap()
String::from_utf8(w.unwrap()).unwrap()
};
let crate_json = match json::from_str(crate_json_str.as_slice()) {
Ok(j) => j,

View File

@ -146,7 +146,7 @@ impl<'a> ToBase64 for &'a [u8] {
}
unsafe {
str::raw::from_utf8(v.as_slice()).to_string()
str::raw::from_utf8_owned(v)
}
}
}

View File

@ -45,7 +45,7 @@ impl<'a> ToHex for &'a [u8] {
}
unsafe {
str::raw::from_utf8(v.as_slice()).to_string()
str::raw::from_utf8_owned(v)
}
}
}

View File

@ -240,7 +240,7 @@ pub fn decode<T: ::Decodable<Decoder, DecoderError>>(s: &str) -> DecodeResult<T>
/// Shortcut function to encode a `T` into a JSON `String`
pub fn encode<'a, T: Encodable<Encoder<'a>, io::IoError>>(object: &T) -> String {
let buff = Encoder::buffer_encode(object);
str::from_utf8_owned(buff).unwrap()
String::from_utf8(buff).unwrap()
}
impl fmt::Show for ErrorCode {
@ -517,8 +517,7 @@ impl<'a> ::Encoder<io::IoError> for Encoder<'a> {
let mut check_encoder = Encoder::new(&mut buf);
try!(f(transmute(&mut check_encoder)));
}
let out = str::from_utf8_owned(buf.unwrap()).unwrap();
let out = out.as_slice();
let out = str::from_utf8(buf.get_ref()).unwrap();
let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
if needs_wrapping { try!(write!(self.writer, "\"")); }
try!(f(self));
@ -762,8 +761,7 @@ impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> {
let mut check_encoder = PrettyEncoder::new(&mut buf);
try!(f(transmute(&mut check_encoder)));
}
let out = str::from_utf8_owned(buf.unwrap()).unwrap();
let out = out.as_slice();
let out = str::from_utf8(buf.get_ref()).unwrap();
let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
if needs_wrapping { try!(write!(self.writer, "\"")); }
try!(f(self));
@ -810,7 +808,7 @@ impl Json {
pub fn to_pretty_str(&self) -> String {
let mut s = MemWriter::new();
self.to_pretty_writer(&mut s as &mut io::Writer).unwrap();
str::from_utf8_owned(s.unwrap()).unwrap()
String::from_utf8(s.unwrap()).unwrap()
}
/// If the Json value is an Object, returns the value associated with the provided key.
@ -1728,14 +1726,14 @@ impl<T: Iterator<char>> Builder<T> {
/// Decodes a json value from an `&mut io::Reader`
pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, BuilderError> {
let contents = match rdr.read_to_end() {
Ok(c) => c,
Ok(c) => c,
Err(e) => return Err(io_error_to_error(e))
};
let s = match str::from_utf8_owned(contents) {
Ok(s) => s,
_ => return Err(SyntaxError(NotUtf8, 0, 0))
let s = match str::from_utf8(contents.as_slice()) {
Some(s) => s,
_ => return Err(SyntaxError(NotUtf8, 0, 0))
};
let mut builder = Builder::new(s.as_slice().chars());
let mut builder = Builder::new(s.chars());
builder.build()
}

View File

@ -438,7 +438,7 @@ unsafe fn str_map_bytes(string: String, map: &'static [u8]) -> String {
*b = map[*b as uint];
}
String::from_str(str::from_utf8(bytes.as_slice()).unwrap())
String::from_utf8(bytes).unwrap()
}
#[inline]

View File

@ -464,7 +464,7 @@ pub use core::fmt::{secret_pointer};
pub fn format(args: &Arguments) -> string::String{
let mut output = io::MemWriter::new();
let _ = write!(&mut output, "{}", args);
str::from_utf8(output.unwrap().as_slice()).unwrap().into_string()
String::from_utf8(output.unwrap()).unwrap()
}
impl<'a> Writer for Formatter<'a> {

View File

@ -999,9 +999,9 @@ mod test {
let mut read_buf = [0, .. 1028];
let read_str = match check!(read_stream.read(read_buf)) {
-1|0 => fail!("shouldn't happen"),
n => str::from_utf8(read_buf.slice_to(n)).unwrap().to_owned()
n => str::from_utf8(read_buf.slice_to(n)).unwrap().to_string()
};
assert_eq!(read_str, message.to_owned());
assert_eq!(read_str.as_slice(), message);
}
check!(unlink(filename));
})

View File

@ -705,9 +705,9 @@ pub trait Reader {
/// UTF-8 bytes.
fn read_to_string(&mut self) -> IoResult<String> {
self.read_to_end().and_then(|s| {
match str::from_utf8(s.as_slice()) {
Some(s) => Ok(String::from_str(s)),
None => Err(standard_error(InvalidInput)),
match String::from_utf8(s) {
Ok(s) => Ok(s),
Err(_) => Err(standard_error(InvalidInput)),
}
})
}
@ -1440,9 +1440,9 @@ pub trait Buffer: Reader {
/// valid UTF-8 sequence of bytes.
fn read_line(&mut self) -> IoResult<String> {
self.read_until('\n' as u8).and_then(|line|
match str::from_utf8(line.as_slice()) {
Some(s) => Ok(String::from_str(s)),
None => Err(standard_error(InvalidInput)),
match String::from_utf8(line) {
Ok(s) => Ok(s),
Err(_) => Err(standard_error(InvalidInput)),
}
)
}

View File

@ -813,8 +813,7 @@ mod tests {
use os;
let prog = pwd_cmd().spawn().unwrap();
let output = str::from_utf8(prog.wait_with_output().unwrap()
.output.as_slice()).unwrap().to_string();
let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
let parent_dir = os::getcwd();
let child_dir = Path::new(output.as_slice().trim());
@ -832,8 +831,7 @@ mod tests {
let parent_dir = os::getcwd().dir_path();
let prog = pwd_cmd().cwd(&parent_dir).spawn().unwrap();
let output = str::from_utf8(prog.wait_with_output().unwrap()
.output.as_slice()).unwrap().to_string();
let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
let child_dir = Path::new(output.as_slice().trim().into_string());
let parent_stat = parent_dir.stat().unwrap();
@ -867,8 +865,7 @@ mod tests {
if running_on_valgrind() { return; }
let prog = env_cmd().spawn().unwrap();
let output = str::from_utf8(prog.wait_with_output().unwrap()
.output.as_slice()).unwrap().to_string();
let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
let r = os::env();
for &(ref k, ref v) in r.iter() {
@ -884,9 +881,7 @@ mod tests {
if running_on_valgrind() { return; }
let mut prog = env_cmd().spawn().unwrap();
let output = str::from_utf8(prog.wait_with_output()
.unwrap().output.as_slice())
.unwrap().to_string();
let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
let r = os::env();
for &(ref k, ref v) in r.iter() {

View File

@ -997,7 +997,7 @@ mod test {
macro_rules! t( ($a:expr, $b:expr) => ({
let mut m = MemWriter::new();
super::demangle(&mut m, $a).unwrap();
assert_eq!(str::from_utf8(m.unwrap().as_slice()).unwrap().to_owned(), $b.to_owned());
assert_eq!(String::from_utf8(m.unwrap()).unwrap(), $b.to_string());
}) )
#[test]

View File

@ -122,17 +122,17 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
}
Ok(bytes) => bytes,
};
match str::from_utf8(bytes.as_slice()) {
Some(src) => {
match String::from_utf8(bytes) {
Ok(src) => {
// Add this input file to the code map to make it available as
// dependency information
let filename = file.display().to_string();
let interned = token::intern_and_get_ident(src);
cx.codemap().new_filemap(filename, src.to_string());
let interned = token::intern_and_get_ident(src.as_slice());
cx.codemap().new_filemap(filename, src);
base::MacExpr::new(cx.expr_str(sp, interned))
}
None => {
Err(_) => {
cx.span_err(sp,
format!("{} wasn't a utf-8 file",
file.display()).as_slice());

View File

@ -339,7 +339,7 @@ pub fn gather_comments_and_literals(span_diagnostic: &diagnostic::SpanHandler,
srdr: &mut io::Reader)
-> (Vec<Comment>, Vec<Literal>) {
let src = srdr.read_to_end().unwrap();
let src = str::from_utf8(src.as_slice()).unwrap().to_string();
let src = String::from_utf8(src).unwrap();
let cm = CodeMap::new();
let filemap = cm.new_filemap(path, src);
let mut rdr = lexer::StringReader::new_raw(span_diagnostic, filemap);

View File

@ -138,7 +138,7 @@ pub fn to_string(f: |&mut State| -> IoResult<()>) -> String {
// downcasts.
let (_, wr): (uint, Box<MemWriter>) = mem::transmute_copy(&s.s.out);
let result =
str::from_utf8_owned(Vec::from_slice(wr.get_ref())).unwrap();
String::from_utf8(Vec::from_slice(wr.get_ref())).unwrap();
mem::forget(wr);
result.to_string()
}

View File

@ -214,9 +214,9 @@ pub fn parse(file: &mut io::Reader, longnames: bool)
// don't read NUL
let bytes = try!(file.read_exact(names_bytes as uint - 1));
let names_str = match str::from_utf8(bytes.as_slice()) {
Some(s) => s.to_string(),
None => return Err("input not utf-8".to_string()),
let names_str = match String::from_utf8(bytes) {
Ok(s) => s,
Err(_) => return Err("input not utf-8".to_string()),
};
let term_names: Vec<String> = names_str.as_slice()

View File

@ -1030,7 +1030,7 @@ mod tests {
use std::io::MemWriter;
let mut m = MemWriter::new();
write_boxplot(&mut m as &mut io::Writer, s, 30).unwrap();
let out = str::from_utf8(m.unwrap().as_slice()).unwrap().to_string();
let out = String::from_utf8(m.unwrap()).unwrap();
assert_eq!(out, expected);
}

View File

@ -1086,7 +1086,7 @@ pub fn strftime(format: &str, tm: &Tm) -> String {
}
}
str::from_utf8(buf.as_slice()).unwrap().to_string()
String::from_utf8(buf).unwrap()
}
#[cfg(test)]

View File

@ -327,7 +327,7 @@ impl Uuid {
*s.get_mut(i*2+0) = digit.as_bytes()[0];
*s.get_mut(i*2+1) = digit.as_bytes()[1];
}
str::from_utf8(s.as_slice()).unwrap().to_string()
String::from_utf8(s).unwrap()
}
/// Returns a string of hexadecimal digits, separated into groups with a hyphen.

View File

@ -14,7 +14,6 @@ use serialize::{Encodable, Encoder};
use serialize::json;
use serialize::ebml::writer;
use std::io::MemWriter;
use std::str::from_utf8_owned;
#[deriving(Encodable)]
struct Foo {