lib/core: Renamed `Text::bytelen` to `Text::byte_length`
[nit.git] / lib / base64.nit
index cb73b3b..0ba5c30 100644 (file)
@@ -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
                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
 
@@ -156,7 +163,7 @@ redef class String
        # If using the default padding character `=`, see `encode_base64`.
        fun encode_base64(padding: nullable Byte): String
        do
-               return to_cstring.encode_base64(bytelen, padding).to_s
+               return to_cstring.encode_base64(byte_length, padding).to_s
        end
 
        # Decodes the receiver string to base64 using a custom padding character.
@@ -164,6 +171,6 @@ redef class String
        # Default padding character `=`
        fun decode_base64(padding : nullable Byte) : String
        do
-               return to_cstring.decode_base64(bytelen, padding).to_s
+               return to_cstring.decode_base64(byte_length, padding).to_s
        end
 end