Skip to content

Commit 211f1ca

Browse files
committed
Deprecate str::from_utf8_owned
Use `String::from_utf8` instead [breaking-change]
1 parent 1704ebb commit 211f1ca

File tree

28 files changed

+80
-86
lines changed

28 files changed

+80
-86
lines changed

src/compiletest/procsrv.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11-
use std::str;
1211
use std::io::process::{ProcessExit, Command, Process, ProcessOutput};
1312
use std::dynamic_lib::DynamicLibrary;
1413

@@ -25,7 +24,7 @@ fn add_target_env(cmd: &mut Command, lib_path: &str, aux_path: Option<&str>) {
2524
// Add the new dylib search path var
2625
let var = DynamicLibrary::envvar();
2726
let newpath = DynamicLibrary::create_path(path.as_slice());
28-
let newpath = str::from_utf8(newpath.as_slice()).unwrap().to_string();
27+
let newpath = String::from_utf8(newpath).unwrap();
2928
cmd.env(var.to_string(), newpath);
3029
}
3130

@@ -55,8 +54,8 @@ pub fn run(lib_path: &str,
5554

5655
Some(Result {
5756
status: status,
58-
out: str::from_utf8(output.as_slice()).unwrap().to_string(),
59-
err: str::from_utf8(error.as_slice()).unwrap().to_string()
57+
out: String::from_utf8(output).unwrap(),
58+
err: String::from_utf8(error).unwrap()
6059
})
6160
},
6261
Err(..) => None

src/compiletest/runtest.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
158158
match props.pp_exact { Some(_) => 1, None => 2 };
159159

160160
let src = File::open(testfile).read_to_end().unwrap();
161-
let src = str::from_utf8(src.as_slice()).unwrap().to_string();
161+
let src = String::from_utf8(src.clone()).unwrap();
162162
let mut srcs = vec!(src);
163163

164164
let mut round = 0;
@@ -185,10 +185,10 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
185185
Some(ref file) => {
186186
let filepath = testfile.dir_path().join(file);
187187
let s = File::open(&filepath).read_to_end().unwrap();
188-
str::from_utf8(s.as_slice()).unwrap().to_string()
189-
}
190-
None => { (*srcs.get(srcs.len() - 2u)).clone() }
191-
};
188+
String::from_utf8(s).unwrap()
189+
}
190+
None => { (*srcs.get(srcs.len() - 2u)).clone() }
191+
};
192192
let mut actual = (*srcs.get(srcs.len() - 1u)).clone();
193193

194194
if props.pp_exact.is_some() {
@@ -582,8 +582,8 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path)
582582
process.wait_with_output().unwrap();
583583

