From 383f9426f440ef0b8b6e0e712453b738a06722f6 Mon Sep 17 00:00:00 2001 From: Ian Jackson Date: Sun, 17 Nov 2019 11:41:04 +0000 Subject: [PATCH 1/1] Provide maxlen functions These make it much easier to write callers! I have chosen not to try to deal with "large" input values and instead write a calculation that would overflow and document the limitation. Handling those large values is fiddle and left for a future enhancement. Signed-off-by: Ian Jackson --- base91.c | 25 +++++++++++++++++++++++++ base91.h | 4 ++++ 2 files changed, 29 insertions(+) diff --git a/base91.c b/base91.c index 3d9d7ea..d1877e9 100644 --- a/base91.c +++ b/base91.c @@ -113,6 +113,18 @@ size_t basE91_encode_end(struct basE91 *b, void *o) return n; } +/* return maximum length that an input of length i could encode to + * (this is a maximum, not a precise figure, because the actual + * size depends on the precise data */ + +size_t basE91_encode_maxlen(size_t i /* must be < SIZE_T_MAX/8 */) +{ + size_t bits = i*8; + size_t pairs = bits / 13; + size_t leftover = bits % 13; + return 2*pairs + (leftover==0 ? 0 : leftover<=6 ? 1 : 2); +} + size_t basE91_decode(struct basE91 *b, const void *i, size_t len, void *o) { const unsigned char *ib = i; @@ -157,3 +169,16 @@ size_t basE91_decode_end(struct basE91 *b, void *o) return n; } + +/* return maximum length that an input of length i could decode to + * (this is a maximum, not a precise figure, because the actual + * size depends on the precise data */ + +size_t basE91_decode_maxlen(size_t i /* must be < SIZE_T_MAX/7 */) +{ + size_t pairs = i / 2; + size_t bits = pairs * 14; + size_t bytes = bits / 8; + size_t leftover = i % 2; + return bytes + !!leftover; +} diff --git a/base91.h b/base91.h index 7a44a60..b298017 100644 --- a/base91.h +++ b/base91.h @@ -21,8 +21,12 @@ size_t basE91_encode(struct basE91 *, const void *, size_t, void *); size_t basE91_encode_end(struct basE91 *, void *); +size_t basE91_encode_maxlen(size_t /* must be < SIZE_T_MAX/8 */); + size_t basE91_decode(struct basE91 *, const void *, size_t, void *); size_t basE91_decode_end(struct basE91 *, void *); +size_t basE91_decode_maxlen(size_t /* must be < SIZE_T_MAX/7 */); + #endif /* base91.h */ -- 2.30.2