diff options
Diffstat (limited to 'src/libstd/ffi/c_str.rs')
| -rw-r--r-- | src/libstd/ffi/c_str.rs | 26 |
1 files changed, 25 insertions, 1 deletions
diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 483f2ba52ec..6dcda986310 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -327,7 +327,31 @@ impl CString { /// [`NulError`]: struct.NulError.html #[stable(feature = "rust1", since = "1.0.0")] pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> { - Self::_new(t.into()) + trait SpecIntoVec { + fn into_vec(self) -> Vec<u8>; + } + impl<T: Into<Vec<u8>>> SpecIntoVec for T { + default fn into_vec(self) -> Vec<u8> { + self.into() + } + } + // Specialization for avoiding reallocation. + impl SpecIntoVec for &'_ [u8] { + fn into_vec(self) -> Vec<u8> { + let mut v = Vec::with_capacity(self.len() + 1); + v.extend(self); + v + } + } + impl SpecIntoVec for &'_ str { + fn into_vec(self) -> Vec<u8> { + let mut v = Vec::with_capacity(self.len() + 1); + v.extend(self.as_bytes()); + v + } + } + + Self::_new(SpecIntoVec::into_vec(t)) } fn _new(bytes: Vec<u8>) -> Result<CString, NulError> { |
