hare

[hare] The Hare programming language
git clone https://git.torresjrjr.com/hare.git
Log | Files | Refs | README | LICENSE

commit a8d9063e6095ddad0d5083647f70a614b46189fd
parent 69546d86a7a9ac6fab8083b35145daf27030cd5e
Author: Bor Grošelj Simić <bgs@turminal.net>
Date:   Wed, 26 Apr 2023 13:47:21 +0200

encoding::base64: add utility functions for buffer size calculations

Diffstat:
Mencoding/base64/base64.ha | 23+++++++++++++++++++++++
1 file changed, 23 insertions(+), 0 deletions(-)

diff --git a/encoding/base64/base64.ha b/encoding/base64/base64.ha @@ -534,3 +534,26 @@ export fn decode( assert(decodestr(invalid[i].1, invalid[i].0) is errors::invalid); }; }; + +// Given the length of the message, returns the size of its base64 encoding +export fn encodedsize(sz: size) size = if (sz == 0) 0 else ((sz - 1)/ 3 + 1) * 4; + +// Given the size of base64 encoded data, returns maximal length of decoded message. +// The message may be at most 2 bytes shorter than the returned value. Input +// size must be a multiple of 4. +export fn decodedsize(sz: size) size = { + assert(sz % 4 == 0); + return sz / 4 * 3; +}; + +@test fn sizecalc() void = { + let enc: [_](size, size) = [(1, 4), (2, 4), (3, 4), (4, 8), (10, 16), + (119, 160), (120, 160), (121, 164), (122, 164), (123, 164) + ]; + assert(encodedsize(0) == 0 && decodedsize(0) == 0); + for (let i = 0z; i < len(enc); i += 1) { + let (decoded, encoded) = enc[i]; + assert(encodedsize(decoded) == encoded); + assert(decodedsize(encoded) == ((decoded - 1) / 3 + 1) * 3); + }; +};