marshallpierce / rust-base64

base64, in rust
Apache License 2.0
606 stars 113 forks source link

`encode_engine_slice` should probably return a `&str` instead of `usize` #209

Open upsuper opened 1 year ago

upsuper commented 1 year ago

I suggest that encode_engine_slice should have a signature like

pub fn encode_engine_slice<'a, E: Engine, T: AsRef<[u8]>>(
    input: T,
    output_buf: &'a mut [u8],
    engine: &E
) -> &'a mut str;

Apparently the encoded result is always a valid string, but the current API leaves a dilemma for some users:

If encode_engine_slice can return a str, that dilemma would be resolved. The length can still be derived from .len() of the returned str.

There is also a precedent in the Rust std: char::encode_utf8 encodes into a buffer and returns a str.

This is a breaking change, though.

marshallpierce commented 1 year ago

Unfortunately this isn't really viable as far as I can tell.

upsuper commented 1 year ago

It seems that encode_engine already does a UTF-8 check on the output.

I wonder if I can build a crate around ASCII chars which exposes a safe API to construct ASCII strings, would you accept a PR making use of that to eliminate the checks?

Nugine commented 1 year ago

base64_simd::Base64::encode_as_str is exactly what you want. base64-simd also supports encoding/decoding with an uninitialized buffer, which is relatively difficult for a 100%-safe library.

upsuper commented 1 year ago

@Nugine That looks great. I'll give it a try. Thanks!