Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Add base-64 encoding of serialized output.
  • Loading branch information
jnthn committed Mar 9, 2013
1 parent 2a77c20 commit ffda411
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
49 changes: 49 additions & 0 deletions src/org/perl6/nqp/runtime/Base64.java
Expand Up @@ -3,6 +3,55 @@
import java.nio.ByteBuffer;

public class Base64 {
private static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();

/* This works around a lack of unsigned in Java. */
private static int deSign(byte b) {
if (b < 0)
return (int)b + 256;
else
return (int)b;
}

public static String encode(ByteBuffer buf)
{
int size = buf.capacity();
char[] str = new char[(size + 3) * 4/3 + 1];

int p = 0;
int i = 0;
buf.position(0);
while (i < size) {
int c = deSign(buf.get());
i++;

c *= 256;
if (i < size)
c += deSign(buf.get());
i++;

c *= 256;
if (i < size)
c += deSign(buf.get());
i++;

str[p++] = base64[(c & 0x00fc0000) >> 18];
str[p++] = base64[(c & 0x0003f000) >> 12];

if (i > size + 1)
str[p++] = '=';
else
str[p++] = base64[(c & 0x00000fc0) >> 6];

if (i > size)
str[p++] = '=';
else
str[p++] = base64[c & 0x0000003f];
}

return String.copyValueOf(str, 0, p);
}

private static int POS(char c)
{
if (c >= 'A' && c <= 'Z') return c - 'A';
Expand Down
2 changes: 1 addition & 1 deletion src/org/perl6/nqp/sixmodel/SerializationWriter.java
Expand Up @@ -391,7 +391,7 @@ private String concatenateOutputs() {
throw new RuntimeException("Serialization sanity check failed: offset != output_size");

/* Base 64 encode and return. */
throw new RuntimeException("No base-64 encoding yet");
return Base64.encode(output);
}

/* Grabs an array of the bytes actually populated in the specified buffer. */
Expand Down

0 comments on commit ffda411

Please sign in to comment.