diff --git a/base64/base64.c b/base64/base64.c index 7cb907a..abbfdb6 100644 --- a/base64/base64.c +++ b/base64/base64.c @@ -39,7 +39,8 @@ static const uint8_t base64_decode_map[] = { // todo: fix encoding for strings with length < 3 const char *const base64_encode(const uint8_t *const data, size_t data_size) { const size_t remaining = data_size % 3; - const size_t base64_len = ceil(((double)data_size * 8) / 6) + 1; + const size_t base64_len = + ((double)data_size * 8) / 6 + 4 /* maximum padding + null char */; char *result = malloc(base64_len); if (!result) { return NULL; diff --git a/base64/maintest.c b/base64/maintest.c index 71a0ad6..cee6bcb 100644 --- a/base64/maintest.c +++ b/base64/maintest.c @@ -5,7 +5,7 @@ #include int main(void) { - const char *decodee = "light w"; + const char *decodee = "this is some long sentence to be encoded in base64."; char *encoded = (char *)base64_encode((uint8_t *)decodee, strlen(decodee)); char *decoded = (char *)base64_decode(encoded, strlen(encoded)); assert(strcmp(decodee, decoded) == 0); @@ -13,33 +13,27 @@ int main(void) { free((void *)encoded); free((void *)decoded); - // ------- - - encoded = (char *)base64_encode((uint8_t *)"Man", 3); - assert(strcmp(encoded, "TWFu") == 0); - decoded = (char *)base64_decode(encoded, strlen(encoded)); - assert(strcmp(decoded, "Man") == 0); - free((void *)encoded); - free((void *)decoded); - - // ------ - - encoded = (char *)base64_encode((uint8_t *)"light work.", 11); - assert(strcmp(encoded, "bGlnaHQgd29yay4=") == 0); - decoded = (char *)base64_decode(encoded, strlen(encoded)); - assert(strcmp(decoded, "light work.") == 0); - free((void *)encoded); - free((void *)decoded); - // ------ - // todo: still crashing atm as function fails for args with len < 3 - // encoded = (char *)base64_encode((uint8_t *)"ma", 2); - // assert(strcmp(encoded, "TWE=") == 0); - // decoded = (char *)base64_decode(encoded, strlen(encoded)); - // assert(strcmp(decoded, "TWE=") == 0); - // free((void *)encoded); - // free((void *)decoded); + struct { + char *encoded; + char *decoded; + } res[] = { + {.decoded = "Man", .encoded = "TWFu"}, + {.decoded = "light work.", .encoded = "bGlnaHQgd29yay4="}, + {.decoded = "ma", .encoded = "bWE="}, + }; + + for (size_t i = 0; i < sizeof(res) / sizeof(res[0]); i++) { + encoded = (char *)base64_encode((uint8_t *)res[i].decoded, + strlen(res[i].decoded)); + assert(strcmp(encoded, res[i].encoded) == 0); + decoded = (char *)base64_decode(encoded, strlen(encoded)); + assert(strcmp(decoded, res[i].decoded) == 0); + + free(encoded); + free(decoded); + } puts("tests passed."); return 0;