add man page and unit tests for scan_base64url

This commit is contained in:
leitner
2017-07-30 13:41:43 +00:00
parent 8d449d442b
commit c8156a9841
5 changed files with 103 additions and 35 deletions

View File

@@ -15,17 +15,36 @@ static inline int dec(unsigned char x) {
size_t scan_base64url(const char *src,char *dest,size_t *destlen) {
unsigned short tmp=0,bits=0;
register const unsigned char* s=(const unsigned char*) src;
const char* orig=dest;
for (;;) {
size_t i,j=0;
for (i=0;;) {
int a=dec(*s);
if (a<0) break;
if (a<0) break; /* base64url does not have padding */
tmp=(tmp<<6)|a; bits+=6;
++s;
if (bits>=8) {
*dest=(tmp>>(bits-=8));
++dest;
bits-=8;
if (dest) dest[i]=(tmp>>bits);
++i;
}
}
*destlen=dest-orig;
if (destlen) *destlen=i;
return (const char*)s-src;
}
#ifdef UNITTEST
#include <assert.h>
#include <string.h>
#include <stdio.h>
int main() {
char buf[100];
size_t i,l;
/* check that we don't consume padding */
memset(buf,0,10); assert(scan_base64url("Zm5vcmQ=",buf,&l)==7 && l==5 && !memcmp(buf,"fnord",6));
/* check that we don't insist on the padding */
memset(buf,0,10); assert(scan_base64url("Zm5vcmQ",buf,&l)==7 && l==5 && !memcmp(buf,"fnord",6));
/* check the special non-isalnum chars :) */
memset(buf,0,10); assert(scan_base64url("_-8=",buf,&l)==3 && l==2 && !memcmp(buf,"\xff\xef",3));
return 0;
}
#endif