Skip to content

Commit

Permalink
FEAT: improving DEBASE so it can decode URL safe Base64 variant input…
Browse files Browse the repository at this point in the history
… even without using a /url refinement

relates to: metaeducation/rebol-issues#2318

Previously this would throw an error:

```
>> debase "qL8R4QIcQ_ZsRqOAbeRfcZhilN_MksRtDaErMA=="
** Script error: data not in correct format: "qL8R4QIcQ_ZsRqOAbeRfcZhilN_MksRtDaErMA=="
```

The reason is that the input is using URL safe alphabet. With this commit when such a situation is detected, the decoder restarts itself automatically as if it would be used with /url refinement.

NOTE: if you are sure that input should be in URL safe format, use the refinement to avoid unnecessary computations.

Possible test:
```
key: "qL8R4QIcQ_ZsRqOAbeRfcZhilN_MksRtDaErMA=="
equal? (debase key) (debase/url key) ;== should be TRUE
```
  • Loading branch information
Oldes committed Sep 1, 2018
1 parent a01c683 commit b54e1b8
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions src/core/f-enbase.c
Original file line number Diff line number Diff line change
Expand Up @@ -410,16 +410,20 @@
{
REBYTE *bp;
REBYTE *cp;
REBCNT flip = 0;
REBINT accum = 0;
REBCNT flip, pos;
REBINT accum;
REBYTE lex;
REBSER *ser;

// Allocate buffer large enough to hold result:
// Accounts for e bytes decoding into 3 bytes.
ser = Make_Binary(((len + 3) * 3) / 4);

start:
bp = STR_HEAD(ser);
cp = *src;
accum = 0;
flip = 0;

const REBYTE *table;
if (urlSafe) {
Expand All @@ -428,7 +432,7 @@
table = Debase64;
}

for (; len > 0; cp++, len--) {
for (pos = len; pos > 0; cp++, pos--) {

// Check for terminating delimiter (optional):
if (delim && *cp == delim) break;
Expand All @@ -455,14 +459,14 @@
} else {
// Special padding: "="
cp++;
len--;
pos--;
if (flip == 3) {
*bp++ = (REBYTE)(accum >> 10);
*bp++ = (REBYTE)(accum >> 2);
flip = 0;
}
else if (flip == 2) {
if (!Skip_To_Char(cp, cp + len, '=')) goto err;
if (!Skip_To_Char(cp, cp + pos, '=')) goto err;
cp++;
*bp++ = (REBYTE)(accum >> 4);
flip = 0;
Expand All @@ -471,7 +475,15 @@
break;
}
}
else if (lex == BIN_ERROR) goto err;
else if (lex == BIN_ERROR) {
if(!urlSafe && (*cp == '-' || *cp == '_')) {
// there was found char, which is used in URL safe encoding, but we are in simple Base64 mode,
// so try to decode it using safe table, instead of throwing an error immediately.
urlSafe = TRUE;
goto start;
}
goto err;
}
}

if(flip==2) {
Expand Down

0 comments on commit b54e1b8

Please sign in to comment.