584584
(status,
585-
str::from_utf8(output.as_slice()).unwrap().to_string(),
586-
str::from_utf8(error.as_slice()).unwrap().to_string())
585+
String::from_utf8(output).unwrap(),
586+
String::from_utf8(error).unwrap())
587587
},
588588
Err(e) => {
589589
fatal(format!("Failed to setup Python process for \

src/libcollections/str.rs

Lines changed: 2 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ Section: Creating a string
107107
/// let string = str::from_utf8_owned(hello_vec);
108108
/// assert_eq!(string, Ok("hello".to_string()));
109109
/// ```
110+
#[deprecated = "Replaced by `String::from_utf8`"]
110111
pub fn from_utf8_owned(vv: Vec<u8>) -> Result<String, Vec<u8>> {
111112
String::from_utf8(vv)
112113
}
@@ -139,9 +140,7 @@ pub fn from_byte(b: u8) -> String {
139140
/// assert_eq!(string.as_slice(), "b");
140141
/// ```
141142
pub fn from_char(ch: char) -> String {
142-
let mut buf = String::new();
143-
buf.push_char(ch);
144-
buf
143+
String::from_char(ch)
145144
}
146145

147146
/// Convert a vector of chars to a string
@@ -2175,19 +2174,6 @@ String::from_str("\u1111\u1171\u11b6"));
21752174
assert_eq!(from_utf8(xs), None);
21762175
}
21772176

2178-
#[test]
2179-
fn test_str_from_utf8_owned() {
2180-
let xs = Vec::from_slice(b"hello");
2181-
assert_eq!(from_utf8_owned(xs), Ok(String::from_str("hello")));
2182-
2183-
let xs = Vec::from_slice("ศไทย中华Việt Nam".as_bytes());
2184-
assert_eq!(from_utf8_owned(xs), Ok(String::from_str("ศไทย中华Việt Nam")));
2185-
2186-
let xs = Vec::from_slice(b"hello\xFF");
2187-
assert_eq!(from_utf8_owned(xs),
2188-
Err(Vec::from_slice(b"hello\xFF")));
2189-
}
2190-
21912177
#[test]
21922178
fn test_str_from_utf8_lossy() {
21932179
let xs = b"hello";

src/libcollections/string.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,14 @@ impl String {
7575
///
7676
/// Returns `Err` with the original vector if the vector contains invalid
7777
/// UTF-8.
78+
///
79+
/// # Example
80+
///
81+
/// ```rust
82+
/// let hello_vec = vec![104, 101, 108, 108, 111];
83+
/// let string = String::from_utf8(hello_vec);
84+
/// assert_eq!(string, Ok("hello".to_string()));
85+
/// ```
7886
#[inline]
7987
pub fn from_utf8(vec: Vec<u8>) -> Result<String, Vec<u8>> {
8088
if str::is_utf8(vec.as_slice()) {
@@ -391,6 +399,19 @@ mod tests {
391399
});
392400
}
393401

402+
#[test]
403+
fn test_str_from_utf8() {
404+
let xs = Vec::from_slice(b"hello");
405+
assert_eq!(String::from_utf8(xs), Ok("hello".to_string()));
406+
407+
let xs = Vec::from_slice("ศไทย中华Việt Nam".as_bytes());
408+
assert_eq!(String::from_utf8(xs), Ok("ศไทย中华Việt Nam".to_string()));
409+
410+
let xs = Vec::from_slice(b"hello\xFF");
411+
assert_eq!(String::from_utf8(xs),
412+
Err(Vec::from_slice(b"hello\xFF")));
413+
}
414+
394415
#[test]
395416
fn test_push_bytes() {
396417
let mut s = String::from_str("ABC");

src/libdebug/repr.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -575,7 +575,6 @@ struct P {a: int, b: f64}
575575

576576
#[test]
577577
fn test_repr() {
578-
use std::str;
579578
use std::io::stdio::println;
580579
use std::char::is_alphabetic;
581580
use std::mem::swap;
@@ -584,7 +583,7 @@ fn test_repr() {
584583
fn exact_test<T>(t: &T, e:&str) {
585584
let mut m = io::MemWriter::new();
586585
write_repr(&mut m as &mut io::Writer, t).unwrap();
587-
let s = str::from_utf8(m.unwrap().as_slice()).unwrap().to_string();
586+
let s = String::from_utf8(m.unwrap()).unwrap();
588587
assert_eq!(s.as_slice(), e);
589588
}
590589

src/libregex/test/bench.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ fn gen_text(n: uint) -> String {
163163
*b = '\n' as u8
164164
}
165165
}
166-
str::from_utf8(bytes.as_slice()).unwrap().to_string()
166+
String::from_utf8(bytes).unwrap()
167167
}
168168

169169
throughput!(easy0_32, easy0(), 32)

src/librustc/back/link.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -380,8 +380,7 @@ pub mod write {
380380
sess.note(format!("{}", &cmd).as_slice());
381381
let mut note = prog.error.clone();
382382
note.push_all(prog.output.as_slice());
383-
sess.note(str::from_utf8(note.as_slice()).unwrap()
384-
.as_slice());
383+
sess.note(str::from_utf8(note.as_slice()).unwrap());
385384
sess.abort_if_errors();
386385
}
387386
},
@@ -1177,8 +1176,7 @@ fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool,
11771176
sess.note(format!("{}", &cmd).as_slice());
11781177
let mut output = prog.error.clone();
11791178
output.push_all(prog.output.as_slice());
1180-
sess.note(str::from_utf8(output.as_slice()).unwrap()
1181-
.as_slice());
1179+
sess.note(str::from_utf8(output.as_slice()).unwrap());
11821180
sess.abort_if_errors();
11831181
}
11841182
},

src/librustc/driver/mod.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,7 @@ fn run_compiler(args: &[String]) {
8282
let ifile = matches.free.get(0).as_slice();
8383
if ifile == "-" {
8484
let contents = io::stdin().read_to_end().unwrap();
85-
let src = str::from_utf8(contents.as_slice()).unwrap()
86-
.to_string();
85+
let src = String::from_utf8(contents).unwrap();
8786
(StrInput(src), None)
8887
} else {
8988
(FileInput(Path::new(ifile)), Some(Path::new(ifile)))

src/librustc/metadata/encoder.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1922,5 +1922,5 @@ pub fn encoded_ty(tcx: &ty::ctxt, t: ty::t) -> String {
19221922
tcx: tcx,
19231923
abbrevs: &RefCell::new(HashMap::new())
19241924
}, t);
1925-
str::from_utf8_owned(Vec::from_slice(wr.get_ref())).unwrap().to_string()
1925+
str::from_utf8(wr.get_ref()).unwrap().to_string()
19261926
}

src/librustdoc/html/render.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -460,7 +460,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::IoResult<String>
460460

461461
try!(write!(&mut w, "]}};"));
462462

463-
Ok(str::from_utf8(w.unwrap().as_slice()).unwrap().to_string())
463+
Ok(String::from_utf8(w.unwrap()).unwrap())
464464
}
465465

466466
fn write_shared(cx: &Context,

src/librustdoc/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -429,7 +429,7 @@ fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
429429
let mut encoder = json::Encoder::new(&mut w as &mut io::Writer);
430430
krate.encode(&mut encoder).unwrap();
431431
}
432-
str::from_utf8_owned(w.unwrap()).unwrap()
432+
String::from_utf8(w.unwrap()).unwrap()
433433
};
434434
let crate_json = match json::from_str(crate_json_str.as_slice()) {
435435
Ok(j) => j,

src/libserialize/base64.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ impl<'a> ToBase64 for &'a [u8] {
146146
}
147147

148148
unsafe {
149-
str::raw::from_utf8(v.as_slice()).to_string()
149+
str::raw::from_utf8_owned(v)
150150
}
151151
}
152152
}

