Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

String: add from_utf8 #399

Merged
merged 1 commit into from
Oct 30, 2023
Merged

String: add from_utf8 #399

merged 1 commit into from
Oct 30, 2023

Conversation

newAM
Copy link
Member

@newAM newAM commented Oct 30, 2023

Closes #378

Leverages the error type from core::str::from_utf8, but it takes a heapless::Vec as an argument similar to core::String::from_utf8 to avoid allocation errors.

I figured we may as well add the unsafe version too for completeness.

@Dirbaio
Copy link
Member

Dirbaio commented Oct 30, 2023

if this is going to copy the bytes anyway, wouldn't it be better to take &[u8]? this way the source of bytes can be something other than a Vec.

(the std method takes a Vec because it can convert the allocatino from Vec to String, without copying)

@newAM
Copy link
Member Author

newAM commented Oct 30, 2023

If it takes bytes: &[u8] then it can run into an allocation error when bytes.len() > N.

Several options:

  1. Leave it as-is, for converting from &[u8] the user calls Vec::from_slice followed by String::from_utf8, with each of those having a single error type.
  2. Add an error enum with two variants for Utf8Error and bytes.len() > N.
  3. Map the Utf8Error onto () to simplify the error type, users can leverage external methods for handling UTF-8 errors.

It's sadly not very ergonomic with any option, I prefer 1, but 2/3 (or another option) would be fine by me. What do you think?

@Dirbaio
Copy link
Member

Dirbaio commented Oct 30, 2023

ah true I didn't think about capacity errors. Sounds good to me then. We can always add from_utf8_slice in the future.

@Dirbaio Dirbaio added this pull request to the merge queue Oct 30, 2023
Merged via the queue into rust-embedded:main with commit ccd3801 Oct 30, 2023
69 checks passed
@newAM newAM deleted the string-from-utf8 branch October 30, 2023 23:33
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.

String::from_utf8?
2 participants