[Add] Comments to base64.
This commit is contained in:
parent
a064eec5eb
commit
97baac1c3e
16
src/base64.c
16
src/base64.c
@ -2,9 +2,9 @@
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
|
||||
// Encode table.
|
||||
// Encode table - base64 alphabet is defined by the rfc
|
||||
static const char cb64[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
// Decode table.
|
||||
// Generate decode table at compile time.
|
||||
#define B64(_) \
|
||||
((_) == 'A' ? 0 \
|
||||
: (_) == 'B' ? 1 \
|
||||
@ -72,6 +72,7 @@ static const char cb64[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwx
|
||||
: (_) == '/' ? 63 \
|
||||
: -1)
|
||||
|
||||
// Makes it much faster.
|
||||
static const signed char cd64[256] = {
|
||||
B64(0), B64(1), B64(2), B64(3),
|
||||
B64(4), B64(5), B64(6), B64(7),
|
||||
@ -180,6 +181,7 @@ char* base64_encode(size_t* len, char* src, size_t sz) {
|
||||
|
||||
for(c = 0; c < pad; c++)
|
||||
r[i-c-1] = '=';
|
||||
// It'll be a valid string.
|
||||
r[i] = '\0';
|
||||
(*len) = i;
|
||||
|
||||
@ -212,19 +214,23 @@ char* base64_decode(size_t* len, char* src, size_t sz) {
|
||||
j = 0;
|
||||
for(i = 0; i < sz; i++) {
|
||||
if(src[i] == '=')
|
||||
// Control padding.
|
||||
pad++;
|
||||
if(dec_valid(src[i]))
|
||||
// Only allow valid characters.
|
||||
dat[j++] = src[i];
|
||||
}
|
||||
|
||||
// Fill r.
|
||||
i = 0;
|
||||
for(c = 0; c < j; c += 4) {
|
||||
n = dec_ch(dat[c+0]) << 18;
|
||||
n += (c+1<j) ? (dec_ch(dat[c+1]) << 12) : 0;
|
||||
// Process the input from base 64.
|
||||
n = dec_ch(dat[c+0]) << 18; // Guaranteed to be valid.
|
||||
n += (c+1<j) ? (dec_ch(dat[c+1]) << 12) : 0; // Check if in bounds.
|
||||
n += (c+2<j) ? (dec_ch(dat[c+2]) << 6) : 0;
|
||||
n += (c+3<j) ? (dec_ch(dat[c+3]) << 0) : 0;
|
||||
|
||||
// Convert the 24 bits of encoded data into 3 8 bit chunks.
|
||||
r[i++] = (n >> 16) & 255;
|
||||
r[i++] = (n >> 8) & 255;
|
||||
r[i++] = (n >> 0) & 255;
|
||||
@ -234,7 +240,7 @@ char* base64_decode(size_t* len, char* src, size_t sz) {
|
||||
// Cleanup.
|
||||
free(dat);
|
||||
|
||||
(*len) = i - pad;
|
||||
(*len) = i - pad; // Must decount the padding.
|
||||
return r;
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user