diff --git a/src/compiletest/compiletest.rs b/src/compiletest/compiletest.rs index 01c4e99b77c..1ee5917ac9c 100644 --- a/src/compiletest/compiletest.rs +++ b/src/compiletest/compiletest.rs @@ -20,6 +20,8 @@ #![feature(std_misc)] #![feature(test)] #![feature(path_ext)] +#![feature(convert)] +#![feature(str_char)] #![deny(warnings)] @@ -115,7 +117,7 @@ pub fn parse_config(args: Vec ) -> Config { fn opt_path(m: &getopts::Matches, nm: &str) -> PathBuf { match m.opt_str(nm) { - Some(s) => PathBuf::new(&s), + Some(s) => PathBuf::from(&s), None => panic!("no option (=path) found for {}", nm), } } @@ -130,10 +132,10 @@ pub fn parse_config(args: Vec ) -> Config { compile_lib_path: matches.opt_str("compile-lib-path").unwrap(), run_lib_path: matches.opt_str("run-lib-path").unwrap(), rustc_path: opt_path(matches, "rustc-path"), - clang_path: matches.opt_str("clang-path").map(|s| PathBuf::new(&s)), + clang_path: matches.opt_str("clang-path").map(|s| PathBuf::from(&s)), valgrind_path: matches.opt_str("valgrind-path"), force_valgrind: matches.opt_present("force-valgrind"), - llvm_bin_path: matches.opt_str("llvm-bin-path").map(|s| PathBuf::new(&s)), + llvm_bin_path: matches.opt_str("llvm-bin-path").map(|s| PathBuf::from(&s)), src_base: opt_path(matches, "src-base"), build_base: opt_path(matches, "build-base"), aux_base: opt_path(matches, "aux-base"), @@ -141,7 +143,7 @@ pub fn parse_config(args: Vec ) -> Config { mode: matches.opt_str("mode").unwrap().parse().ok().expect("invalid mode"), run_ignored: matches.opt_present("ignored"), filter: filter, - logfile: matches.opt_str("logfile").map(|s| PathBuf::new(&s)), + logfile: matches.opt_str("logfile").map(|s| PathBuf::from(&s)), runtool: matches.opt_str("runtool"), host_rustcflags: matches.opt_str("host-rustcflags"), target_rustcflags: matches.opt_str("target-rustcflags"), diff --git a/src/compiletest/header.rs b/src/compiletest/header.rs index 29123173f5b..e1ad66c69e4 100644 --- a/src/compiletest/header.rs +++ b/src/compiletest/header.rs @@ -328,10 +328,10 @@ fn parse_exec_env(line: &str) -> Option<(String, String)> { fn parse_pp_exact(line: &str, testfile: &Path) -> Option { match parse_name_value_directive(line, "pp-exact") { - Some(s) => Some(PathBuf::new(&s)), + Some(s) => Some(PathBuf::from(&s)), None => { if parse_name_directive(line, "pp-exact") { - testfile.file_name().map(|s| PathBuf::new(s)) + testfile.file_name().map(|s| PathBuf::from(s)) } else { None } diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index a754bd950f7..319248cb810 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -1440,7 +1440,7 @@ fn aux_output_dir_name(config: &Config, testfile: &Path) -> PathBuf { } fn output_testname(testfile: &Path) -> PathBuf { - PathBuf::new(testfile.file_stem().unwrap()) + PathBuf::from(testfile.file_stem().unwrap()) } fn output_base_name(config: &Config, testfile: &Path) -> PathBuf { diff --git a/src/libcollections/borrow.rs b/src/libcollections/borrow.rs index 4bedbdeb368..88d59f699d1 100644 --- a/src/libcollections/borrow.rs +++ b/src/libcollections/borrow.rs @@ -14,6 +14,7 @@ use core::clone::Clone; use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; +use core::convert::AsRef; use core::hash::{Hash, Hasher}; use core::marker::Sized; use core::ops::Deref; @@ -291,10 +292,9 @@ impl<'a, B: ?Sized> Hash for Cow<'a, B> where B: Hash + ToOwned } /// Trait for moving into a `Cow` -#[stable(feature = "rust1", since = "1.0.0")] +#[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`")] pub trait IntoCow<'a, B: ?Sized> where B: ToOwned { /// Moves `self` into `Cow` - #[stable(feature = "rust1", since = "1.0.0")] fn into_cow(self) -> Cow<'a, B>; } @@ -304,3 +304,10 @@ impl<'a, B: ?Sized> IntoCow<'a, B> for Cow<'a, B> where B: ToOwned { self } } + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a, T: Clone> AsRef for Cow<'a, T> { + fn as_ref(&self) -> &T { + self + } +} diff --git a/src/libcollections/lib.rs b/src/libcollections/lib.rs index c4a01496763..156c90f1e84 100644 --- a/src/libcollections/lib.rs +++ b/src/libcollections/lib.rs @@ -36,6 +36,7 @@ #![feature(unsafe_no_drop_flag)] #![feature(step_by)] #![feature(str_char)] +#![feature(convert)] #![cfg_attr(test, feature(rand, rustc_private, test))] #![cfg_attr(test, allow(deprecated))] // rand diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index 45864153dd7..0a0307aef32 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -88,6 +88,7 @@ #![stable(feature = "rust1", since = "1.0.0")] use alloc::boxed::Box; +use core::convert::AsRef; use core::clone::Clone; use core::cmp::Ordering::{self, Greater, Less}; use core::cmp::{self, Ord, PartialEq}; @@ -1088,23 +1089,23 @@ pub trait SliceConcatExt { fn connect(&self, sep: &T) -> U; } -impl> SliceConcatExt> for [V] { +impl> SliceConcatExt> for [V] { fn concat(&self) -> Vec { - let size = self.iter().fold(0, |acc, v| acc + v.as_slice().len()); + let size = self.iter().fold(0, |acc, v| acc + v.as_ref().len()); let mut result = Vec::with_capacity(size); for v in self { - result.push_all(v.as_slice()) + result.push_all(v.as_ref()) } result } fn connect(&self, sep: &T) -> Vec { - let size = self.iter().fold(0, |acc, v| acc + v.as_slice().len()); + let size = self.iter().fold(0, |acc, v| acc + v.as_ref().len()); let mut result = Vec::with_capacity(size + self.len()); let mut first = true; for v in self { if first { first = false } else { result.push(sep.clone()) } - result.push_all(v.as_slice()) + result.push_all(v.as_ref()) } result } diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index 3a289e4ef37..c014ddc069d 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -61,10 +61,10 @@ use core::iter::AdditiveIterator; use core::iter::{Iterator, IteratorExt, Extend}; use core::option::Option::{self, Some, None}; use core::result::Result; -use core::slice::AsSlice; use core::str as core_str; use unicode::str::{UnicodeStr, Utf16Encoder}; +use core::convert::AsRef; use vec_deque::VecDeque; use borrow::{Borrow, ToOwned}; use string::String; @@ -86,51 +86,47 @@ pub use core::str::{Searcher, ReverseSearcher, DoubleEndedSearcher, SearchStep}; Section: Creating a string */ -impl SliceConcatExt for [S] { +impl> SliceConcatExt for [S] { fn concat(&self) -> String { - let s = self.as_slice(); - - if s.is_empty() { + if self.is_empty() { return String::new(); } // `len` calculation may overflow but push_str will check boundaries - let len = s.iter().map(|s| s.as_slice().len()).sum(); + let len = self.iter().map(|s| s.as_ref().len()).sum(); let mut result = String::with_capacity(len); - for s in s { - result.push_str(s.as_slice()) + for s in self { + result.push_str(s.as_ref()) } result } fn connect(&self, sep: &str) -> String { - let s = self.as_slice(); - - if s.is_empty() { + if self.is_empty() { return String::new(); } // concat is faster if sep.is_empty() { - return s.concat(); + return self.concat(); } // this is wrong without the guarantee that `self` is non-empty // `len` calculation may overflow but push_str but will check boundaries - let len = sep.len() * (s.len() - 1) - + s.iter().map(|s| s.as_slice().len()).sum(); + let len = sep.len() * (self.len() - 1) + + self.iter().map(|s| s.as_ref().len()).sum(); let mut result = String::with_capacity(len); let mut first = true; - for s in s { + for s in self { if first { first = false; } else { result.push_str(sep); } - result.push_str(s.as_slice()); + result.push_str(s.as_ref()); } result } diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index cd6f27bf65f..6463949ac8a 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -814,6 +814,7 @@ impl<'a, 'b> PartialEq> for &'b str { } #[unstable(feature = "collections", reason = "waiting on Str stabilization")] +#[allow(deprecated)] impl Str for String { #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -973,6 +974,27 @@ impl ToString for T { } } +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef for String { + fn as_ref(&self) -> &str { + self + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a> From<&'a str> for String { + fn from(s: &'a str) -> String { + s.to_string() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Into> for String { + fn into(self) -> Vec { + self.into_bytes() + } +} + #[stable(feature = "rust1", since = "1.0.0")] impl IntoCow<'static, str> for String { #[inline] @@ -989,6 +1011,7 @@ impl<'a> IntoCow<'a, str> for &'a str { } } +#[allow(deprecated)] impl<'a> Str for Cow<'a, str> { #[inline] fn as_slice<'b>(&'b self) -> &'b str { diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index b0e8dc7d0b6..85833c34049 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -1369,7 +1369,7 @@ impl ops::Index for Vec { type Output = [T]; #[inline] fn index(&self, _index: &ops::RangeFull) -> &[T] { - self.as_slice() + self } } @@ -1406,7 +1406,13 @@ impl ops::IndexMut for Vec { impl ops::Deref for Vec { type Target = [T]; - fn deref(&self) -> &[T] { self.as_slice() } + fn deref(&self) -> &[T] { + unsafe { + let p = *self.ptr; + assume(p != 0 as *mut T); + slice::from_raw_parts(p, self.len) + } + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -1548,6 +1554,7 @@ impl Ord for Vec { } } +#[allow(deprecated)] impl AsSlice for Vec { /// Returns a slice into `self`. /// @@ -1562,11 +1569,7 @@ impl AsSlice for Vec { #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn as_slice(&self) -> &[T] { - unsafe { - let p = *self.ptr; - assume(p != 0 as *mut T); - slice::from_raw_parts(p, self.len) - } + self } } @@ -1614,6 +1617,41 @@ impl fmt::Debug for Vec { } } +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef> for Vec { + fn as_ref(&self) -> &Vec { + self + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Into> for Vec { + fn into(self) -> Vec { + self + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef<[T]> for Vec { + fn as_ref(&self) -> &[T] { + self + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a, T: Clone> From<&'a [T]> for Vec { + fn from(s: &'a [T]) -> Vec { + s.to_vec() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a> From<&'a str> for Vec { + fn from(s: &'a str) -> Vec { + s.as_bytes().to_vec() + } +} + //////////////////////////////////////////////////////////////////////////////// // Clone-on-write //////////////////////////////////////////////////////////////////////////////// diff --git a/src/libcore/convert.rs b/src/libcore/convert.rs new file mode 100644 index 00000000000..65a226d37cb --- /dev/null +++ b/src/libcore/convert.rs @@ -0,0 +1,113 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Traits for conversions between types. +//! +//! The traits in this module provide a general way to talk about +//! conversions from one type to another. They follow the standard +//! Rust conventions of `as`/`to`/`into`/`from`. + +#![unstable(feature = "convert", + reason = "recently added, experimental traits")] + +use marker::Sized; + +/// A cheap, reference-to-reference conversion. +pub trait AsRef { + /// Perform the conversion. + fn as_ref(&self) -> &T; +} + +/// A cheap, mutable reference-to-mutable reference conversion. +pub trait AsMut { + /// Perform the conversion. + fn as_mut(&mut self) -> &mut T; +} + +/// A conversion that consumes `self`, which may or may not be +/// expensive. +pub trait Into: Sized { + /// Perform the conversion. + fn into(self) -> T; +} + +/// Construct `Self` via a conversion. +pub trait From { + /// Perform the conversion. + fn from(T) -> Self; +} + +//////////////////////////////////////////////////////////////////////////////// +// GENERIC IMPLS +//////////////////////////////////////////////////////////////////////////////// + +// As implies Into +impl<'a, T: ?Sized, U: ?Sized> Into<&'a U> for &'a T where T: AsRef { + fn into(self) -> &'a U { + self.as_ref() + } +} + +// As lifts over & +impl<'a, T: ?Sized, U: ?Sized> AsRef for &'a T where T: AsRef { + fn as_ref(&self) -> &U { + >::as_ref(*self) + } +} + +// As lifts over &mut +impl<'a, T: ?Sized, U: ?Sized> AsRef for &'a mut T where T: AsRef { + fn as_ref(&self) -> &U { + >::as_ref(*self) + } +} + +// AsMut implies Into +impl<'a, T: ?Sized, U: ?Sized> Into<&'a mut U> for &'a mut T where T: AsMut { + fn into(self) -> &'a mut U { + (*self).as_mut() + } +} + +// AsMut lifts over &mut +impl<'a, T: ?Sized, U: ?Sized> AsMut for &'a mut T where T: AsMut { + fn as_mut(&mut self) -> &mut U { + (*self).as_mut() + } +} + +// From implies Into +impl Into for T where U: From { + fn into(self) -> U { + U::from(self) + } +} + +//////////////////////////////////////////////////////////////////////////////// +// CONCRETE IMPLS +//////////////////////////////////////////////////////////////////////////////// + +impl AsRef<[T]> for [T] { + fn as_ref(&self) -> &[T] { + self + } +} + +impl AsMut<[T]> for [T] { + fn as_mut(&mut self) -> &mut [T] { + self + } +} + +impl AsRef for str { + fn as_ref(&self) -> &str { + self + } +} diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index 29cc11d5a60..e31542c183a 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -125,6 +125,7 @@ pub mod ops; pub mod cmp; pub mod clone; pub mod default; +pub mod convert; /* Core types and methods on primitives */ diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 455c68d4319..4a1e24c1f40 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -154,6 +154,7 @@ use mem; use ops::{Deref, FnOnce}; use result::Result::{Ok, Err}; use result::Result; +#[allow(deprecated)] use slice::AsSlice; use slice; @@ -701,6 +702,19 @@ impl Option { pub fn take(&mut self) -> Option { mem::replace(self, None) } + + /// Convert from `Option` to `&[T]` (without copying) + #[inline] + #[unstable(feature = "as_slice", since = "unsure of the utility here")] + pub fn as_slice<'a>(&'a self) -> &'a [T] { + match *self { + Some(ref x) => slice::ref_slice(x), + None => { + let result: &[_] = &[]; + result + } + } + } } impl<'a, T: Clone, D: Deref> Option { @@ -752,6 +766,9 @@ impl Option { #[unstable(feature = "core", reason = "waiting on the stability of the trait itself")] +#[deprecated(since = "1.0.0", + reason = "use the inherent method instead")] +#[allow(deprecated)] impl AsSlice for Option { /// Convert from `Option` to `&[T]` (without copying) #[inline] diff --git a/src/libcore/prelude.rs b/src/libcore/prelude.rs index 4bf7f85284c..424829939b9 100644 --- a/src/libcore/prelude.rs +++ b/src/libcore/prelude.rs @@ -36,6 +36,7 @@ pub use mem::drop; pub use char::CharExt; pub use clone::Clone; pub use cmp::{PartialEq, PartialOrd, Eq, Ord}; +pub use convert::{AsRef, AsMut, Into, From}; pub use iter::{Extend, IteratorExt}; pub use iter::{Iterator, DoubleEndedIterator}; pub use iter::{ExactSizeIterator}; diff --git a/src/libcore/result.rs b/src/libcore/result.rs index bc8d53e2a57..4b3cda46c1d 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -240,6 +240,7 @@ use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator, ExactSizeIterator, IntoIterator}; use ops::{FnMut, FnOnce}; use option::Option::{self, None, Some}; +#[allow(deprecated)] use slice::AsSlice; use slice; @@ -408,6 +409,20 @@ impl Result { } } + /// Convert from `Result` to `&[T]` (without copying) + #[inline] + #[unstable(feature = "as_slice", since = "unsure of the utility here")] + pub fn as_slice(&self) -> &[T] { + match *self { + Ok(ref x) => slice::ref_slice(x), + Err(_) => { + // work around lack of implicit coercion from fixed-size array to slice + let emp: &[_] = &[]; + emp + } + } + } + /// Convert from `Result` to `&mut [T]` (without copying) /// /// ``` @@ -788,10 +803,14 @@ impl Result { // Trait implementations ///////////////////////////////////////////////////////////////////////////// +#[unstable(feature = "core", + reason = "waiting on the stability of the trait itself")] +#[deprecated(since = "1.0.0", + reason = "use inherent method instead")] +#[allow(deprecated)] impl AsSlice for Result { /// Convert from `Result` to `&[T]` (without copying) #[inline] - #[stable(feature = "rust1", since = "1.0.0")] fn as_slice<'a>(&'a self) -> &'a [T] { match *self { Ok(ref x) => slice::ref_slice(x), diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index 907b2eba80c..e7535ae1d17 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -596,24 +596,29 @@ impl ops::IndexMut for [T] { /// Data that is viewable as a slice. #[unstable(feature = "core", reason = "will be replaced by slice syntax")] +#[deprecated(since = "1.0.0", + reason = "use std::convert::AsRef<[T]> instead")] pub trait AsSlice { /// Work with `self` as a slice. fn as_slice<'a>(&'a self) -> &'a [T]; } #[unstable(feature = "core", reason = "trait is experimental")] +#[allow(deprecated)] impl AsSlice for [T] { #[inline(always)] fn as_slice<'a>(&'a self) -> &'a [T] { self } } #[unstable(feature = "core", reason = "trait is experimental")] +#[allow(deprecated)] impl<'a, T, U: ?Sized + AsSlice> AsSlice for &'a U { #[inline(always)] fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) } } #[unstable(feature = "core", reason = "trait is experimental")] +#[allow(deprecated)] impl<'a, T, U: ?Sized + AsSlice> AsSlice for &'a mut U { #[inline(always)] fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) } diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index e8181395b5c..e31aebbd74e 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -1275,16 +1275,20 @@ mod traits { reason = "Instead of taking this bound generically, this trait will be \ replaced with one of slicing syntax (&foo[..]), deref coercions, or \ a more generic conversion trait")] +#[deprecated(since = "1.0.0", + reason = "use std::convert::AsRef instead")] pub trait Str { /// Work with `self` as a slice. fn as_slice<'a>(&'a self) -> &'a str; } +#[allow(deprecated)] impl Str for str { #[inline] fn as_slice<'a>(&'a self) -> &'a str { self } } +#[allow(deprecated)] impl<'a, S: ?Sized> Str for &'a S where S: Str { #[inline] fn as_slice(&self) -> &str { Str::as_slice(*self) } diff --git a/src/libgraphviz/lib.rs b/src/libgraphviz/lib.rs index 0e080459344..6d95d5e0724 100644 --- a/src/libgraphviz/lib.rs +++ b/src/libgraphviz/lib.rs @@ -280,6 +280,7 @@ html_root_url = "http://doc.rust-lang.org/nightly/")] #![feature(int_uint)] #![feature(collections)] +#![feature(into_cow)] use self::LabelText::*; diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs index 97ed391fdfc..793eff6a9da 100644 --- a/src/librustc/lib.rs +++ b/src/librustc/lib.rs @@ -43,6 +43,8 @@ #![feature(path_ext)] #![feature(str_words)] #![feature(str_char)] +#![feature(convert)] +#![feature(into_cow)] #![cfg_attr(test, feature(test))] extern crate arena; diff --git a/src/librustc/metadata/cstore.rs b/src/librustc/metadata/cstore.rs index 47ec31c0f1a..dc9d1e11e8e 100644 --- a/src/librustc/metadata/cstore.rs +++ b/src/librustc/metadata/cstore.rs @@ -243,7 +243,7 @@ impl crate_metadata { impl MetadataBlob { pub fn as_slice<'a>(&'a self) -> &'a [u8] { let slice = match *self { - MetadataVec(ref vec) => vec.as_slice(), + MetadataVec(ref vec) => &vec[..], MetadataArchive(ref ar) => ar.as_slice(), }; if slice.len() < 4 { diff --git a/src/librustc/metadata/filesearch.rs b/src/librustc/metadata/filesearch.rs index 22a4a6fc978..284e76b328a 100644 --- a/src/librustc/metadata/filesearch.rs +++ b/src/librustc/metadata/filesearch.rs @@ -156,7 +156,7 @@ impl<'a> FileSearch<'a> { // Returns a list of directories where target-specific tool binaries are located. pub fn get_tools_search_paths(&self) -> Vec { - let mut p = PathBuf::new(self.sysroot); + let mut p = PathBuf::from(self.sysroot); p.push(&find_libdir(self.sysroot)); p.push(&rustlibdir()); p.push(&self.triple); @@ -166,7 +166,7 @@ impl<'a> FileSearch<'a> { } pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> PathBuf { - let mut p = PathBuf::new(&find_libdir(sysroot)); + let mut p = PathBuf::from(&find_libdir(sysroot)); assert!(p.is_relative()); p.push(&rustlibdir()); p.push(target_triple); @@ -224,7 +224,7 @@ pub fn rust_path() -> Vec { Some(env_path) => { let env_path_components = env_path.split(PATH_ENTRY_SEPARATOR); - env_path_components.map(|s| PathBuf::new(s)).collect() + env_path_components.map(|s| PathBuf::from(s)).collect() } None => Vec::new() }; diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index e466dc8a3a0..7854db81146 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -628,7 +628,7 @@ impl<'a> Context<'a> { let mut rlibs = HashMap::new(); let mut dylibs = HashMap::new(); { - let locs = locs.iter().map(|l| PathBuf::new(&l[..])).filter(|loc| { + let locs = locs.iter().map(|l| PathBuf::from(l)).filter(|loc| { if !loc.exists() { sess.err(&format!("extern location for {} does not exist: {}", self.crate_name, loc.display())); diff --git a/src/librustc/middle/traits/select.rs b/src/librustc/middle/traits/select.rs index 7dfbccea0dc..882caecb382 100644 --- a/src/librustc/middle/traits/select.rs +++ b/src/librustc/middle/traits/select.rs @@ -1762,7 +1762,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { match obligations { Ok(mut obls) => { - obls.push_all(normalized.obligations.as_slice()); + obls.push_all(&normalized.obligations); obls }, Err(ErrorReported) => Vec::new() diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index e368a669133..a7c67a08631 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -907,7 +907,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { let cg = build_codegen_options(matches); - let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::new(&m)); + let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m)); let target = matches.opt_str("target").unwrap_or( host_triple().to_string()); let opt_level = { diff --git a/src/librustc/session/search_paths.rs b/src/librustc/session/search_paths.rs index 3c5d9744505..3dc31f9524e 100644 --- a/src/librustc/session/search_paths.rs +++ b/src/librustc/session/search_paths.rs @@ -54,7 +54,7 @@ impl SearchPaths { if path.is_empty() { early_error("empty search path given via `-L`"); } - self.paths.push((kind, PathBuf::new(path))); + self.paths.push((kind, PathBuf::from(path))); } pub fn iter(&self, kind: PathKind) -> Iter { diff --git a/src/librustc_back/archive.rs b/src/librustc_back/archive.rs index aec8ac38a5a..2cc51a723f2 100644 --- a/src/librustc_back/archive.rs +++ b/src/librustc_back/archive.rs @@ -319,7 +319,7 @@ impl<'a> ArchiveBuilder<'a> { }; let new_filename = self.work_dir.path().join(&filename[..]); try!(fs::rename(&file, &new_filename)); - self.members.push(PathBuf::new(&filename)); + self.members.push(PathBuf::from(filename)); } Ok(()) } diff --git a/src/librustc_back/fs.rs b/src/librustc_back/fs.rs index c29cbb352a3..6d8891dd4fe 100644 --- a/src/librustc_back/fs.rs +++ b/src/librustc_back/fs.rs @@ -19,7 +19,7 @@ use std::path::{Path, PathBuf}; pub fn realpath(original: &Path) -> io::Result { let old = old_path::Path::new(original.to_str().unwrap()); match old_realpath(&old) { - Ok(p) => Ok(PathBuf::new(p.as_str().unwrap())), + Ok(p) => Ok(PathBuf::from(p.as_str().unwrap())), Err(e) => Err(io::Error::new(io::ErrorKind::Other, "realpath error", Some(e.to_string()))) diff --git a/src/librustc_back/lib.rs b/src/librustc_back/lib.rs index 99d24a60130..086742f740c 100644 --- a/src/librustc_back/lib.rs +++ b/src/librustc_back/lib.rs @@ -49,6 +49,7 @@ #![feature(std_misc)] #![feature(path_relative_from)] #![feature(step_by)] +#![feature(convert)] extern crate syntax; extern crate serialize; diff --git a/src/librustc_back/rpath.rs b/src/librustc_back/rpath.rs index 4f9f1447d8a..8dd65c5b893 100644 --- a/src/librustc_back/rpath.rs +++ b/src/librustc_back/rpath.rs @@ -106,7 +106,7 @@ fn get_rpath_relative_to_output(config: &mut RPathConfig, lib: &Path) -> String } fn relativize(path: &Path, rel: &Path) -> PathBuf { - let mut res = PathBuf::new(""); + let mut res = PathBuf::new(); let mut cur = rel; while !path.starts_with(cur) { res.push(".."); diff --git a/src/librustc_back/target/mod.rs b/src/librustc_back/target/mod.rs index 4663901a7b4..c464658f447 100644 --- a/src/librustc_back/target/mod.rs +++ b/src/librustc_back/target/mod.rs @@ -393,11 +393,11 @@ impl Target { let path = { let mut target = target.to_string(); target.push_str(".json"); - PathBuf::new(&target) + PathBuf::from(target) }; let target_path = env::var_os("RUST_TARGET_PATH") - .unwrap_or(OsString::from_str("")); + .unwrap_or(OsString::new()); // FIXME 16351: add a sane default search path? diff --git a/src/librustc_borrowck/lib.rs b/src/librustc_borrowck/lib.rs index e09457970e1..e927ea5b86c 100644 --- a/src/librustc_borrowck/lib.rs +++ b/src/librustc_borrowck/lib.rs @@ -28,6 +28,7 @@ #![feature(rustc_private)] #![feature(staged_api)] #![feature(unsafe_destructor)] +#![feature(into_cow)] #[macro_use] extern crate log; #[macro_use] extern crate syntax; diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index dc27a301109..4c654cbf27d 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -468,7 +468,7 @@ pub fn phase_2_configure_and_expand(sess: &Session, // dependent dlls. Note that this uses cfg!(windows) as opposed to // targ_cfg because syntax extensions are always loaded for the host // compiler, not for the target. - let mut _old_path = OsString::from_str(""); + let mut _old_path = OsString::new(); if cfg!(windows) { _old_path = env::var_os("PATH").unwrap_or(_old_path); let mut new_path = sess.host_filesearch(PathKind::All).get_dylib_search_paths(); @@ -752,7 +752,7 @@ pub fn phase_5_run_llvm_passes(sess: &Session, pub fn phase_6_link_output(sess: &Session, trans: &trans::CrateTranslation, outputs: &OutputFilenames) { - let old_path = env::var_os("PATH").unwrap_or(OsString::from_str("")); + let old_path = env::var_os("PATH").unwrap_or(OsString::new()); let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths(); new_path.extend(env::split_paths(&old_path)); env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap()); @@ -927,7 +927,7 @@ pub fn build_output_filenames(input: &Input, // We want to toss everything after the final '.' let dirpath = match *odir { Some(ref d) => d.clone(), - None => PathBuf::new("") + None => PathBuf::new() }; // If a crate name is present, we use it as the link name diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 0071e4434ef..5e6f2fb835b 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -39,6 +39,7 @@ #![feature(io)] #![feature(set_stdio)] #![feature(unicode)] +#![feature(convert)] extern crate arena; extern crate flate; @@ -163,8 +164,8 @@ pub fn run_compiler<'a>(args: &[String], // Extract output directory and file from matches. fn make_output(matches: &getopts::Matches) -> (Option, Option) { - let odir = matches.opt_str("out-dir").map(|o| PathBuf::new(&o)); - let ofile = matches.opt_str("o").map(|o| PathBuf::new(&o)); + let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o)); + let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o)); (odir, ofile) } @@ -177,7 +178,7 @@ fn make_input(free_matches: &[String]) -> Option<(Input, Option)> { io::stdin().read_to_string(&mut src).unwrap(); Some((Input::Str(src), None)) } else { - Some((Input::File(PathBuf::new(ifile)), Some(PathBuf::new(ifile)))) + Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)))) } } else { None @@ -858,9 +859,9 @@ pub fn diagnostics_registry() -> diagnostics::registry::Registry { use syntax::diagnostics::registry::Registry; let all_errors = Vec::new() + - rustc::diagnostics::DIAGNOSTICS.as_slice() + - rustc_typeck::diagnostics::DIAGNOSTICS.as_slice() + - rustc_resolve::diagnostics::DIAGNOSTICS.as_slice(); + &rustc::diagnostics::DIAGNOSTICS[..] + + &rustc_typeck::diagnostics::DIAGNOSTICS[..] + + &rustc_resolve::diagnostics::DIAGNOSTICS[..]; Registry::new(&*all_errors) } diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index f6f82c65374..7958dabe74e 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -2056,7 +2056,7 @@ impl LintPass for InvalidNoMangleItems { } }, ast::ItemStatic(..) => { - if attr::contains_name(it.attrs.as_slice(), "no_mangle") && + if attr::contains_name(&it.attrs, "no_mangle") && !cx.exported_items.contains(&it.id) { let msg = format!("static {} is marked #[no_mangle], but not exported", it.ident); @@ -2064,7 +2064,7 @@ impl LintPass for InvalidNoMangleItems { } }, ast::ItemConst(..) => { - if attr::contains_name(it.attrs.as_slice(), "no_mangle") { + if attr::contains_name(&it.attrs, "no_mangle") { // Const items do not refer to a particular location in memory, and therefore // don't have anything to attach a symbol to let msg = "const items should never be #[no_mangle], consider instead using \ diff --git a/src/librustc_trans/back/link.rs b/src/librustc_trans/back/link.rs index 34a23f3efac..c0a2e24d6f5 100644 --- a/src/librustc_trans/back/link.rs +++ b/src/librustc_trans/back/link.rs @@ -877,7 +877,7 @@ fn link_args(cmd: &mut Command, if t.options.is_like_osx { let morestack = lib_path.join("libmorestack.a"); - let mut v = OsString::from_str("-Wl,-force_load,"); + let mut v = OsString::from("-Wl,-force_load,"); v.push(&morestack); cmd.arg(&v); } else { @@ -1002,7 +1002,7 @@ fn link_args(cmd: &mut Command, cmd.args(&["-dynamiclib", "-Wl,-dylib"]); if sess.opts.cg.rpath { - let mut v = OsString::from_str("-Wl,-install_name,@rpath/"); + let mut v = OsString::from("-Wl,-install_name,@rpath/"); v.push(out_filename.file_name().unwrap()); cmd.arg(&v); } @@ -1020,7 +1020,7 @@ fn link_args(cmd: &mut Command, let mut get_install_prefix_lib_path = || { let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX"); let tlib = filesearch::relative_target_lib_path(sysroot, target_triple); - let mut path = PathBuf::new(install_prefix); + let mut path = PathBuf::from(install_prefix); path.push(&tlib); path @@ -1102,7 +1102,7 @@ fn add_local_native_libraries(cmd: &mut Command, sess: &Session) { &sess.target.target.options.staticlib_suffix, &search_path[..], &sess.diagnostic().handler); - let mut v = OsString::from_str("-Wl,-force_load,"); + let mut v = OsString::from("-Wl,-force_load,"); v.push(&lib); cmd.arg(&v); } diff --git a/src/librustc_trans/lib.rs b/src/librustc_trans/lib.rs index efc81da560b..176e3805a31 100644 --- a/src/librustc_trans/lib.rs +++ b/src/librustc_trans/lib.rs @@ -41,6 +41,7 @@ #![feature(path_ext)] #![feature(fs)] #![feature(hash)] +#![feature(convert)] #![feature(path_relative_from)] extern crate arena; diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index 83bb5efb425..765e93f5b82 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -1509,10 +1509,10 @@ pub fn process_crate(sess: &Session, // find a path to dump our data to let mut root_path = match env::var_os("DXR_RUST_TEMP_FOLDER") { - Some(val) => PathBuf::new(&val), + Some(val) => PathBuf::from(val), None => match odir { Some(val) => val.join("dxr"), - None => PathBuf::new("dxr-temp"), + None => PathBuf::from("dxr-temp"), }, }; diff --git a/src/librustc_trans/trans/debuginfo.rs b/src/librustc_trans/trans/debuginfo.rs index 3e8cc46e255..b9c59a0bc78 100644 --- a/src/librustc_trans/trans/debuginfo.rs +++ b/src/librustc_trans/trans/debuginfo.rs @@ -1695,7 +1695,7 @@ fn declare_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, }; let name = CString::new(name.as_bytes()).unwrap(); - match (variable_access, [].as_slice()) { + match (variable_access, &[][..]) { (DirectVariable { alloca }, address_operations) | (IndirectVariable {alloca, address_operations}, _) => { let metadata = unsafe { diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 97cc3ac7c48..f1352cacae4 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -690,7 +690,7 @@ fn convert_field<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, } } -fn convert_associated_type<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, +fn as_refsociated_type<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, container: ImplOrTraitItemContainer, ident: ast::Ident, id: ast::NodeId, @@ -835,7 +835,7 @@ fn convert_item(ccx: &CrateCtxt, it: &ast::Item) { "associated items are not allowed in inherent impls"); } - convert_associated_type(ccx, ImplContainer(local_def(it.id)), + as_refsociated_type(ccx, ImplContainer(local_def(it.id)), impl_item.ident, impl_item.id, impl_item.vis); let typ = ccx.icx(&ty_predicates).to_ty(&ExplicitRscope, ty); @@ -917,7 +917,7 @@ fn convert_item(ccx: &CrateCtxt, it: &ast::Item) { match trait_item.node { ast::MethodTraitItem(..) => {} ast::TypeTraitItem(..) => { - convert_associated_type(ccx, TraitContainer(local_def(it.id)), + as_refsociated_type(ccx, TraitContainer(local_def(it.id)), trait_item.ident, trait_item.id, ast::Public); } } @@ -1987,7 +1987,7 @@ fn conv_param_bounds<'a,'tcx>(astconv: &AstConv<'tcx>, builtin_bounds, trait_bounds, region_bounds - } = astconv::partition_bounds(tcx, span, ast_bounds.as_slice()); + } = astconv::partition_bounds(tcx, span, &ast_bounds); let mut projection_bounds = Vec::new(); diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 421549f8b7e..8e9408c9ebc 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -188,7 +188,7 @@ impl<'a, 'tcx> Clean for visit_ast::RustdocVisitor<'a, 'tcx> { let src = match cx.input { Input::File(ref path) => path.clone(), - Input::Str(_) => PathBuf::new("") // FIXME: this is wrong + Input::Str(_) => PathBuf::new() // FIXME: this is wrong }; Crate { diff --git a/src/librustdoc/externalfiles.rs b/src/librustdoc/externalfiles.rs index c2b6c940cae..57cb87e1b2d 100644 --- a/src/librustdoc/externalfiles.rs +++ b/src/librustdoc/externalfiles.rs @@ -47,7 +47,7 @@ pub fn load_string(input: &Path) -> io::Result> { macro_rules! load_or_return { ($input: expr, $cant_read: expr, $not_utf8: expr) => { { - let input = PathBuf::new($input); + let input = PathBuf::from(&$input[..]); match ::externalfiles::load_string(&input) { Err(e) => { let _ = writeln!(&mut io::stderr(), diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 81daac7b90f..d9b40fb6ba6 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -300,7 +300,7 @@ pub fn run(mut krate: clean::Crate, passes: HashSet) -> io::Result<()> { let src_root = match krate.src.parent() { Some(p) => p.to_path_buf(), - None => PathBuf::new(""), + None => PathBuf::new(), }; let mut cx = Context { dst: dst, @@ -784,7 +784,7 @@ impl<'a> DocFolder for SourceCollector<'a> { impl<'a> SourceCollector<'a> { /// Renders the given filename into its corresponding HTML source file. fn emit_source(&mut self, filename: &str) -> io::Result<()> { - let p = PathBuf::new(filename); + let p = PathBuf::from(filename); // If we couldn't open this file, then just returns because it // probably means that it's some standard library macro thing and we @@ -819,7 +819,7 @@ impl<'a> SourceCollector<'a> { let mut fname = p.file_name().expect("source has no filename") .to_os_string(); fname.push(".html"); - cur.push(&fname); + cur.push(&fname[..]); let mut w = BufWriter::new(try!(File::create(&cur))); let title = format!("{} -- source", cur.file_name().unwrap() diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index d747ed3f119..12baa849cc9 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -38,6 +38,7 @@ #![feature(file_path)] #![feature(path_ext)] #![feature(path_relative_from)] +#![feature(convert)] extern crate arena; extern crate getopts; @@ -251,7 +252,7 @@ pub fn main_args(args: &[String]) -> int { let should_test = matches.opt_present("test"); let markdown_input = input.ends_with(".md") || input.ends_with(".markdown"); - let output = matches.opt_str("o").map(|s| PathBuf::new(&s)); + let output = matches.opt_str("o").map(|s| PathBuf::from(&s)); let cfgs = matches.opt_strs("cfg"); let external_html = match ExternalHtml::load( @@ -271,7 +272,7 @@ pub fn main_args(args: &[String]) -> int { return test::run(input, cfgs, libs, externs, test_args, crate_name) } (false, true) => return markdown::render(input, - output.unwrap_or(PathBuf::new("doc")), + output.unwrap_or(PathBuf::from("doc")), &matches, &external_html, !matches.opt_present("markdown-no-toc")), (false, false) => {} @@ -289,7 +290,7 @@ pub fn main_args(args: &[String]) -> int { match matches.opt_str("w").as_ref().map(|s| &**s) { Some("html") | None => { match html::render::run(krate, &external_html, - output.unwrap_or(PathBuf::new("doc")), + output.unwrap_or(PathBuf::from("doc")), passes.into_iter().collect()) { Ok(()) => {} Err(e) => panic!("failed to generate documentation: {}", e), @@ -297,7 +298,7 @@ pub fn main_args(args: &[String]) -> int { } Some("json") => { match json_output(krate, json_plugins, - output.unwrap_or(PathBuf::new("doc.json"))) { + output.unwrap_or(PathBuf::from("doc.json"))) { Ok(()) => {} Err(e) => panic!("failed to write json: {}", e), } @@ -376,7 +377,7 @@ fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matche let cfgs = matches.opt_strs("cfg"); let triple = matches.opt_str("target"); - let cr = PathBuf::new(cratefile); + let cr = PathBuf::from(cratefile); info!("starting to run rustc"); let (tx, rx) = channel(); diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index e2f8a6f82c6..0b79fa7970d 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -46,7 +46,7 @@ pub fn run(input: &str, mut test_args: Vec, crate_name: Option) -> int { - let input_path = PathBuf::new(input); + let input_path = PathBuf::from(input); let input = config::Input::File(input_path.clone()); let sessopts = config::Options { diff --git a/src/libserialize/lib.rs b/src/libserialize/lib.rs index 90cb88046e5..f320f723c2e 100644 --- a/src/libserialize/lib.rs +++ b/src/libserialize/lib.rs @@ -37,6 +37,7 @@ Core encoding and decoding interfaces. #![feature(std_misc)] #![feature(unicode)] #![feature(str_char)] +#![feature(convert)] #![cfg_attr(test, feature(test))] // test harness access diff --git a/src/libserialize/serialize.rs b/src/libserialize/serialize.rs index 71f9e01706d..5e9baa9b9e9 100644 --- a/src/libserialize/serialize.rs +++ b/src/libserialize/serialize.rs @@ -579,7 +579,7 @@ impl Encodable for path::PathBuf { impl Decodable for path::PathBuf { fn decode(d: &mut D) -> Result { let bytes: String = try!(Decodable::decode(d)); - Ok(path::PathBuf::new(&bytes)) + Ok(path::PathBuf::from(bytes)) } } diff --git a/src/libstd/env.rs b/src/libstd/env.rs index 24882c7f7ab..9d6933ce9c8 100644 --- a/src/libstd/env.rs +++ b/src/libstd/env.rs @@ -23,7 +23,7 @@ use error::Error; use ffi::{OsString, AsOsStr}; use fmt; use io; -use path::{AsPath, PathBuf}; +use path::{self, Path, PathBuf}; use sync::atomic::{AtomicIsize, ATOMIC_ISIZE_INIT, Ordering}; use sync::{StaticMutex, MUTEX_INIT}; use sys::os as os_imp; @@ -67,8 +67,8 @@ pub fn current_dir() -> io::Result { /// println!("Successfully changed working directory to {}!", root.display()); /// ``` #[stable(feature = "env", since = "1.0.0")] -pub fn set_current_dir(p: &P) -> io::Result<()> { - os_imp::chdir(p.as_path()) +pub fn set_current_dir + ?Sized>(p: &P) -> io::Result<()> { + os_imp::chdir(p.as_ref()) } static ENV_LOCK: StaticMutex = MUTEX_INIT; diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index fc4f03ff3a5..1760445a0fc 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -10,6 +10,7 @@ #![unstable(feature = "std_misc")] +use convert::Into; use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering}; use error::{Error, FromError}; use fmt; @@ -130,6 +131,8 @@ pub struct NulError(usize, Vec); /// A conversion trait used by the constructor of `CString` for types that can /// be converted to a vector of bytes. +#[deprecated(since = "1.0.0", reason = "use std::convert::Into> instead")] +#[unstable(feature = "std_misc")] pub trait IntoBytes { /// Consumes this container, returning a vector of bytes. fn into_bytes(self) -> Vec; @@ -163,8 +166,8 @@ impl CString { /// internal 0 byte. The error returned will contain the bytes as well as /// the position of the nul byte. #[stable(feature = "rust1", since = "1.0.0")] - pub fn new(t: T) -> Result { - let bytes = t.into_bytes(); + pub fn new>>(t: T) -> Result { + let bytes = t.into(); match bytes.iter().position(|x| *x == 0) { Some(i) => Err(NulError(i, bytes)), None => Ok(unsafe { CString::from_vec_unchecked(bytes) }), @@ -433,15 +436,19 @@ pub unsafe fn c_str_to_bytes_with_nul<'a>(raw: &'a *const libc::c_char) slice::from_raw_parts(*(raw as *const _ as *const *const u8), len as usize) } +#[allow(deprecated)] impl<'a> IntoBytes for &'a str { fn into_bytes(self) -> Vec { self.as_bytes().to_vec() } } +#[allow(deprecated)] impl<'a> IntoBytes for &'a [u8] { fn into_bytes(self) -> Vec { self.to_vec() } } +#[allow(deprecated)] impl IntoBytes for String { fn into_bytes(self) -> Vec { self.into_bytes() } } +#[allow(deprecated)] impl IntoBytes for Vec { fn into_bytes(self) -> Vec { self } } diff --git a/src/libstd/ffi/os_str.rs b/src/libstd/ffi/os_str.rs index feacbf1e98b..4d411046632 100644 --- a/src/libstd/ffi/os_str.rs +++ b/src/libstd/ffi/os_str.rs @@ -63,16 +63,18 @@ pub struct OsStr { impl OsString { /// Constructs an `OsString` at no cost by consuming a `String`. #[stable(feature = "rust1", since = "1.0.0")] + #[deprecated(since = "1.0.0", reason = "use `from` instead")] pub fn from_string(s: String) -> OsString { - OsString { inner: Buf::from_string(s) } + OsString::from(s) } /// Constructs an `OsString` by copying from a `&str` slice. /// /// Equivalent to: `OsString::from_string(String::from_str(s))`. #[stable(feature = "rust1", since = "1.0.0")] + #[deprecated(since = "1.0.0", reason = "use `from` instead")] pub fn from_str(s: &str) -> OsString { - OsString { inner: Buf::from_str(s) } + OsString::from(s) } /// Constructs a new empty `OsString`. @@ -98,8 +100,36 @@ impl OsString { /// Extend the string with the given `&OsStr` slice. #[stable(feature = "rust1", since = "1.0.0")] - pub fn push(&mut self, s: &T) { - self.inner.push_slice(&s.as_os_str().inner) + pub fn push>(&mut self, s: T) { + self.inner.push_slice(&s.as_ref().inner) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl From for OsString { + fn from(s: String) -> OsString { + OsString { inner: Buf::from_string(s) } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a> From<&'a String> for OsString { + fn from(s: &'a String) -> OsString { + OsString { inner: Buf::from_str(s) } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a> From<&'a str> for OsString { + fn from(s: &'a str) -> OsString { + OsString { inner: Buf::from_str(s) } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a> From<&'a OsStr> for OsString { + fn from(s: &'a OsStr) -> OsString { + OsString { inner: s.inner.to_owned() } } } @@ -316,37 +346,76 @@ impl ToOwned for OsStr { } #[stable(feature = "rust1", since = "1.0.0")] +#[deprecated(since = "1.0.0", reason = "trait is deprecated")] impl<'a, T: AsOsStr + ?Sized> AsOsStr for &'a T { fn as_os_str(&self) -> &OsStr { (*self).as_os_str() } } +#[stable(feature = "rust1", since = "1.0.0")] +#[deprecated(since = "1.0.0", reason = "trait is deprecated")] impl AsOsStr for OsStr { fn as_os_str(&self) -> &OsStr { self } } +#[stable(feature = "rust1", since = "1.0.0")] +#[deprecated(since = "1.0.0", reason = "trait is deprecated")] impl AsOsStr for OsString { fn as_os_str(&self) -> &OsStr { &self[..] } } +#[stable(feature = "rust1", since = "1.0.0")] +#[deprecated(since = "1.0.0", reason = "trait is deprecated")] impl AsOsStr for str { fn as_os_str(&self) -> &OsStr { OsStr::from_str(self) } } +#[stable(feature = "rust1", since = "1.0.0")] +#[deprecated(since = "1.0.0", reason = "trait is deprecated")] impl AsOsStr for String { fn as_os_str(&self) -> &OsStr { OsStr::from_str(&self[..]) } } +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef for OsStr { + fn as_ref(&self) -> &OsStr { + self + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef for OsString { + fn as_ref(&self) -> &OsStr { + self + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef for str { + fn as_ref(&self) -> &OsStr { + OsStr::from_str(self) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef for String { + fn as_ref(&self) -> &OsStr { + OsStr::from_str(&self[..]) + } +} + #[allow(deprecated)] +#[stable(feature = "rust1", since = "1.0.0")] +#[deprecated(since = "1.0.0", reason = "trait is deprecated")] impl AsOsStr for Path { #[cfg(unix)] fn as_os_str(&self) -> &OsStr { diff --git a/src/libstd/fs/mod.rs b/src/libstd/fs/mod.rs index 7df6d6887a2..ab65004f5d1 100644 --- a/src/libstd/fs/mod.rs +++ b/src/libstd/fs/mod.rs @@ -20,7 +20,7 @@ use core::prelude::*; use io::{self, Error, ErrorKind, SeekFrom, Seek, Read, Write}; -use path::{AsPath, Path, PathBuf}; +use path::{Path, PathBuf}; use sys::fs2 as fs_imp; use sys_common::{AsInnerMut, FromInner, AsInner}; use vec::Vec; @@ -129,7 +129,7 @@ impl File { /// This function will return an error if `path` does not already exist. /// Other errors may also be returned according to `OpenOptions::open`. #[stable(feature = "rust1", since = "1.0.0")] - pub fn open(path: P) -> io::Result { + pub fn open>(path: P) -> io::Result { OpenOptions::new().read(true).open(path) } @@ -140,7 +140,7 @@ impl File { /// /// See the `OpenOptions::open` function for more details. #[stable(feature = "rust1", since = "1.0.0")] - pub fn create(path: P) -> io::Result { + pub fn create>(path: P) -> io::Result { OpenOptions::new().write(true).create(true).truncate(true).open(path) } @@ -302,8 +302,8 @@ impl OpenOptions { /// permissions for /// * Filesystem-level errors (full disk, etc) #[stable(feature = "rust1", since = "1.0.0")] - pub fn open(&self, path: P) -> io::Result { - let path = path.as_path(); + pub fn open>(&self, path: P) -> io::Result { + let path = path.as_ref(); let inner = try!(fs_imp::File::open(path, &self.0)); Ok(File { path: path.to_path_buf(), inner: inner }) } @@ -415,8 +415,8 @@ impl DirEntry { /// user lacks permissions to remove the file, or if some other filesystem-level /// error occurs. #[stable(feature = "rust1", since = "1.0.0")] -pub fn remove_file(path: P) -> io::Result<()> { - fs_imp::unlink(path.as_path()) +pub fn remove_file>(path: P) -> io::Result<()> { + fs_imp::unlink(path.as_ref()) } /// Given a path, query the file system to get information about a file, @@ -443,8 +443,8 @@ pub fn remove_file(path: P) -> io::Result<()> { /// permissions to perform a `metadata` call on the given `path` or if there /// is no entry in the filesystem at the provided path. #[stable(feature = "rust1", since = "1.0.0")] -pub fn metadata(path: P) -> io::Result { - fs_imp::stat(path.as_path()).map(Metadata) +pub fn metadata>(path: P) -> io::Result { + fs_imp::stat(path.as_ref()).map(Metadata) } /// Rename a file or directory to a new name. @@ -464,8 +464,8 @@ pub fn metadata(path: P) -> io::Result { /// reside on separate filesystems, or if some other intermittent I/O error /// occurs. #[stable(feature = "rust1", since = "1.0.0")] -pub fn rename(from: P, to: Q) -> io::Result<()> { - fs_imp::rename(from.as_path(), to.as_path()) +pub fn rename, Q: AsRef>(from: P, to: Q) -> io::Result<()> { + fs_imp::rename(from.as_ref(), to.as_ref()) } /// Copies the contents of one file to another. This function will also @@ -494,9 +494,9 @@ pub fn rename(from: P, to: Q) -> io::Result<()> { /// * The current process does not have the permission rights to access /// `from` or write `to` #[stable(feature = "rust1", since = "1.0.0")] -pub fn copy(from: P, to: Q) -> io::Result { - let from = from.as_path(); - let to = to.as_path(); +pub fn copy, Q: AsRef>(from: P, to: Q) -> io::Result { + let from = from.as_ref(); + let to = to.as_ref(); if !from.is_file() { return Err(Error::new(ErrorKind::InvalidInput, "the source path is not an existing file", @@ -517,16 +517,16 @@ pub fn copy(from: P, to: Q) -> io::Result { /// The `dst` path will be a link pointing to the `src` path. Note that systems /// often require these two paths to both be located on the same filesystem. #[stable(feature = "rust1", since = "1.0.0")] -pub fn hard_link(src: P, dst: Q) -> io::Result<()> { - fs_imp::link(src.as_path(), dst.as_path()) +pub fn hard_link, Q: AsRef>(src: P, dst: Q) -> io::Result<()> { + fs_imp::link(src.as_ref(), dst.as_ref()) } /// Creates a new soft link on the filesystem. /// /// The `dst` path will be a soft link pointing to the `src` path. #[stable(feature = "rust1", since = "1.0.0")] -pub fn soft_link(src: P, dst: Q) -> io::Result<()> { - fs_imp::symlink(src.as_path(), dst.as_path()) +pub fn soft_link, Q: AsRef>(src: P, dst: Q) -> io::Result<()> { + fs_imp::symlink(src.as_ref(), dst.as_ref()) } /// Reads a soft link, returning the file that the link points to. @@ -537,8 +537,8 @@ pub fn soft_link(src: P, dst: Q) -> io::Result<()> { /// reading a file that does not exist or reading a file that is not a soft /// link. #[stable(feature = "rust1", since = "1.0.0")] -pub fn read_link(path: P) -> io::Result { - fs_imp::readlink(path.as_path()) +pub fn read_link>(path: P) -> io::Result { + fs_imp::readlink(path.as_ref()) } /// Create a new, empty directory at the provided path @@ -556,8 +556,8 @@ pub fn read_link(path: P) -> io::Result { /// This function will return an error if the user lacks permissions to make a /// new directory at the provided `path`, or if the directory already exists. #[stable(feature = "rust1", since = "1.0.0")] -pub fn create_dir(path: P) -> io::Result<()> { - fs_imp::mkdir(path.as_path()) +pub fn create_dir>(path: P) -> io::Result<()> { + fs_imp::mkdir(path.as_ref()) } /// Recursively create a directory and all of its parent components if they @@ -570,8 +570,8 @@ pub fn create_dir(path: P) -> io::Result<()> { /// error conditions for when a directory is being created (after it is /// determined to not exist) are outlined by `fs::create_dir`. #[stable(feature = "rust1", since = "1.0.0")] -pub fn create_dir_all(path: P) -> io::Result<()> { - let path = path.as_path(); +pub fn create_dir_all>(path: P) -> io::Result<()> { + let path = path.as_ref(); if path.is_dir() { return Ok(()) } if let Some(p) = path.parent() { try!(create_dir_all(p)) } create_dir(path) @@ -592,8 +592,8 @@ pub fn create_dir_all(path: P) -> io::Result<()> { /// This function will return an error if the user lacks permissions to remove /// the directory at the provided `path`, or if the directory isn't empty. #[stable(feature = "rust1", since = "1.0.0")] -pub fn remove_dir(path: P) -> io::Result<()> { - fs_imp::rmdir(path.as_path()) +pub fn remove_dir>(path: P) -> io::Result<()> { + fs_imp::rmdir(path.as_ref()) } /// Removes a directory at this path, after removing all its contents. Use @@ -606,8 +606,8 @@ pub fn remove_dir(path: P) -> io::Result<()> { /// /// See `file::remove_file` and `fs::remove_dir` #[stable(feature = "rust1", since = "1.0.0")] -pub fn remove_dir_all(path: P) -> io::Result<()> { - let path = path.as_path(); +pub fn remove_dir_all>(path: P) -> io::Result<()> { + let path = path.as_ref(); for child in try!(read_dir(path)) { let child = try!(child).path(); let stat = try!(lstat(&*child)); @@ -659,8 +659,8 @@ pub fn remove_dir_all(path: P) -> io::Result<()> { /// the process lacks permissions to view the contents or if the `path` points /// at a non-directory file #[stable(feature = "rust1", since = "1.0.0")] -pub fn read_dir(path: P) -> io::Result { - fs_imp::readdir(path.as_path()).map(ReadDir) +pub fn read_dir>(path: P) -> io::Result { + fs_imp::readdir(path.as_ref()).map(ReadDir) } /// Returns an iterator that will recursively walk the directory structure @@ -675,7 +675,7 @@ pub fn read_dir(path: P) -> io::Result { reason = "the precise semantics and defaults for a recursive walk \ may change and this may end up accounting for files such \ as symlinks differently")] -pub fn walk_dir(path: P) -> io::Result { +pub fn walk_dir>(path: P) -> io::Result { let start = try!(read_dir(path)); Ok(WalkDir { cur: Some(start), stack: Vec::new() }) } @@ -761,9 +761,9 @@ impl PathExt for Path { reason = "the argument type of u64 is not quite appropriate for \ this function and may change if the standard library \ gains a type to represent a moment in time")] -pub fn set_file_times(path: P, accessed: u64, +pub fn set_file_times>(path: P, accessed: u64, modified: u64) -> io::Result<()> { - fs_imp::utimes(path.as_path(), accessed, modified) + fs_imp::utimes(path.as_ref(), accessed, modified) } /// Changes the permissions found on a file or a directory. @@ -790,8 +790,8 @@ pub fn set_file_times(path: P, accessed: u64, reason = "a more granual ability to set specific permissions may \ be exposed on the Permissions structure itself and this \ method may not always exist")] -pub fn set_permissions(path: P, perm: Permissions) -> io::Result<()> { - fs_imp::set_perm(path.as_path(), perm.0) +pub fn set_permissions>(path: P, perm: Permissions) -> io::Result<()> { + fs_imp::set_perm(path.as_ref(), perm.0) } #[cfg(test)] diff --git a/src/libstd/fs/tempdir.rs b/src/libstd/fs/tempdir.rs index 8f32d7a5864..a9717e36323 100644 --- a/src/libstd/fs/tempdir.rs +++ b/src/libstd/fs/tempdir.rs @@ -18,7 +18,7 @@ use prelude::v1::*; use env; use io::{self, Error, ErrorKind}; use fs; -use path::{self, PathBuf, AsPath}; +use path::{self, PathBuf}; use rand::{thread_rng, Rng}; /// A wrapper for a path to temporary directory implementing automatic @@ -43,10 +43,9 @@ impl TempDir { /// /// If no directory can be created, `Err` is returned. #[allow(deprecated)] // rand usage - pub fn new_in(tmpdir: &P, prefix: &str) - -> io::Result { + pub fn new_in>(tmpdir: P, prefix: &str) -> io::Result { let storage; - let mut tmpdir = tmpdir.as_path(); + let mut tmpdir = tmpdir.as_ref(); if !tmpdir.is_absolute() { let cur_dir = try!(env::current_dir()); storage = cur_dir.join(tmpdir); diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index b055796ba54..1488c7969f6 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -126,8 +126,10 @@ #![feature(hash)] #![feature(int_uint)] #![feature(unique)] +#![feature(convert)] #![feature(allow_internal_unstable)] #![feature(str_char)] +#![feature(into_cow)] #![cfg_attr(test, feature(test, rustc_private))] // Don't link to std. We are std. @@ -169,6 +171,7 @@ pub use core::any; pub use core::cell; pub use core::clone; #[cfg(not(test))] pub use core::cmp; +pub use core::convert; pub use core::default; #[allow(deprecated)] pub use core::finally; diff --git a/src/libstd/net/ip.rs b/src/libstd/net/ip.rs index 73c2464a6b2..d737ad17ff8 100644 --- a/src/libstd/net/ip.rs +++ b/src/libstd/net/ip.rs @@ -374,7 +374,6 @@ impl fmt::Display for Ipv6Addr { .iter() .map(|&seg| format!("{:x}", seg)) .collect::>() - .as_slice() .connect(":") } diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 3870b8614ff..72f9338b456 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -38,6 +38,7 @@ use self::MapError::*; use boxed::Box; use clone::Clone; +use convert::From; use env; use error::{FromError, Error}; use ffi::{OsString, OsStr}; @@ -79,12 +80,12 @@ fn err2old(new: ::io::Error) -> IoError { #[cfg(windows)] fn path2new(path: &Path) -> PathBuf { - PathBuf::new(path.as_str().unwrap()) + PathBuf::from(path.as_str().unwrap()) } #[cfg(unix)] fn path2new(path: &Path) -> PathBuf { use os::unix::prelude::*; - PathBuf::new(::from_bytes(path.as_vec())) + PathBuf::from(::from_bytes(path.as_vec())) } #[cfg(unix)] diff --git a/src/libstd/path.rs b/src/libstd/path.rs index ddceed14cc6..25372c1cb7c 100644 --- a/src/libstd/path.rs +++ b/src/libstd/path.rs @@ -106,6 +106,7 @@ use cmp; use iter::{self, IntoIterator}; use mem; use ops::{self, Deref}; +use string::String; use vec::Vec; use fmt; @@ -527,6 +528,13 @@ impl<'a> Component<'a> { } } +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a> AsRef for Component<'a> { + fn as_ref(&self) -> &OsStr { + self.as_os_str() + } +} + /// The core iterator giving the components of a path. /// /// See the module documentation for an in-depth explanation of components and @@ -601,6 +609,7 @@ impl<'a> Components<'a> { } /// Extract a slice corresponding to the portion of the path remaining for iteration. + #[stable(feature = "rust1", since = "1.0.0")] pub fn as_path(&self) -> &'a Path { let mut comps = self.clone(); if comps.front == State::Body { comps.trim_left(); } @@ -695,6 +704,20 @@ impl<'a> Components<'a> { } } +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a> AsRef for Components<'a> { + fn as_ref(&self) -> &Path { + self.as_path() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a> AsRef for Components<'a> { + fn as_ref(&self) -> &OsStr { + self.as_path().as_os_str() + } +} + impl<'a> Iter<'a> { /// Extract a slice corresponding to the portion of the path remaining for iteration. #[stable(feature = "rust1", since = "1.0.0")] @@ -703,6 +726,20 @@ impl<'a> Iter<'a> { } } +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a> AsRef for Iter<'a> { + fn as_ref(&self) -> &Path { + self.as_path() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a> AsRef for Iter<'a> { + fn as_ref(&self) -> &OsStr { + self.as_path().as_os_str() + } +} + #[stable(feature = "rust1", since = "1.0.0")] impl<'a> Iterator for Iter<'a> { type Item = &'a OsStr; @@ -873,11 +910,10 @@ impl PathBuf { unsafe { mem::transmute(self) } } - /// Allocate a `PathBuf` with initial contents given by the - /// argument. + /// Allocate an empty `PathBuf`. #[stable(feature = "rust1", since = "1.0.0")] - pub fn new(s: S) -> PathBuf { - PathBuf { inner: s.as_os_str().to_os_string() } + pub fn new() -> PathBuf { + PathBuf { inner: OsString::new() } } /// Extend `self` with `path`. @@ -890,8 +926,8 @@ impl PathBuf { /// replaces everything except for the prefix (if any) of `self`. /// * if `path` has a prefix but no root, it replaces `self. #[stable(feature = "rust1", since = "1.0.0")] - pub fn push(&mut self, path: P) { - let path = path.as_path(); + pub fn push>(&mut self, path: P) { + let path = path.as_ref(); // in general, a separator is needed if the rightmost byte is not a separator let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false); @@ -958,12 +994,12 @@ impl PathBuf { /// assert!(buf == PathBuf::new("/baz.txt")); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn set_file_name(&mut self, file_name: S) { + pub fn set_file_name>(&mut self, file_name: S) { if self.file_name().is_some() { let popped = self.pop(); debug_assert!(popped); } - self.push(file_name.as_os_str()); + self.push(file_name.as_ref()); } /// Updates `self.extension()` to `extension`. @@ -973,15 +1009,15 @@ impl PathBuf { /// Otherwise, returns `true`; if `self.extension()` is `None`, the extension /// is added; otherwise it is replaced. #[stable(feature = "rust1", since = "1.0.0")] - pub fn set_extension(&mut self, extension: S) -> bool { + pub fn set_extension>(&mut self, extension: S) -> bool { if self.file_name().is_none() { return false; } let mut stem = match self.file_stem() { Some(stem) => stem.to_os_string(), - None => OsString::from_str(""), + None => OsString::new(), }; - let extension = extension.as_os_str(); + let extension = extension.as_ref(); if os_str_as_u8_slice(extension).len() > 0 { stem.push("."); stem.push(extension); @@ -999,16 +1035,65 @@ impl PathBuf { } #[stable(feature = "rust1", since = "1.0.0")] -impl iter::FromIterator

