X-Git-Url: http://nitlanguage.org diff --git a/lib/base64.nit b/lib/base64.nit index 4eae395..8f6565b 100644 --- a/lib/base64.nit +++ b/lib/base64.nit @@ -42,7 +42,7 @@ redef class NativeString # assert "string".encode_base64 == "c3RyaW5n" private fun encode_base64(length: Int, padding: nullable Byte): Bytes do var base64_bytes = once base64_chars - if padding == null then padding = '='.ascii.to_b + if padding == null then padding = '='.ascii var steps = length / 3 var bytes_in_last_step = length % 3 var result_length = steps * 4 @@ -78,15 +78,22 @@ redef class NativeString # Decodes `self` from base64 # # assert "c3RyaW5n".decode_base64 == "string" + # assert "c3Rya\nW5n".decode_base64 == "string" # # REQUIRE: `length % 4 == 0` private fun decode_base64(length: Int, padding: nullable Byte): Bytes do - if padding == null then padding = '='.ascii.to_b + if padding == null then padding = '='.ascii var inv = once inverted_base64_chars if length == 0 then return new Bytes.empty - assert length % 4 == 0 else print "base64::decode_base64 only supports strings of length multiple of 4" - var bytes = self + # Remove non-base64 chars + var bytes = new Bytes.with_capacity(length) + for k in [0 .. length[ do + var byte = self[k] + if inv.has_key(byte) or byte == padding then bytes.add(byte) + end + length = bytes.length + var steps = length / 4 var result_length = steps * 3