Skip to content

Add SecretBox::from_utf8 and related methods - #1364

Open
mrdomino wants to merge 11 commits into
iqlusioninc:mainfrom
mrdomino:add-utf8-methods
Open

Add SecretBox::from_utf8 and related methods#1364
mrdomino wants to merge 11 commits into
iqlusioninc:mainfrom
mrdomino:add-utf8-methods

Conversation

@mrdomino

@mrdomino mrdomino commented Mar 14, 2026

Copy link
Copy Markdown

These methods allow converting a SecretBox<[u8]> into a SecretString without creating a new allocation. Also adds a new FromUtf8Error type, similar to (and in fact wrapping) the one returned by String::from_utf8, except that this one zeroizes its buffer on return.

I made the choice here to provide this functionality via functions declared directly on impl SecretString (i.e., impl SecretBox<str>) rather than via, say, impl TryFrom<Vec<u8>> for SecretString. Either approach would probably work; two arguments in favor of the one taken:

  1. This follows the existing String API.
  2. We would not be able to implement from_utf8_box_len, except maybe via a contrived TryFrom<(SecretBox<[u8]>, usize)>.

These methods allow converting a `SecretBox<[u8]>` into a `SecretString`
without copies. They are both based on a new `TryFrom<Vec<u8>>` for
`SecretString`.
I, Steven Dee, hereby agree to license all contributions I make
to this project under the terms of the Apache License, Version 2.0.
@mrdomino

Copy link
Copy Markdown
Author

Just read CONTRIBUTORS.md and added my name to AUTHORS.md.

I decided the `impl TryFrom<Vec<u8>>` was too cheesy and instead just
called that method `SecretString::from_utf8`, with different variants
for `from_utf8_box` or `from_utf8_box_len`.
Specify the actual path from `Box<[u8]>` to `SecretString` with a copy.
Puts the new methods next to the other `SecretString` trait impls.
Derives `Debug`, `Display`, and `Error` on `FromUtf8Error`.
Drops Clone (which is only derived on `no_global_oom_handling`) and adds
`PartialEq` + `Eq`.
@mrdomino

Copy link
Copy Markdown
Author

Coming back to this: is there any interest in anything in the general area of this? Very open to discussing changes to the proposed API. Also fine with “no, we don’t want anything like this” as an answer; extra copies are not the worst thing in the world.

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.

1 participant