From 444299b86e41897b368a73b039a7065677eb7127 Mon Sep 17 00:00:00 2001 From: Erik Ekman Date: Tue, 17 Feb 2009 20:40:40 +0000 Subject: [PATCH] #51 handle one block encode/decode for base32 --- src/base32.c | 9 ++++++--- tests/base32.c | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/src/base32.c b/src/base32.c index af6a214..06a59fe 100644 --- a/src/base32.c +++ b/src/base32.c @@ -103,9 +103,12 @@ base32_encode(char *buf, size_t *buflen, const void *data, size_t size) memset(buf, 0, *buflen); /* how many chars can we encode within the buf */ - maxsize = BLKSIZE_RAW * (*buflen / BLKSIZE_ENC - 1) - 1; + maxsize = BLKSIZE_RAW * (*buflen / BLKSIZE_ENC); /* how big will the encoded data be */ - newsize = BLKSIZE_ENC * (size / BLKSIZE_RAW + 1) + 1; + newsize = BLKSIZE_ENC * (size / BLKSIZE_RAW); + if (size % BLKSIZE_RAW) { + newsize += BLKSIZE_ENC; + } /* if the buffer is too small, eat some of the data */ if (*buflen < newsize) { size = maxsize; @@ -132,7 +135,7 @@ base32_encode(char *buf, size_t *buflen, const void *data, size_t size) /* store number of bytes from data that was used */ *buflen = size; - return strlen(buf) - 1; + return strlen(buf); } #define DECODE_ERROR 0xffffffff diff --git a/tests/base32.c b/tests/base32.c index 0b77a03..9ff0cf7 100644 --- a/tests/base32.c +++ b/tests/base32.c @@ -85,6 +85,48 @@ START_TEST(test_base32_5to8_8to5) } END_TEST +START_TEST(test_base32_blksize) +{ + size_t rawlen; + size_t enclen; + char *rawbuf; + char *encbuf; + struct encoder *b32; + int i; + int val; + + b32 = get_base32_encoder(); + + rawlen = b32->blocksize_raw(); + enclen = b32->blocksize_encoded(); + + rawbuf = malloc(rawlen + 16); + encbuf = malloc(enclen + 16); + + for (i = 0; i < rawlen; i++) { + rawbuf[i] = 'A'; + } + rawbuf[i] = 0; + + val = b32->encode(encbuf, &enclen, rawbuf, rawlen); + + fail_unless(rawlen == 5, "raw length was %d not 5", rawlen); + fail_unless(enclen == 5, "encoded %d bytes, not 5", enclen); + fail_unless(val == 8, "encoded string %s was length %d", encbuf, val); + + memset(rawbuf, 0, rawlen + 16); + + enclen = val; + val = b32->decode(rawbuf, &rawlen, encbuf, enclen); + + fail_unless(rawlen == 5, "raw length was %d not 5", rawlen); + fail_unless(val == 5, "val was not 5 but %d", val); + for (i = 0; i < rawlen; i++) { + fail_unless(rawbuf[i] == 'A'); + } +} +END_TEST + TCase * test_base32_create_tests() { @@ -94,6 +136,7 @@ test_base32_create_tests() tcase_add_loop_test(tc, test_base32_encode, 0, TUPLES); tcase_add_loop_test(tc, test_base32_decode, 0, TUPLES); tcase_add_test(tc, test_base32_5to8_8to5); + tcase_add_test(tc, test_base32_blksize); return tc; }