data-encoding icon indicating copy to clipboard operation
data-encoding copied to clipboard

Make `{encode,decode}_len` const fns?

Open oxalica opened this issue 2 years ago • 3 comments

When operating on fixed length hashes like SRI, it's great to use arrays on stack as buffers. But only constants and const-fns can be used in array length expressions, results in manual magic numbers like let buf = [0u8; 44] in code (base64 encoded length of SHA256 hash). With const-fns, we could possibly write let buf = [0u8; BASE64.encode_len(32)]; to make it clear.

oxalica avatar May 24 '23 01:05 oxalica

Thanks for the suggestion! I think it makes sense to do something like that however:

  1. I won't have time to work on it before mid June.
  2. I'm not sure it will be possible to have those functions const. If not I'll expose them in data-encoding-macro. Or if possible in nightly I'll add a feature.

I'll come back to this later.

ia0 avatar May 25 '23 05:05 ia0

As expected, making {encode,decode}_len const fns does not work for a few different reasons:

  • I use traits and it's not possible to have const fn in traits.
  • I use Cow (when the alloc feature is enabled) and rely on Deref which is not const.

So I'll go with the solution of making those functions macros in the data-encoding-macro crate. I'll only have time to look at this at the earliest this week-end though. I'll ping here when done.

ia0 avatar Jun 19 '23 20:06 ia0

You can test if #70 is fixing your issue. Instead of writing let buf = [0u8; BASE64.encode_len(32)]; as in your original comment, you would need to write let buf = [0u8; base64_encode_len!(32)]; instead. If that's useful, I'll merge and make a release.

ia0 avatar Jun 24 '23 13:06 ia0

Due to lack of activity I'm going to close this. This will eventually get fixed once const support in Rust is improved.

ia0 avatar Mar 30 '24 12:03 ia0