summary refs log tree commit diff
diff options
context:
space:
mode:
authortzlil <tzlils@protonmail.com>2023-09-26 03:09:22 +0300
committertzlil <tzlils@protonmail.com>2023-09-26 03:09:22 +0300
commit101e6f1f8090a707f24112bdeb12655a76b2ffc8 (patch)
treef82f280210ed2279bf027d5bcd3157dd3af56deb
parent50e0817bff003d9bfe1cca6f9c5ea4c7b68fb332 (diff)
padding padding
-rw-r--r--base64.joy37
1 files changed, 24 insertions, 13 deletions
diff --git a/base64.joy b/base64.joy
index 0aa97b4..f5216c4 100644
--- a/base64.joy
+++ b/base64.joy
@@ -12,18 +12,29 @@ b64enc2 == "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" sw
 
 s2l == [null]  [pop []]  [uncons]  [cons]  linrec;
 b64enc ==
-	s2l
-	"" swap
-	# pad with null bytes
-	# calculate how many bytes to pad
-	[size 3 rem 3 swap - 3 rem] nullary
-	# i cant use null bytes in strings (hence s2l)
-	[0 chr [] cons concat] times
-	# len(s)/3 times
-	[size 3 /] nullary
-	[[3 take] nullary s2l [b64enc1 b64enc2] infra first rollup [swap concat] dip 3 drop] times
-	# remove the now-empty string
-	pop
-	"\n" concat
+	  s2l
+          "" swap
+	  # pad with null bytes
+          # calculate how many bytes to pad
+	  [size 3 rem 3 swap - 3 rem] nullary
+	  # save the amount for later
+	  dup [swap] dip [[swap] dip] dip
+	  # i cant use null bytes
+	  [0 chr [] cons concat] times
+	  # len(s)/3 times
+	  [size 3 /] nullary
+	  [[3 take] nullary s2l [b64enc1 b64enc2] infra first rollup [swap concat] dip 3 drop] times
+	  # remove the now-empty string
+	  pop
+	  # add the padding
+	  # encoded characters - characters that need to be padded
+	  [size] nullary swapd [swap -] unary
+	  # take only the non padded characters
+	  swapd take
+	  # add back as many ='s as you took
+
+	  # for some reason this part crahes joy with a malloc error if the input is more than 20 characters
+	  swap ["=" concat] times
+	  "\n" concat
 END
 stdin [feof not] [fgets b64enc putchars] while fclose.