src/libserialize/hex.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ impl<'a> ToHex for &'a [u8] {
4545
}
4646

4747
unsafe {
48-
str::raw::from_utf8(v.as_slice()).to_string()
48+
str::raw::from_utf8_owned(v)
4949
}
5050
}
5151
}

src/libserialize/json.rs

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,7 @@ pub fn decode<T: ::Decodable<Decoder, DecoderError>>(s: &str) -> DecodeResult<T>
240240
/// Shortcut function to encode a `T` into a JSON `String`
241241
pub fn encode<'a, T: Encodable<Encoder<'a>, io::IoError>>(object: &T) -> String {
242242
let buff = Encoder::buffer_encode(object);
243-
str::from_utf8_owned(buff).unwrap()
243+
String::from_utf8(buff).unwrap()
244244
}
245245

246246
impl fmt::Show for ErrorCode {
@@ -517,8 +517,7 @@ impl<'a> ::Encoder<io::IoError> for Encoder<'a> {
517517
let mut check_encoder = Encoder::new(&mut buf);
518518
try!(f(transmute(&mut check_encoder)));
519519
}
520-
let out = str::from_utf8_owned(buf.unwrap()).unwrap();
521-
let out = out.as_slice();
520+
let out = str::from_utf8(buf.get_ref()).unwrap();
522521
let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
523522
if needs_wrapping { try!(write!(self.writer, "\"")); }
524523
try!(f(self));
@@ -762,8 +761,7 @@ impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> {
762761
let mut check_encoder = PrettyEncoder::new(&mut buf);
763762
try!(f(transmute(&mut check_encoder)));
764763
}
765-
let out = str::from_utf8_owned(buf.unwrap()).unwrap();
766-
let out = out.as_slice();
764+
let out = str::from_utf8(buf.get_ref()).unwrap();
767765
let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
768766
if needs_wrapping { try!(write!(self.writer, "\"")); }
769767
try!(f(self));
@@ -810,7 +808,7 @@ impl Json {
810808
pub fn to_pretty_str(&self) -> String {
811809
let mut s = MemWriter::new();
812810
self.to_pretty_writer(&mut s as &mut io::Writer).unwrap();
813-
str::from_utf8_owned(s.unwrap()).unwrap()
811+
String::from_utf8(s.unwrap()).unwrap()
814812
}
815813

816814
/// 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> {
17281726
/// Decodes a json value from an `&mut io::Reader`
17291727
pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, BuilderError> {
17301728
let contents = match rdr.read_to_end() {
1731-
Ok(c) => c,
1729+
Ok(c) => c,
17321730
Err(e) => return Err(io_error_to_error(e))
17331731
};
1734-
let s = match str::from_utf8_owned(contents) {
1735-
Ok(s) => s,
1736-
_ => return Err(SyntaxError(NotUtf8, 0, 0))
1732+
let s = match str::from_utf8(contents.as_slice()) {
1733+
Some(s) => s,
1734+
_ => return Err(SyntaxError(NotUtf8, 0, 0))
17371735
};
1738-
let mut builder = Builder::new(s.as_slice().chars());
1736+
let mut builder = Builder::new(s.chars());
17391737
builder.build()
17401738
}
17411739

src/libstd/ascii.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -438,7 +438,7 @@ unsafe fn str_map_bytes(string: String, map: &'static [u8]) -> String {
438438
*b = map[*b as uint];
439439
}
440440

441-
String::from_str(str::from_utf8(bytes.as_slice()).unwrap())
441+
String::from_utf8(bytes).unwrap()
442442
}
443443

444444
#[inline]

src/libstd/fmt.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -464,7 +464,7 @@ pub use core::fmt::{secret_pointer};
464464
pub fn format(args: &Arguments) -> string::String{
465465
let mut output = io::MemWriter::new();
466466
let _ = write!(&mut output, "{}", args);
467-
str::from_utf8(output.unwrap().as_slice()).unwrap().into_string()
467+
String::from_utf8(output.unwrap()).unwrap()
468468
}
469469

470470
impl<'a> Writer for Formatter<'a> {

src/libstd/io/fs.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -999,9 +999,9 @@ mod test {
999999
let mut read_buf = [0, .. 1028];
10001000
let read_str = match check!(read_stream.read(read_buf)) {
10011001
-1|0 => fail!("shouldn't happen"),
1002-
n => str::from_utf8(read_buf.slice_to(n)).unwrap().to_owned()
1002+
n => str::from_utf8(read_buf.slice_to(n)).unwrap().to_string()
10031003
};
1004-
assert_eq!(read_str, message.to_owned());
1004+
assert_eq!(read_str.as_slice(), message);
10051005
}
10061006
check!(unlink(filename));
10071007
})

src/libstd/io/mod.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -705,9 +705,9 @@ pub trait Reader {
705705
/// UTF-8 bytes.
706706
fn read_to_string(&mut self) -> IoResult<String> {
707707
self.read_to_end().and_then(|s| {
708-
match str::from_utf8(s.as_slice()) {
709-
Some(s) => Ok(String::from_str(s)),
710-
None => Err(standard_error(InvalidInput)),
708+
match String::from_utf8(s) {
709+
Ok(s) => Ok(s),
710+
Err(_) => Err(standard_error(InvalidInput)),
711711
}
712712
})
713713
}
@@ -1440,9 +1440,9 @@ pub trait Buffer: Reader {
14401440
/// valid UTF-8 sequence of bytes.
14411441
fn read_line(&mut self) -> IoResult<String> {
14421442
self.read_until('\n' as u8).and_then(|line|
1443-
match str::from_utf8(line.as_slice()) {
1444-
Some(s) => Ok(String::from_str(s)),
1445-
None => Err(standard_error(InvalidInput)),
1443+
match String::from_utf8(line) {
1444+
Ok(s) => Ok(s),
1445+
Err(_) => Err(standard_error(InvalidInput)),
14461446
}
14471447
)
14481448
}

src/libstd/io/process.rs

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -813,8 +813,7 @@ mod tests {
813813
use os;
814814
let prog = pwd_cmd().spawn().unwrap();
815815

816-
let output = str::from_utf8(prog.wait_with_output().unwrap()
817-
.output.as_slice()).unwrap().to_string();
816+
let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
818817
let parent_dir = os::getcwd();
819818
let child_dir = Path::new(output.as_slice().trim());
820819

@@ -832,8 +831,7 @@ mod tests {
832831
let parent_dir = os::getcwd().dir_path();
833832
let prog = pwd_cmd().cwd(&parent_dir).spawn().unwrap();
834833

835-
let output = str::from_utf8(prog.wait_with_output().unwrap()
836-
.output.as_slice()).unwrap().to_string();
834+
let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
837835
let child_dir = Path::new(output.as_slice().trim().into_string());
838836

839837
let parent_stat = parent_dir.stat().unwrap();
@@ -867,8 +865,7 @@ mod tests {
867865
if running_on_valgrind() { return; }
868866

869867
let prog = env_cmd().spawn().unwrap();
870-
let output = str::from_utf8(prog.wait_with_output().unwrap()
871-
.output.as_slice()).unwrap().to_string();
868+
let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
872869

873870
let r = os::env();
874871
for &(ref k, ref v) in r.iter() {
@@ -884,9 +881,7 @@ mod tests {
884881
if running_on_valgrind() { return; }
885882

886883
let mut prog = env_cmd().spawn().unwrap();
887-
let output = str::from_utf8(prog.wait_with_output()
888-
.unwrap().output.as_slice())
889-
.unwrap().to_string();
884+
let output = String::from_utf8(prog.wait_with_output().unwrap().output).unwrap();
890885

891886
let r = os::env();
892887
for &(ref k, ref v) in r.iter() {

src/libstd/rt/backtrace.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -997,7 +997,7 @@ mod test {
997997
macro_rules! t( ($a:expr, $b:expr) => ({
998998
let mut m = MemWriter::new();
999999
super::demangle(&mut m, $a).unwrap();
1000-
assert_eq!(str::from_utf8(m.unwrap().as_slice()).unwrap().to_owned(), $b.to_owned());
1000+
assert_eq!(String::from_utf8(m.unwrap()).unwrap(), $b.to_string());
10011001
}) )
10021002

10031003
#[test]

0 commit comments

Comments
 (0)