Skip to content

CStr::from_bytes_with_nul returns non-actionable error result #493

Closed
@nyurik

Description

@nyurik

Proposal

Problem statement

One of CStr constructors, CStr::from_bytes_with_nul(bytes: &[u8]) handles 3 cases:

  1. bytes has one NULL as the last value - creates CStr
  2. bytes has no NULL - error
  3. bytes has a NULL in some other position - error

The 3rd case is error that may require lossy conversion, but the 2nd case can easily be handled by the user code. Unfortunately, this function returns an opaque FromBytesWithNulError error in both 2nd and 3rd case, so the user cannot detect just the 2nd case - having to re-implement the entire function and bring in the memchr dependency.

Motivating examples or use cases

In this code, my FFI code needs to copy user's &[u8] into a C-allocated memory blob in a NUL-terminated CStr format. My code must first validate if &[u8] has a trailing NUL (case 1), no NUL (adds one on the fly - case 2), or NUL in the middle (3rd case - error). I had to re-implement from_bytes_with_nul and add memchrdependency just to handle the 2nd case.

Solution sketch

It may make sense to do one of these:

  • stabilize the kind of the error this function returns - so it can be examined
  • introduce a new function that returns validation result for all 3 cases
  • something else?

CStr::validate_bytes(value: &[u8]) -> CStrValidation -- returns an enum with valid, NotNulTerminated, InteriorNul

Metadata

Metadata

Assignees

No one assigned

    Labels

    ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions