decodeBase64

Decode a Base64 encoded value, appending the result onto a Vec!ubyte. Reusing the same Vec!ubyte allows you to avoid reallocations. Note: err must point to a bool and cannot be null. Ugly signature sorry.

  1. ubyte[] decodeBase64(const(ubyte)[] data, char plusChar, char slashChar)
  2. ubyte[] decodeBase64(const(char)[] data, char plusChar, char slashChar)
  3. void decodeBase64(const(ubyte)[] data, Vec!ubyte outBuffer, char plusChar, char slashChar, bool* err)
    nothrow @nogc @safe
    void
    decodeBase64
    (
    scope const(ubyte)[] data
    ,
    ref Vec!ubyte outBuffer
    ,,,
    bool* err
    )

Examples

Test decoding of data which has a length which can be cleanly decoded.

// Note: the decoded strings are leaked in this test.
assert("QUJD".decodeBase64 == "ABC");
assert("QQ==".decodeBase64 == "A");
assert("YSBiIGMgZCBlIGYgZyBoIGkgaiBrIGwgbSBuIG8gcCBxIHIgcyB0IHUgdiB3IHggeSB6".decodeBase64 
       == "a b c d e f g h i j k l m n o p q r s t u v w x y z");
assert("LCAuIDsgLyBbICcgXSBcID0gLSAwIDkgOCA3IDYgNSA0IDMgMiAxIGAgfiAhIEAgIyAkICUgXiAmICogKCApIF8gKyB8IDogPCA+ID8="
       .decodeBase64 == ", . ; / [ ' ] \\ = - 0 9 8 7 6 5 4 3 2 1 ` ~ ! @ # $ % ^ & * ( ) _ + | : < > ?");
assert("AAA=".decodeBase64 == "\x00\x00");
assert("AAAABBCC".decodeBase64 == "\x00\x00\x00\x04\x10\x82");
assert("AA==".decodeBase64 == "\x00");
assert("AA/=".decodeBase64 == "\x00\x0f");

Test decoding invalid data

void testFail(const(char)[] input) @trusted
{
    ubyte[] decoded = input.decodeBase64;
    assert(decoded is null);
    free(decoded.ptr);
}

testFail("===A");
testFail("A=");
testFail("AA=");
testFail("A=AA");
testFail("AA=A");
testFail("AA=A====");
testFail("=AAA");
testFail("AAA=QUJD");
// This fails because we don't allow extra padding (than what is necessary)
testFail("AA======");
// This fails because we don't allow padding before the end of the string (otherwise we'd 
// have a side-channel)
testFail("QU==QUJD");
testFail("QU======QUJD");
// Invalid data that's out of the alphabet
testFail("!@##@@!@");

Meta