for PathBuf { +impl<'a> From<&'a Path> for PathBuf { + fn from(s: &'a Path) -> PathBuf { + s.to_path_buf() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a> From<&'a str> for PathBuf { + fn from(s: &'a str) -> PathBuf { + PathBuf::from(OsString::from(s)) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a> From<&'a String> for PathBuf { + fn from(s: &'a String) -> PathBuf { + PathBuf::from(OsString::from(s)) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl From for PathBuf { + fn from(s: String) -> PathBuf { + PathBuf::from(OsString::from(s)) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a> From<&'a OsStr> for PathBuf { + fn from(s: &'a OsStr) -> PathBuf { + PathBuf::from(OsString::from(s)) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a> From<&'a OsString> for PathBuf { + fn from(s: &'a OsString) -> PathBuf { + PathBuf::from(s.to_os_string()) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl From for PathBuf { + fn from(s: OsString) -> PathBuf { + PathBuf { inner: s } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl> iter::FromIterator

for PathBuf { fn from_iter>(iter: I) -> PathBuf { - let mut buf = PathBuf::new(""); + let mut buf = PathBuf::new(); buf.extend(iter); buf } } #[stable(feature = "rust1", since = "1.0.0")] -impl iter::Extend

for PathBuf { +impl> iter::Extend

for PathBuf { fn extend>(&mut self, iter: I) { for p in iter { self.push(p) @@ -1084,12 +1169,27 @@ impl cmp::Ord for PathBuf { } #[stable(feature = "rust1", since = "1.0.0")] +impl AsRef for PathBuf { + fn as_ref(&self) -> &OsStr { + &self.inner[..] + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +#[deprecated(since = "1.0.0", reason = "trait is deprecated")] impl AsOsStr for PathBuf { fn as_os_str(&self) -> &OsStr { &self.inner[..] } } +#[stable(feature = "rust1", since = "1.0.0")] +impl Into for PathBuf { + fn into(self) -> OsString { + self.inner + } +} + /// A slice of a path (akin to `str`). /// /// This type supports a number of operations for inspecting a path, including @@ -1133,8 +1233,14 @@ impl Path { /// /// This is a cost-free conversion. #[stable(feature = "rust1", since = "1.0.0")] - pub fn new(s: &S) -> &Path { - unsafe { mem::transmute(s.as_os_str()) } + pub fn new + ?Sized>(s: &S) -> &Path { + unsafe { mem::transmute(s.as_ref()) } + } + + /// Yield the underlying `OsStr` slice. + #[stable(feature = "rust1", since = "1.0.0")] + pub fn as_os_str(&self) -> &OsStr { + &self.inner } /// Yield a `&str` slice if the `Path` is valid unicode. @@ -1156,7 +1262,7 @@ impl Path { /// Convert a `Path` to an owned `PathBuf`. #[stable(feature = "rust1", since = "1.0.0")] pub fn to_path_buf(&self) -> PathBuf { - PathBuf::new(self) + PathBuf::from(self.inner.to_os_string()) } /// A path is *absolute* if it is independent of the current directory. @@ -1244,22 +1350,21 @@ impl Path { /// Returns a path that, when joined onto `base`, yields `self`. #[unstable(feature = "path_relative_from", reason = "see #23284")] - pub fn relative_from<'a, P: ?Sized>(&'a self, base: &'a P) -> Option<&Path> where - P: AsPath + pub fn relative_from<'a, P: ?Sized + AsRef>(&'a self, base: &'a P) -> Option<&Path> { - iter_after(self.components(), base.as_path().components()).map(|c| c.as_path()) + iter_after(self.components(), base.as_ref().components()).map(|c| c.as_path()) } /// Determines whether `base` is a prefix of `self`. #[stable(feature = "rust1", since = "1.0.0")] - pub fn starts_with(&self, base: P) -> bool { - iter_after(self.components(), base.as_path().components()).is_some() + pub fn starts_with>(&self, base: P) -> bool { + iter_after(self.components(), base.as_ref().components()).is_some() } /// Determines whether `child` is a suffix of `self`. #[stable(feature = "rust1", since = "1.0.0")] - pub fn ends_with(&self, child: P) -> bool { - iter_after(self.components().rev(), child.as_path().components().rev()).is_some() + pub fn ends_with>(&self, child: P) -> bool { + iter_after(self.components().rev(), child.as_ref().components().rev()).is_some() } /// Extract the stem (non-extension) portion of `self.file()`. @@ -1292,7 +1397,7 @@ impl Path { /// /// See `PathBuf::push` for more details on what it means to adjoin a path. #[stable(feature = "rust1", since = "1.0.0")] - pub fn join(&self, path: P) -> PathBuf { + pub fn join>(&self, path: P) -> PathBuf { let mut buf = self.to_path_buf(); buf.push(path); buf @@ -1302,7 +1407,7 @@ impl Path { /// /// See `PathBuf::set_file_name` for more details. #[stable(feature = "rust1", since = "1.0.0")] - pub fn with_file_name(&self, file_name: S) -> PathBuf { + pub fn with_file_name>(&self, file_name: S) -> PathBuf { let mut buf = self.to_path_buf(); buf.set_file_name(file_name); buf @@ -1312,7 +1417,7 @@ impl Path { /// /// See `PathBuf::set_extension` for more details. #[stable(feature = "rust1", since = "1.0.0")] - pub fn with_extension(&self, extension: S) -> PathBuf { + pub fn with_extension>(&self, extension: S) -> PathBuf { let mut buf = self.to_path_buf(); buf.set_extension(extension); buf @@ -1346,6 +1451,14 @@ impl Path { } #[stable(feature = "rust1", since = "1.0.0")] +impl AsRef for Path { + fn as_ref(&self) -> &OsStr { + &self.inner + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +#[deprecated(since = "1.0.0", reason = "trait is deprecated")] impl AsOsStr for Path { fn as_os_str(&self) -> &OsStr { &self.inner @@ -1405,6 +1518,7 @@ impl cmp::Ord for Path { /// Freely convertible to a `Path`. #[unstable(feature = "std_misc")] +#[deprecated(since = "1.0.0", reason = "use std::convert::AsRef instead")] pub trait AsPath { /// Convert to a `Path`. #[unstable(feature = "std_misc")] @@ -1412,10 +1526,42 @@ pub trait AsPath { } #[unstable(feature = "std_misc")] +#[deprecated(since = "1.0.0", reason = "use std::convert::AsRef instead")] +#[allow(deprecated)] impl AsPath for T { fn as_path(&self) -> &Path { Path::new(self.as_os_str()) } } +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef for Path { + fn as_ref(&self) -> &Path { self } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef for OsStr { + fn as_ref(&self) -> &Path { Path::new(self) } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef for OsString { + fn as_ref(&self) -> &Path { Path::new(self) } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef for str { + fn as_ref(&self) -> &Path { Path::new(self) } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef for String { + fn as_ref(&self) -> &Path { Path::new(self) } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef for PathBuf { + fn as_ref(&self) -> &Path { self } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/libstd/prelude/v1.rs b/src/libstd/prelude/v1.rs index a0b4c80e9f3..6e12ac1a226 100644 --- a/src/libstd/prelude/v1.rs +++ b/src/libstd/prelude/v1.rs @@ -29,6 +29,8 @@ #[doc(no_inline)] pub use clone::Clone; #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] pub use cmp::{PartialEq, PartialOrd, Eq, Ord}; +#[unstable(feature = "convert")] +#[doc(no_inline)] pub use convert::{AsRef, AsMut, Into, From}; #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] pub use iter::DoubleEndedIterator; #[stable(feature = "rust1", since = "1.0.0")] @@ -40,8 +42,10 @@ #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] pub use result::Result::{self, Ok, Err}; #[stable(feature = "rust1", since = "1.0.0")] +#[allow(deprecated)] #[doc(no_inline)] pub use slice::{SliceConcatExt, AsSlice}; #[stable(feature = "rust1", since = "1.0.0")] +#[allow(deprecated)] #[doc(no_inline)] pub use str::Str; #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] pub use string::{String, ToString}; diff --git a/src/libstd/process.rs b/src/libstd/process.rs index 6b09636c1df..d11c3d22144 100644 --- a/src/libstd/process.rs +++ b/src/libstd/process.rs @@ -19,8 +19,8 @@ use io::prelude::*; use ffi::AsOsStr; use fmt; use io::{self, Error, ErrorKind}; -use path::AsPath; use libc; +use path; use sync::mpsc::{channel, Receiver}; use sys::pipe2::{self, AnonPipe}; use sys::process2::Process as ProcessImp; @@ -198,8 +198,8 @@ impl Command { /// Set the working directory for the child process. #[stable(feature = "process", since = "1.0.0")] - pub fn current_dir(&mut self, dir: P) -> &mut Command { - self.inner.cwd(dir.as_path().as_os_str()); + pub fn current_dir>(&mut self, dir: P) -> &mut Command { + self.inner.cwd(dir.as_ref().as_os_str()); self } diff --git a/src/libstd/sys/unix/fs2.rs b/src/libstd/sys/unix/fs2.rs index ea74aab3331..202e5ddaec4 100644 --- a/src/libstd/sys/unix/fs2.rs +++ b/src/libstd/sys/unix/fs2.rs @@ -338,8 +338,7 @@ pub fn readlink(p: &Path) -> io::Result { })); buf.set_len(n as usize); } - let s: OsString = OsStringExt::from_vec(buf); - Ok(PathBuf::new(&s)) + Ok(PathBuf::from(OsString::from_vec(buf))) } pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> { diff --git a/src/libstd/sys/unix/os.rs b/src/libstd/sys/unix/os.rs index a5a2f71acb7..6c191689255 100644 --- a/src/libstd/sys/unix/os.rs +++ b/src/libstd/sys/unix/os.rs @@ -36,7 +36,7 @@ const BUF_BYTES: usize = 2048; const TMPBUF_SZ: usize = 128; fn bytes2path(b: &[u8]) -> PathBuf { - PathBuf::new(::from_bytes(b)) + PathBuf::from(::from_bytes(b)) } fn os2path(os: OsString) -> PathBuf { @@ -253,7 +253,7 @@ pub fn current_exe() -> io::Result { let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz); if err != 0 { return Err(io::Error::last_os_error()); } v.set_len(sz as uint - 1); // chop off trailing NUL - Ok(PathBuf::new(OsString::from_vec(v))) + Ok(PathBuf::from(OsString::from_vec(v))) } } @@ -466,9 +466,9 @@ pub fn page_size() -> usize { pub fn temp_dir() -> PathBuf { getenv("TMPDIR".as_os_str()).map(os2path).unwrap_or_else(|| { if cfg!(target_os = "android") { - PathBuf::new("/data/local/tmp") + PathBuf::from("/data/local/tmp") } else { - PathBuf::new("/tmp") + PathBuf::from("/tmp") } }) } diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 70aab26092c..1abe8d0a3c1 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -351,8 +351,7 @@ impl Encodable for FileMap { let max_line_length = if lines.len() == 1 { 0 } else { - lines.as_slice() - .windows(2) + lines.windows(2) .map(|w| w[1] - w[0]) .map(|bp| bp.to_usize()) .max() diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index c61aec0069d..31d8b207bb9 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -194,7 +194,7 @@ pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) fn res_rel_file(cx: &mut ExtCtxt, sp: codemap::Span, arg: &Path) -> PathBuf { // NB: relative paths are resolved relative to the compilation unit if !arg.is_absolute() { - let mut cu = PathBuf::new(&cx.codemap().span_to_filename(sp)); + let mut cu = PathBuf::from(&cx.codemap().span_to_filename(sp)); cu.pop(); cu.push(arg); cu diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs index 9f217bba00a..9af7b9ab633 100644 --- a/src/libsyntax/lib.rs +++ b/src/libsyntax/lib.rs @@ -39,6 +39,8 @@ #![feature(unicode)] #![feature(path_ext)] #![feature(str_char)] +#![feature(convert)] +#![feature(into_cow)] extern crate arena; extern crate fmt_macros; diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 667af642744..e77786c1347 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -5064,8 +5064,8 @@ impl<'a> Parser<'a> { outer_attrs: &[ast::Attribute], id_sp: Span) -> (ast::Item_, Vec ) { - let mut prefix = PathBuf::new(&self.sess.span_diagnostic.cm - .span_to_filename(self.span)); + let mut prefix = PathBuf::from(&self.sess.span_diagnostic.cm + .span_to_filename(self.span)); prefix.pop(); let mut dir_path = prefix; for part in &self.mod_path_stack { diff --git a/src/libterm/lib.rs b/src/libterm/lib.rs index f517dca53cd..8e3c00bb805 100644 --- a/src/libterm/lib.rs +++ b/src/libterm/lib.rs @@ -62,6 +62,7 @@ #![feature(std_misc)] #![feature(str_char)] #![feature(path_ext)] +#![feature(convert)] #![cfg_attr(windows, feature(libc))] #[macro_use] extern crate log; diff --git a/src/libterm/terminfo/searcher.rs b/src/libterm/terminfo/searcher.rs index f47921cbf5e..66ee2b1ba87 100644 --- a/src/libterm/terminfo/searcher.rs +++ b/src/libterm/terminfo/searcher.rs @@ -31,7 +31,7 @@ pub fn get_dbpath_for_term(term: &str) -> Option> { // Find search directory match env::var_os("TERMINFO") { - Some(dir) => dirs_to_search.push(PathBuf::new(&dir)), + Some(dir) => dirs_to_search.push(PathBuf::from(dir)), None => { if homedir.is_some() { // ncurses compatibility; @@ -40,9 +40,9 @@ pub fn get_dbpath_for_term(term: &str) -> Option> { match env::var("TERMINFO_DIRS") { Ok(dirs) => for i in dirs.split(':') { if i == "" { - dirs_to_search.push(PathBuf::new("/usr/share/terminfo")); + dirs_to_search.push(PathBuf::from("/usr/share/terminfo")); } else { - dirs_to_search.push(PathBuf::new(i)); + dirs_to_search.push(PathBuf::from(i)); } }, // Found nothing in TERMINFO_DIRS, use the default paths: @@ -50,9 +50,9 @@ pub fn get_dbpath_for_term(term: &str) -> Option> { // ~/.terminfo, ncurses will search /etc/terminfo, then // /lib/terminfo, and eventually /usr/share/terminfo. Err(..) => { - dirs_to_search.push(PathBuf::new("/etc/terminfo")); - dirs_to_search.push(PathBuf::new("/lib/terminfo")); - dirs_to_search.push(PathBuf::new("/usr/share/terminfo")); + dirs_to_search.push(PathBuf::from("/etc/terminfo")); + dirs_to_search.push(PathBuf::from("/lib/terminfo")); + dirs_to_search.push(PathBuf::from("/usr/share/terminfo")); } } } diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index 51decbab858..94944453eda 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -45,6 +45,7 @@ #![feature(libc)] #![feature(set_stdio)] #![feature(os)] +#![feature(convert)] extern crate getopts; extern crate serialize; @@ -382,7 +383,7 @@ pub fn parse_opts(args: &[String]) -> Option { let run_ignored = matches.opt_present("ignored"); let logfile = matches.opt_str("logfile"); - let logfile = logfile.map(|s| PathBuf::new(&s)); + let logfile = logfile.map(|s| PathBuf::from(&s)); let run_benchmarks = matches.opt_present("bench"); let run_tests = ! run_benchmarks || @@ -696,7 +697,7 @@ pub fn run_tests_console(opts: &TestOpts, tests: Vec ) -> io::Res match tests.iter().max_by(|t|len_if_padded(*t)) { Some(t) => { let n = t.desc.name.as_slice(); - st.max_name_len = n.as_slice().len(); + st.max_name_len = n.len(); }, None => {} } diff --git a/src/rustbook/book.rs b/src/rustbook/book.rs index ac7f2f824cb..a08481f8be9 100644 --- a/src/rustbook/book.rs +++ b/src/rustbook/book.rs @@ -102,8 +102,8 @@ pub fn parse_summary(input: &mut Read, src: &Path) -> Result> // always include the introduction top_items.push(BookItem { title: "Introduction".to_string(), - path: PathBuf::new("README.md"), - path_to_root: PathBuf::new("."), + path: PathBuf::from("README.md"), + path_to_root: PathBuf::from("."), children: vec!(), }); @@ -133,10 +133,10 @@ pub fn parse_summary(input: &mut Read, src: &Path) -> Result> errors.push(format!("paths in SUMMARY.md must be relative, \ but path '{}' for section '{}' is not.", given_path, title)); - PathBuf::new("") + PathBuf::new() } }; - let path_to_root = PathBuf::new(&iter::repeat("../") + let path_to_root = PathBuf::from(&iter::repeat("../") .take(path_from_root.components().count() - 1) .collect::()); let item = BookItem { diff --git a/src/rustbook/build.rs b/src/rustbook/build.rs index 731773917e0..f06290b27cb 100644 --- a/src/rustbook/build.rs +++ b/src/rustbook/build.rs @@ -87,7 +87,7 @@ fn render(book: &Book, tgt: &Path) -> CliResult<()> { if env::args().len() < 3 { src = env::current_dir().unwrap().clone(); } else { - src = PathBuf::new(&env::args().nth(2).unwrap()); + src = PathBuf::from(&env::args().nth(2).unwrap()); } // preprocess the markdown, rerouting markdown references to html references let mut markdown_data = String::new(); @@ -164,13 +164,13 @@ impl Subcommand for Build { if env::args().len() < 3 { src = cwd.clone(); } else { - src = PathBuf::new(&env::args().nth(2).unwrap()); + src = PathBuf::from(&env::args().nth(2).unwrap()); } if env::args().len() < 4 { tgt = cwd.join("_book"); } else { - tgt = PathBuf::new(&env::args().nth(3).unwrap()); + tgt = PathBuf::from(&env::args().nth(3).unwrap()); } try!(fs::create_dir(&tgt)); diff --git a/src/rustbook/main.rs b/src/rustbook/main.rs index 09fcd518c1e..4a652f846ed 100644 --- a/src/rustbook/main.rs +++ b/src/rustbook/main.rs @@ -15,6 +15,7 @@ #![feature(rustdoc)] #![feature(rustc_private)] #![feature(path_relative_from)] +#![feature(convert)] extern crate rustdoc; extern crate rustc_back; diff --git a/src/test/run-pass/env-home-dir.rs b/src/test/run-pass/env-home-dir.rs index 5d68a25a14a..cd614750451 100644 --- a/src/test/run-pass/env-home-dir.rs +++ b/src/test/run-pass/env-home-dir.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(convert)] + use std::env::*; use std::path::PathBuf; @@ -16,7 +18,7 @@ fn main() { let oldhome = var("HOME"); set_var("HOME", "/home/MountainView"); - assert!(home_dir() == Some(PathBuf::new("/home/MountainView"))); + assert!(home_dir() == Some(PathBuf::from("/home/MountainView"))); remove_var("HOME"); if cfg!(target_os = "android") { @@ -37,14 +39,14 @@ fn main() { assert!(home_dir().is_some()); set_var("HOME", "/home/MountainView"); - assert!(home_dir() == Some(PathBuf::new("/home/MountainView"))); + assert!(home_dir() == Some(PathBuf::from("/home/MountainView"))); remove_var("HOME"); set_var("USERPROFILE", "/home/MountainView"); - assert!(home_dir() == Some(PathBuf::new("/home/MountainView"))); + assert!(home_dir() == Some(PathBuf::from("/home/MountainView"))); set_var("HOME", "/home/MountainView"); set_var("USERPROFILE", "/home/PaloAlto"); - assert!(home_dir() == Some(PathBuf::new("/home/MountainView"))); + assert!(home_dir() == Some(PathBuf::from("/home/MountainView"))); }