chiark / gitweb /
Provide maxlen functions
authorIan Jackson <ijackson@chiark.greenend.org.uk>
Sun, 17 Nov 2019 11:41:04 +0000 (11:41 +0000)
committerIan Jackson <ijackson@chiark.greenend.org.uk>
Sun, 17 Nov 2019 11:41:04 +0000 (11:41 +0000)
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 <ijackson@chiark.greenend.org.uk>
base91.c
base91.h

index 3d9d7eaab6294bffff9bb152b5128c2b8f4820b9..d1877e997554ff8e78efac278794a70489dcbdc4 100644 (file)
--- 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;
+}
index 7a44a60b357e749b24d543d12473977c74b4acb1..b298017784578004f62e5702fe7a6b3e8050d4f4 100644 (file)
--- 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 */