[std::str] Rename from_utf8_owned_opt() to from_utf8_owned(), drop the old from_utf8_owned() behavior

This commit is contained in:
Simon Sapin 2013-12-23 17:45:01 +01:00
parent b8c4149293
commit 05ae134ace
33 changed files with 65 additions and 91 deletions

View File

@ -66,8 +66,8 @@ pub fn run(lib_path: &str,
Some(Result {
status: status,
out: str::from_utf8_owned(output),
err: str::from_utf8_owned(error)
out: str::from_utf8_owned(output).unwrap(),
err: str::from_utf8_owned(error).unwrap()
})
},
None => None

View File

@ -154,7 +154,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();
let src = str::from_utf8_owned(src);
let src = str::from_utf8_owned(src).unwrap();
let mut srcs = ~[src];
let mut round = 0;
@ -176,7 +176,7 @@ 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();
str::from_utf8_owned(s)
str::from_utf8_owned(s).unwrap()
}
None => { srcs[srcs.len() - 2u].clone() }
};
@ -1100,7 +1100,7 @@ fn disassemble_extract(config: &config, _props: &TestProps,
fn count_extracted_lines(p: &Path) -> uint {
let x = File::open(&p.with_extension("ll")).read_to_end();
let x = str::from_utf8_owned(x);
let x = str::from_utf8_owned(x).unwrap();
x.lines().len()
}

View File

@ -198,7 +198,7 @@ impl<'a> FromBase64 for &'a str {
* println!("base64 output: {}", hello_str);
* let res = hello_str.from_base64();
* if res.is_ok() {
* let optBytes = str::from_utf8_owned_opt(res.unwrap());
* let optBytes = str::from_utf8_owned(res.unwrap());
* if optBytes.is_some() {
* println!("decoded from base64: {}", optBytes.unwrap());
* }

View File

@ -96,7 +96,7 @@ impl<'a> FromHex for &'a str {
* println!("{}", hello_str);
* let bytes = hello_str.from_hex().unwrap();
* println!("{:?}", bytes);
* let result_str = str::from_utf8_owned(bytes);
* let result_str = str::from_utf8_owned(bytes).unwrap();
* println!("{}", result_str);
* }
* ```

View File

@ -312,7 +312,7 @@ impl<'a> Encoder<'a> {
/// Encode the specified struct into a json str
pub fn str_encode<T:Encodable<Encoder<'a>>>(to_encode_object: &T) -> ~str {
let buff:~[u8] = Encoder::buffer_encode(to_encode_object);
str::from_utf8_owned(buff)
str::from_utf8_owned(buff).unwrap()
}
}
@ -684,7 +684,7 @@ impl Json{
pub fn to_pretty_str(&self) -> ~str {
let mut s = MemWriter::new();
self.to_pretty_writer(&mut s as &mut io::Writer);
str::from_utf8_owned(s.unwrap())
str::from_utf8_owned(s.unwrap()).unwrap()
}
}
@ -1067,7 +1067,7 @@ impl<T : Iterator<char>> Parser<T> {
/// Decodes a json value from an `&mut io::Reader`
pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, Error> {
let s = str::from_utf8_owned(rdr.read_to_end());
let s = str::from_utf8_owned(rdr.read_to_end()).unwrap();
let mut parser = Parser::new(s.chars());
parser.parse()
}
@ -1541,7 +1541,7 @@ impl to_str::ToStr for Json {
fn to_str(&self) -> ~str {
let mut s = MemWriter::new();
self.to_writer(&mut s as &mut io::Writer);
str::from_utf8_owned(s.unwrap())
str::from_utf8_owned(s.unwrap()).unwrap()
}
}
@ -1732,7 +1732,7 @@ mod tests {
let mut m = MemWriter::new();
f(&mut m as &mut io::Writer);
str::from_utf8_owned(m.unwrap())
str::from_utf8_owned(m.unwrap()).unwrap()
}
#[test]

View File

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

View File

@ -216,7 +216,7 @@ pub fn parse(file: &mut io::Reader,
}
// don't read NUL
let names_str = str::from_utf8_owned(file.read_bytes(names_bytes as uint - 1));
let names_str = str::from_utf8_owned(file.read_bytes(names_bytes as uint - 1)).unwrap();
let term_names: ~[~str] = names_str.split('|').map(|s| s.to_owned()).collect();

View File

@ -1030,7 +1030,7 @@ pub fn strftime(format: &str, tm: &Tm) -> ~str {
}
}
str::from_utf8_owned(buf)
str::from_utf8_owned(buf).unwrap()
}
#[cfg(test)]

View File

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

View File

@ -243,7 +243,7 @@ fn json_encode<'a, T:Encodable<json::Encoder<'a>>>(t: &T) -> ~str {
let mut writer = MemWriter::new();
let mut encoder = json::Encoder::new(&mut writer as &mut io::Writer);
t.encode(&mut encoder);
str::from_utf8_owned(writer.unwrap())
str::from_utf8_owned(writer.unwrap()).unwrap()
}
// FIXME(#5121)
@ -491,7 +491,7 @@ fn test() {
let subcx = cx.clone();
let pth = pth.clone();
let file_content = from_utf8_owned(File::open(&pth).read_to_end());
let file_content = from_utf8_owned(File::open(&pth).read_to_end()).unwrap();
// FIXME (#9639): This needs to handle non-utf8 paths
prep.declare_input("file", pth.as_str().unwrap(), file_content);

View File

@ -298,7 +298,7 @@ pub mod write {
if !prog.status.success() {
sess.err(format!("linking with `{}` failed: {}", cc, prog.status));
sess.note(format!("{} arguments: '{}'", cc, args.connect("' '")));
sess.note(str::from_utf8_owned(prog.error + prog.output));
sess.note(str::from_utf8_owned(prog.error + prog.output).unwrap());
sess.abort_if_errors();
}
},
@ -1007,7 +1007,7 @@ fn link_natively(sess: Session, dylib: bool, obj_filename: &Path,
if !prog.status.success() {
sess.err(format!("linking with `{}` failed: {}", cc_prog, prog.status));
sess.note(format!("{} arguments: '{}'", cc_prog, cc_args.connect("' '")));
sess.note(str::from_utf8_owned(prog.error + prog.output));
sess.note(str::from_utf8_owned(prog.error + prog.output).unwrap());
sess.abort_if_errors();
}
},

View File

@ -234,7 +234,7 @@ pub fn run_compiler(args: &[~str], demitter: @diagnostic::Emitter) {
1u => {
let ifile = matches.free[0].as_slice();
if "-" == ifile {
let src = str::from_utf8_owned(io::stdin().read_to_end());
let src = str::from_utf8_owned(io::stdin().read_to_end()).unwrap();
d::StrInput(src.to_managed())
} else {
d::FileInput(Path::new(ifile))

View File

@ -1989,5 +1989,5 @@ pub fn encoded_ty(tcx: ty::ctxt, t: ty::t) -> ~str {
abbrevs: tyencode::ac_no_abbrevs};
let mut wr = MemWriter::new();
tyencode::enc_ty(&mut wr, cx, t);
str::from_utf8_owned(wr.get_ref().to_owned())
str::from_utf8_owned(wr.get_ref().to_owned()).unwrap()
}

View File

@ -825,7 +825,7 @@ impl Liveness {
}
}
}
str::from_utf8_owned(wr.unwrap())
str::from_utf8_owned(wr.unwrap()).unwrap()
}
pub fn init_empty(&self, ln: LiveNode, succ_ln: LiveNode) {

View File

@ -427,7 +427,7 @@ impl<'a> SourceCollector<'a> {
}
}
}
let contents = str::from_utf8_owned(contents);
let contents = str::from_utf8_owned(contents).unwrap();
// Create the intermediate directories
let mut cur = self.dst.clone();

View File

@ -330,7 +330,7 @@ fn json_output(crate: clean::Crate, res: ~[plugins::PluginJson], dst: Path) {
let mut encoder = json::Encoder::new(&mut w as &mut io::Writer);
crate.encode(&mut encoder);
}
str::from_utf8_owned(w.unwrap())
str::from_utf8_owned(w.unwrap()).unwrap()
};
let crate_json = match json::from_str(crate_json_str) {
Ok(j) => j,

View File

@ -38,8 +38,8 @@ pub fn safe_git_clone(source: &Path, v: &Version, target: &Path) -> CloneResult
target.as_str().unwrap().to_owned()]);
let outp = opt_outp.expect("Failed to exec `git`");
if !outp.status.success() {
println!("{}", str::from_utf8_owned(outp.output.clone()));
println!("{}", str::from_utf8_owned(outp.error));
println!("{}", str::from_utf8_owned(outp.output.clone()).unwrap());
println!("{}", str::from_utf8_owned(outp.error).unwrap());
return DirToUse(target.clone());
}
else {
@ -54,8 +54,8 @@ pub fn safe_git_clone(source: &Path, v: &Version, target: &Path) -> CloneResult
format!("--git-dir={}", git_dir.as_str().unwrap().to_owned()),
~"checkout", format!("{}", *s)]).expect("Failed to exec `git`");
if !outp.status.success() {
println!("{}", str::from_utf8_owned(outp.output.clone()));
println!("{}", str::from_utf8_owned(outp.error));
println!("{}", str::from_utf8_owned(outp.output.clone()).unwrap());
println!("{}", str::from_utf8_owned(outp.error).unwrap());
return DirToUse(target.clone());
}
}
@ -114,8 +114,8 @@ pub fn git_clone_url(source: &str, target: &Path, v: &Version) {
target.as_str().unwrap().to_owned()]);
let outp = opt_outp.expect("Failed to exec `git`");
if !outp.status.success() {
debug!("{}", str::from_utf8_owned(outp.output.clone()));
debug!("{}", str::from_utf8_owned(outp.error));
debug!("{}", str::from_utf8_owned(outp.output.clone()).unwrap());
debug!("{}", str::from_utf8_owned(outp.error).unwrap());
cond.raise((source.to_owned(), target.clone()))
}
else {
@ -125,8 +125,8 @@ pub fn git_clone_url(source: &str, target: &Path, v: &Version) {
target);
let outp = opt_outp.expect("Failed to exec `git`");
if !outp.status.success() {
debug!("{}", str::from_utf8_owned(outp.output.clone()));
debug!("{}", str::from_utf8_owned(outp.error));
debug!("{}", str::from_utf8_owned(outp.output.clone()).unwrap());
debug!("{}", str::from_utf8_owned(outp.error).unwrap());
cond.raise((source.to_owned(), target.clone()))
}
}

View File

@ -1191,7 +1191,7 @@ fn test_info() {
let expected_info = ~"package foo"; // fill in
let workspace = create_local_package(&CrateId::new("foo"));
let output = command_line_test([~"info", ~"foo"], workspace.path());
assert_eq!(str::from_utf8_owned(output.output), expected_info);
assert_eq!(str::from_utf8_owned(output.output).unwrap(), expected_info);
}
#[test]

View File

@ -691,7 +691,7 @@ pub fn format(args: &Arguments) -> ~str {
pub unsafe fn format_unsafe(fmt: &[rt::Piece], args: &[Argument]) -> ~str {
let mut output = MemWriter::new();
write_unsafe(&mut output as &mut io::Writer, fmt, args);
return str::from_utf8_owned(output.unwrap());
return str::from_utf8_owned(output.unwrap()).unwrap();
}
impl<'a> Formatter<'a> {

View File

@ -754,7 +754,7 @@ mod test {
let mut read_buf = [0, .. 1028];
let read_str = match read_stream.read(read_buf).unwrap() {
-1|0 => fail!("shouldn't happen"),
n => str::from_utf8_owned(read_buf.slice_to(n).to_owned())
n => str::from_utf8_owned(read_buf.slice_to(n).to_owned()).unwrap()
};
assert_eq!(read_str, message.to_owned());
}

View File

@ -607,7 +607,7 @@ pub trait Reader {
/// This function will raise all the same conditions as the `read` method,
/// along with raising a condition if the input is not valid UTF-8.
fn read_to_str(&mut self) -> ~str {
match str::from_utf8_owned_opt(self.read_to_end()) {
match str::from_utf8_owned(self.read_to_end()) {
Some(s) => s,
None => {
io_error::cond.raise(standard_error(InvalidInput));
@ -1117,7 +1117,7 @@ pub trait Buffer: Reader {
/// The task will also fail if sequence of bytes leading up to
/// the newline character are not valid UTF-8.
fn read_line(&mut self) -> Option<~str> {
self.read_until('\n' as u8).map(str::from_utf8_owned)
self.read_until('\n' as u8).map(|line| str::from_utf8_owned(line).unwrap())
}
/// Create an iterator that reads a line on each iteration until EOF.

View File

@ -427,7 +427,7 @@ pub fn float_to_str_common<T:NumCast+Zero+One+Eq+Ord+NumStrConv+Float+Round+
sign: SignFormat, digits: SignificantDigits) -> (~str, bool) {
let (bytes, special) = float_to_str_bytes_common(num, radix,
negative_zero, sign, digits);
(str::from_utf8_owned(bytes), special)
(str::from_utf8_owned(bytes).unwrap(), special)
}
// Some constants for from_str_bytes_common's input validation,

View File

@ -608,7 +608,7 @@ pub fn repr_to_str<T>(t: &T) -> ~str {
let mut result = io::MemWriter::new();
write_repr(&mut result as &mut io::Writer, t);
str::from_utf8_owned(result.unwrap())
str::from_utf8_owned(result.unwrap()).unwrap()
}
#[cfg(test)]
@ -626,7 +626,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);
let s = str::from_utf8_owned(m.unwrap());
let s = str::from_utf8_owned(m.unwrap()).unwrap();
assert_eq!(s.as_slice(), e);
}

View File

@ -372,7 +372,7 @@ mod tests {
let run::ProcessOutput {status, output, error}
= run::process_output("echo", [~"hello"]).expect("failed to exec `echo`");
let output_str = str::from_utf8_owned(output);
let output_str = str::from_utf8_owned(output).unwrap();
assert!(status.success());
assert_eq!(output_str.trim().to_owned(), ~"hello");
@ -439,7 +439,7 @@ mod tests {
None => break
}
}
str::from_utf8_owned(res)
str::from_utf8_owned(res).unwrap()
}
#[test]
@ -467,7 +467,7 @@ mod tests {
.expect("failed to exec `echo`");
let run::ProcessOutput {status, output, error}
= prog.finish_with_output();
let output_str = str::from_utf8_owned(output);
let output_str = str::from_utf8_owned(output).unwrap();
assert!(status.success());
assert_eq!(output_str.trim().to_owned(), ~"hello");
@ -486,7 +486,7 @@ mod tests {
let run::ProcessOutput {status, output, error}
= prog.finish_with_output();
let output_str = str::from_utf8_owned(output);
let output_str = str::from_utf8_owned(output).unwrap();
assert!(status.success());
assert_eq!(output_str.trim().to_owned(), ~"hello");
@ -533,7 +533,7 @@ mod tests {
fn test_keep_current_working_dir() {
let mut prog = run_pwd(None);
let output = str::from_utf8_owned(prog.finish_with_output().output);
let output = str::from_utf8_owned(prog.finish_with_output().output).unwrap();
let parent_dir = os::getcwd();
let child_dir = Path::new(output.trim());
@ -551,7 +551,7 @@ mod tests {
let parent_dir = os::getcwd().dir_path();
let mut prog = run_pwd(Some(&parent_dir));
let output = str::from_utf8_owned(prog.finish_with_output().output);
let output = str::from_utf8_owned(prog.finish_with_output().output).unwrap();
let child_dir = Path::new(output.trim());
let parent_stat = parent_dir.stat();
@ -590,7 +590,7 @@ mod tests {
if running_on_valgrind() { return; }
let mut prog = run_env(None);
let output = str::from_utf8_owned(prog.finish_with_output().output);
let output = str::from_utf8_owned(prog.finish_with_output().output).unwrap();
let r = os::env();
for &(ref k, ref v) in r.iter() {
@ -604,7 +604,7 @@ mod tests {
if running_on_valgrind() { return; }
let mut prog = run_env(None);
let output = str::from_utf8_owned(prog.finish_with_output().output);
let output = str::from_utf8_owned(prog.finish_with_output().output).unwrap();
let r = os::env();
for &(ref k, ref v) in r.iter() {
@ -623,7 +623,7 @@ mod tests {
new_env.push((~"RUN_TEST_NEW_ENV", ~"123"));
let mut prog = run_env(Some(new_env));
let output = str::from_utf8_owned(prog.finish_with_output().output);
let output = str::from_utf8_owned(prog.finish_with_output().output).unwrap();
assert!(output.contains("RUN_TEST_NEW_ENV=123"));
}

View File

@ -129,26 +129,9 @@ condition! {
Section: Creating a string
*/
/// Consumes a vector of bytes to create a new utf-8 string
///
/// # Failure
///
/// Raises the `not_utf8` condition if invalid UTF-8
pub fn from_utf8_owned(vv: ~[u8]) -> ~str {
use str::not_utf8::cond;
if !is_utf8(vv) {
let first_bad_byte = *vv.iter().find(|&b| !is_utf8([*b])).unwrap();
cond.raise(format!("from_utf8: input is not UTF-8; first bad byte is {}",
first_bad_byte))
} else {
unsafe { raw::from_utf8_owned(vv) }
}
}
/// 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_opt(vv: ~[u8]) -> Option<~str> {
pub fn from_utf8_owned(vv: ~[u8]) -> Option<~str> {
if is_utf8(vv) {
Some(unsafe { raw::from_utf8_owned(vv) })
} else {
@ -3964,22 +3947,13 @@ mod tests {
#[test]
fn test_str_from_utf8_owned() {
let xs = bytes!("hello").to_owned();
assert_eq!(from_utf8_owned(xs), ~"hello");
assert_eq!(from_utf8_owned(xs), Some(~"hello"));
let xs = bytes!("ศไทย中华Việt Nam").to_owned();
assert_eq!(from_utf8_owned(xs), ~"ศไทย中华Việt Nam");
}
#[test]
fn test_str_from_utf8_owned_opt() {
let xs = bytes!("hello").to_owned();
assert_eq!(from_utf8_owned_opt(xs), Some(~"hello"));
let xs = bytes!("ศไทย中华Việt Nam").to_owned();
assert_eq!(from_utf8_owned_opt(xs), Some(~"ศไทย中华Việt Nam"));
assert_eq!(from_utf8_owned(xs), Some(~"ศไทย中华Việt Nam"));
let xs = bytes!("hello", 0xff).to_owned();
assert_eq!(from_utf8_owned_opt(xs), None);
assert_eq!(from_utf8_owned(xs), None);
}
#[test]

View File

@ -109,7 +109,7 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
}
Ok(bytes) => bytes,
};
match str::from_utf8_owned_opt(bytes) {
match str::from_utf8_owned(bytes) {
Some(src) => {
// Add this input file to the code map to make it available as
// dependency information

View File

@ -351,7 +351,7 @@ pub fn gather_comments_and_literals(span_diagnostic:
path: @str,
srdr: &mut io::Reader)
-> (~[Comment], ~[Literal]) {
let src = str::from_utf8_owned(srdr.read_to_end()).to_managed();
let src = str::from_utf8_owned(srdr.read_to_end()).unwrap().to_managed();
let cm = CodeMap::new();
let filemap = cm.new_filemap(path, src);
let rdr = lexer::new_low_level_string_reader(span_diagnostic, filemap);

View File

@ -246,7 +246,7 @@ pub fn file_to_filemap(sess: @ParseSess, path: &Path, spanopt: Option<Span>)
unreachable!()
}
};
match str::from_utf8_owned_opt(bytes) {
match str::from_utf8_owned(bytes) {
Some(s) => {
return string_to_filemap(sess, s.to_managed(),
path.as_str().unwrap().to_managed());
@ -315,7 +315,7 @@ mod test {
let mut writer = MemWriter::new();
let mut encoder = extra::json::Encoder::new(&mut writer as &mut io::Writer);
val.encode(&mut encoder);
str::from_utf8_owned(writer.unwrap())
str::from_utf8_owned(writer.unwrap()).unwrap()
}
// produce a codemap::span

View File

@ -2316,7 +2316,7 @@ pub fn print_string(s: &mut State, st: &str, style: ast::StrStyle) {
// downcasts.
unsafe fn get_mem_writer(writer: &mut ~io::Writer) -> ~str {
let (_, wr): (uint, ~MemWriter) = cast::transmute_copy(writer);
let result = str::from_utf8_owned(wr.get_ref().to_owned());
let result = str::from_utf8_owned(wr.get_ref().to_owned()).unwrap();
cast::forget(wr);
result
}

View File

@ -59,7 +59,7 @@ impl Code {
}
reverse(result);
str::from_utf8_owned(result)
str::from_utf8_owned(result).unwrap()
}
}

View File

@ -187,7 +187,7 @@ fn to_utf8(raw_sol: &List<u64>) -> ~str {
if m & 1 << i != 0 {sol[i] = '0' as u8 + id;}
}
}
std::str::from_utf8_owned(sol)
std::str::from_utf8_owned(sol).unwrap()
}
// Prints a solution in ~str form.

View File

@ -62,14 +62,14 @@ fn test_destroy_actually_kills(force: bool) {
fn process_exists(pid: libc::pid_t) -> bool {
let run::ProcessOutput {output, ..} = run::process_output("ps", [~"-p", pid.to_str()])
.expect("failed to exec `ps`");
str::from_utf8_owned(output).contains(pid.to_str())
str::from_utf8_owned(output).unwrap().contains(pid.to_str())
}
#[cfg(unix,target_os="android")]
fn process_exists(pid: libc::pid_t) -> bool {
let run::ProcessOutput {output, ..} = run::process_output("/system/bin/ps", [pid.to_str()])
.expect("failed to exec `/system/bin/ps`");
str::from_utf8_owned(output).contains(~"root")
str::from_utf8_owned(output).unwrap().contains(~"root")
}
#[cfg(windows)]

View File

@ -260,7 +260,7 @@ fn test_write() {
writeln!(w, "{foo}", foo="bar");
}
let s = str::from_utf8_owned(buf.unwrap());
let s = str::from_utf8_owned(buf.unwrap()).unwrap();
t!(s, "34helloline\nbar\n");
}
@ -284,7 +284,7 @@ fn test_format_args() {
format_args!(|args| { fmt::write(w, args) }, "test");
format_args!(|args| { fmt::write(w, args) }, "{test}", test=3);
}
let s = str::from_utf8_owned(buf.unwrap());
let s = str::from_utf8_owned(buf.unwrap()).unwrap();
t!(s, "1test3");
let s = format_args!(fmt::format, "hello {}", "world");