Implemented the newly stabilized CString::from_vec_with_nul method (#473)

This commit is contained in:
Trangar 2022-01-13 20:52:51 +01:00 committed by GitHub
parent 8106eadf66
commit c1e9828e7d
2 changed files with 10 additions and 10 deletions

View File

@ -139,13 +139,20 @@ pub enum DecodeError {
duration: core::time::Duration,
},
/// The decoder tried to decode a `CStr` or `CString`, but the incoming data contained a 0 byte
/// The decoder tried to decode a `CStr`, but the incoming data contained a 0 byte
#[cfg(feature = "std")]
CStrNulError {
/// The inner exception
inner: std::ffi::FromBytesWithNulError,
},
/// The decoder tried to decode a `CString`, but the incoming data contained a 0 byte
#[cfg(feature = "std")]
CStringNulError {
/// The inner exception
inner: std::ffi::FromVecWithNulError,
},
/// An uncommon error occured, see the inner text for more information
#[cfg(feature = "alloc")]
OtherString(alloc::string::String),

View File

@ -128,15 +128,8 @@ impl Encode for CString {
impl Decode for CString {
fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, DecodeError> {
// BlockedTODO: https://github.com/rust-lang/rust/issues/73179
// use `from_vec_with_nul` instead, combined with:
// let bytes = std::vec::Vec::<u8>::decode(decoder)?;
// now we have to allocate twice unfortunately
let vec: std::vec::Vec<u8> = std::vec::Vec::decode(decoder)?;
let cstr =
CStr::from_bytes_with_nul(&vec).map_err(|e| DecodeError::CStrNulError { inner: e })?;
Ok(cstr.into())
let vec = std::vec::Vec::decode(decoder)?;
CString::from_vec_with_nul(vec).map_err(|inner| DecodeError::CStringNulError { inner })
}
}