Rust: CStr should have a function like from_bytes_with_nul() that reads until the first '\0'

Created on 17 Mar 2018  路  5Comments  路  Source: rust-lang/rust

When dealing with FFI (fixed char buffers in file formats that represent strings and passing fixed char buffers to C code to write chars to them up to a given max len) I often find myself doing this:

let end = s.iter().position(|&b| b == 0).map_or(0, |i| i + 1);
CStr::from_bytes_with_nul(&s[..end])

Because if I pass the whole slice to it, it returns a FromBytesWithNulError.
There should be a function that combines both lines and read until the first '\0' byte in the slice.

Something like:

CStr::from_bytes_until_nul(slice)

And yes, I did write my own function for my use case but I find myself copying these two lines around into different projects dealing with FFI and I think it would make sense to have this (arguably) "basic functionality" in std's CStr :)

C-feature-request T-libs

Most helpful comment

That's a bit sad and problematic that such a basic functionality isn't implemented on CStr directly...

All 5 comments

This has been proposed before as #20475, and closed because this is already supported by the package c_fixed_string.

That's a bit sad and problematic that such a basic functionality isn't implemented on CStr directly...

Why does from_bytes_with_nul accept &[u8], whereas char by default is signed?

@kanekv are you talking about in C? Because in C char's sign is undefined. We use u8 because we treat them as bytes -- which are treated as unsigned 8 bit numbers.

@kennytm is there a possibility to accept such function inside CStr and not rely on a package for that ?
This is really a basic thing to have for any person that is dealing with fixed size char arrays, I totally agree with @GuillaumeGomez

Was this page helpful?
0 / 5 - 0 ratings