Tracking Issue for methods to go from nul-terminated Vec<u8> to CString ·...
source link: https://github.com/rust-lang/rust/issues/73179
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
The feature gate for the issue is #![feature(cstring_from_vec_with_nul)]
.
This adds the following method to CString
:
pub unsafe fn from_vec_with_nul_unchecked(v: Vec<u8>) -> Self { /* ... */ } pub fn from_vec_with_nul(v: Vec<u8>) -> Result<Self, FromVecWithNulError> { /* ... */ }
FromVecWithNulError
is a new error type, following the naming pattern of FromBytesWithNulError
already existing for CStr::new
.
This type, defined as:
#[derive(Clone, PartialEq, Eq, Debug)] #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] pub struct FromVecWithNulError { error_kind: FromBytesWithNulErrorKind, bytes: Vec<u8>, }
It is inspired from the FromUtf8Error
type (having as_bytes
and into_bytes
method) that allows recuperating the input when conversion failed.
The fmt:Display
implementation for the type uses the same text as the FromBytesWithNulError
, without using the deprecated description
method of the Error
trait.
#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] impl fmt::Display for FromVecWithNulError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.error_kind { FromBytesWithNulErrorKind::InteriorNul(pos) => { write!(f, "data provided contains an interior nul byte at pos {}", pos) } FromBytesWithNulErrorKind::NotNulTerminated => { write!(f, "data provided is not nul terminated") } } } }
Unresolved Questions
- Is this feature needed ? It was asked for issue #73100 and
CStr::from_bytes_with_nul
(and itsunchecked
version) seems to indicates that having an owned version would be logical. - Names ? I just changed
bytes
tovec
in the names (CStr::from_bytes_with_nul
->CString::from_vec_with_nul
andCStr::from_bytes_with_nul_unchecked
->CString::from_vec_with_nul_unchecked
). - Input type for the safe version: I used
Vec<u8>
but I seeCString::new
usesInto<Vec<u8>>
, should I use that too ?
Implementation history
PR #73139 implements this at the moment, in a unstable
form, with documentation and doc tests.
PR #89292 by @CleanCut proposes to stabilize this
Edit: this being the first time I write a tracking issue, please do not hesitate to tell me if there is something to fix.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK