Skip to content

Commit

Permalink
Move default base32 alphabet to EncodeBase32 function
Browse files Browse the repository at this point in the history
  • Loading branch information
pkulchenko committed Oct 9, 2023
1 parent 584345e commit df36caa
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
8 changes: 7 additions & 1 deletion net/http/base32.c
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ Apache License, Version 2.0\\n\
Copyright 2010 Google Inc.\"");
asm(".include \"libc/disclaimer.inc\"");

const char base32def[] = "0123456789abcdefghjkmnpqrstvwxyz";

int tobits(int b) {
int bits = 0; while (b && (b >>= 1)) bits++;
return bits;
Expand All @@ -38,9 +40,13 @@ int tobits(int b) {
char* EncodeBase32(const char *s, size_t sl,
const char *a, size_t al,
size_t *ol) {
unassert(2 <= al && al <= 256);
size_t count = 0;
char *r;
if (al == 0) {
a = base32def;
al = sizeof(base32def)/sizeof(a[0]);
}
unassert(2 <= al && al <= 128);
int bl = tobits(al);
int mask = (1 << bl) - 1;
*ol = (sl * 8 + bl - 1) / bl; // calculate exact output length
Expand Down
7 changes: 4 additions & 3 deletions tool/net/lfuncs.c
Original file line number Diff line number Diff line change
Expand Up @@ -609,9 +609,10 @@ int LuaEncodeBase32(lua_State *L) {
char *p;
size_t sl, al; // source/output and alphabet lengths
const char *s = luaL_checklstring(L, 1, &sl);
const char *a = luaL_optlstring(L, 2, "0123456789abcdefghjkmnpqrstvwxyz", &al);
if (al & (al - 1) || al > 256 || al < 2)
return luaL_error(L, "alphabet length is not a power of 2 in range 2..256");
// use an empty string, as EncodeBase32 provides a default value
const char *a = luaL_optlstring(L, 2, "", &al);
if (al & (al - 1) || al > 128 || al == 1)
return luaL_error(L, "alphabet length is not a power of 2 in range 2..128");
if (!(p = EncodeBase32(s, sl, a, al, &sl)))
return luaL_error(L, "out of memory");
lua_pushlstring(L, p, sl);
Expand Down

0 comments on commit df36caa

Please sign in to comment.