libutil

C Utility Library
git clone http://git.omkov.net/libutil
Log | Tree | Refs | README | LICENCE | Download

AuthorJamozed <[email protected]>
Date2021-02-20 06:08:39
Commit9e513ff3f61acf440fe77875e05f90ba864dbccc
Parent32a9a7435816cb3b29f5ce27d61fc12ba6d3aaf7

base64: Simplify b64decode function

Diffstat

M src/base64.c | 34 ++++++++++++++++++----------------
M src/base64.h | 2 +-

2 files changed, 19 insertions, 17 deletions

diff --git a/src/base64.c b/src/base64.c
index 2714040..c6d92e7 100644
--- a/src/base64.c
+++ b/src/base64.c
@@ -1,4 +1,4 @@
-// base64.c, version 1.1.1
+// base64.c, version 1.1.2
 // Base64 source file for OMKOV lib
 // Copyright (C) 2021, Jakob Wakeling
 // All rights reserved.
@@ -70,25 +70,27 @@ size_t b64encode(uint8_t *dst, uint8_t *src, size_t len) {
 
 /* Decode Base64 */
 size_t b64decode(uint8_t *dst, uint8_t *src, size_t len) {
-	if (!len) { return 0; }
-	
-	register uint8_t *o = dst;
-	
-	bool pad1 = len % 4 || src[len - 1] == '=';
-	bool pad2 = pad1 && (len % 4 > 2 || src[len - 2] != '=');
+	register uint8_t *i = src, *o = dst;
 
-	size_t end = (len - pad1) / 4 << 2;
+	for (; src[len - 1] == '='; --len);
 
-	for (size_t j = 0; j != end; j += 4) {
-		*o++ = B64D[src[j + 0]] << 2 | B64D[src[j + 1]] >> 4;
-		*o++ = B64D[src[j + 1]] << 4 | B64D[src[j + 2]] >> 2;
-		*o++ = B64D[src[j + 2]] << 6 | B64D[src[j + 3]];
+	for (; len >= 4; len -= 4) {
+		*o++ = (B64D[i[0]] << 2) | (B64D[i[1]] >> 4);
+		*o++ = (B64D[i[1]] << 4) | (B64D[i[2]] >> 2);
+		*o++ = (B64D[i[2]] << 6) | (B64D[i[3]]); i += 4;
 	}
 
-	if (pad1) {
-		int n = B64D[src[end]] << 18 | B64D[src[end + 1]] << 12; *o++ = n >> 16;
-		if (pad2) { n |= B64D[src[end + 2]] << 6; *o++ = n >> 8 & 0xFF; }
-    }
+	switch (len) {
+	case 2: {
+		*o++ = (B64D[i[0]] << 2) | (B64D[i[1]] >> 4);
+		*o++ = (B64D[i[1]] << 4); break;
+	}
+	case 3: {
+		*o++ = (B64D[i[0]] << 2) | (B64D[i[1]] >> 4);
+		*o++ = (B64D[i[1]] << 4) | (B64D[i[2]] >> 2);
+		*o++ = (B64D[i[2]] << 6); break;
+	}
+	}
 
 	return o - dst;
 }
diff --git a/src/base64.h b/src/base64.h
index 008e600..203b02b 100644
--- a/src/base64.h
+++ b/src/base64.h
@@ -1,4 +1,4 @@
-// base64.h, version 1.1.1
+// base64.h, version 1.1.2
 // Base64 header file for OMKOV lib
 // Copyright (C) 2021, Jakob Wakeling
 // All rights reserved.