Skip to content

Conversation

@johann-cm
Copy link
Contributor

I would have liked to build the implementation upon safe functions, but all my attempts needed to check the no-interior-nul condition twice: once for trimming the input bytes slice, and once for safely extending the String with it.
Of course, by trimming the input bytes to the first nul byte, we already know that there are no interior nul bytes.
With unsafe code, we can make use of that knowledge and don't need to check again.

@sgued
Copy link
Contributor

sgued commented Nov 23, 2025

Thanks for the contribution.

Please add some tests (exercising all branches, not null terminated, null terminated, interior null, and with or without the capacity).

The behaviour here is net the same as CStr::from_bytes_until_null, which fails if there is no null (while here we add the null in that case). This could be confusing and I'm in favour of renaming it, or rejecting non-null terminated values. from_bytes_truncating_at_null is a bit verbose but clearer.
What do you think?

- rename from_bytes_until_nul to from_bytes_truncating_at_nul, in order
to aviod confusion with Cstr::from_bytes_until_nul, which errors on
non-nul terminated data. - add a test case for handling a nul-terminated
slice without interior nul bytes - improve documentation
@johann-cm
Copy link
Contributor Author

I've added one test case. As far as I can tell, all other cases are covered now by the doc-tests, or am I missing something?

I've renamed the method, in order to avoid confusion. I think adopting the CStr behavior of throwing an error on non-nul data is unnecessary here, because we copy the data and can just push a nul byte anyway. This eliminates one source of error for free.
In the doc-comment, I've made the differences to CStr::from_bytes_until_nul more explicit.

@sgued
Copy link
Contributor

sgued commented Nov 23, 2025

The current doc tests don't test the case where the null is not at the end.

@johann-cm
Copy link
Contributor Author

Okay, I see what you mean. I've tweaked one test to cover that case.

@sgued sgued enabled auto-merge November 25, 2025 19:41
@sgued sgued added this pull request to the merge queue Nov 25, 2025
Merged via the queue into rust-embedded:main with commit e79f79c Nov 25, 2025
21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants