Skip to content

Commit

Permalink
base32: update base32 api
Browse files Browse the repository at this point in the history
Update the base32 api to be consistent with the recent changes to the
base64 api introduced by commit 6010183 ("Updated base64 encoding
api").
  • Loading branch information
konimarti authored and lerno committed Nov 25, 2024
1 parent b0c0fd7 commit 8d03aaf
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
40 changes: 40 additions & 0 deletions lib/std/encoding/base32.c3
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,37 @@ const Alphabet STD_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
// Extended Hex Alphabet
const Alphabet HEX_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUV";

fn String! encode_buffer(char[] code, char[] buffer)
{
@check_coder(std_encoder);
return (String)buffer[:std_encoder.encode(code, buffer)!];
}

fn char[]! decode_buffer(char[] code, char[] buffer)
{
@check_coder(std_decoder);
return buffer[:std_decoder.decode(code, buffer)!];
}

fn String! encode(char[] code, Allocator allocator)
{
@check_coder(std_encoder);
char[] data = allocator::alloc_array(allocator, char, std_encoder.encode_len(code.len));
return (String)data[:std_encoder.encode(code, data)!];
}

fn char[]! decode(char[] code, Allocator allocator)
{
@check_coder(std_decoder);
char[] data = allocator::alloc_array(allocator, char, std_decoder.decode_len(code.len));
return data[:std_decoder.decode(code, data)!];
}

fn String! encode_new(char[] code) @inline => encode(code, allocator::heap());
fn String! encode_temp(char[] code) @inline => encode(code, allocator::temp());
fn char[]! decode_new(char[] code) @inline => decode(code, allocator::heap());
fn char[]! decode_temp(char[] code) @inline => decode(code, allocator::temp());

const uint MASK @private = 0b11111;
const char INVALID @private = 0xff;

Expand Down Expand Up @@ -308,3 +339,12 @@ fn void! Alphabet.validate(&self, int padding)
}
}
}

tlocal Base32Encoder std_encoder @local;
tlocal Base32Decoder std_decoder @local;

macro @check_coder(#coder) @local
{
if (#coder.alphabet == STD_ALPHABET) return;
#coder.init(STD_ALPHABET, '=')!!;
}
15 changes: 15 additions & 0 deletions test/unit/stdlib/encoding/base32.c3
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,18 @@ fn void decode_nopadding()
decode_tests(std_tests, base32::STD_ALPHABET, -1);
decode_tests(hex_tests, base32::HEX_ALPHABET, -1);
}

fn void! base32_api()
{
@pool()
{
foreach (t : std_tests)
{
String got = base32::encode_temp(t.dec)!;
assert(got == t.enc, "got: %s, want: %s", got, t.enc);

char[] got_chars = base32::decode_temp(t.enc)!;
assert(got_chars == t.dec, "got: %s, want: %s", got_chars, t.dec);
}
};
}

0 comments on commit 8d03aaf

Please sign in to comment.