Base64 Encoding in Chapel

Chapel provides built-in support for base64 encoding/decoding.

use Base64;
use IO;

proc main() {
    // Here's the string we'll encode/decode.
    var data = "abc123!?$*&()'-=@~";

    // Chapel supports both standard and URL-compatible
    // base64. Here's how to encode using the standard
    // encoder.
    var sEnc = encode(data.bytes());
    writeln(sEnc);

    // Decoding may return an error, which you can check
    // if you don't already know the input to be
    // well-formed.
    var sDec = decode(sEnc);
    writeln(sDec);
    writeln();

    // This encodes/decodes using a URL-compatible base64
    // format.
    var uEnc = encode(data.bytes(), url=true);
    writeln(uEnc);
    var uDec = decode(uEnc, url=true);
    writeln(uDec);
}

To run the program, save it as base64_encoding.chpl and use the Chapel compiler:

$ chpl base64_encoding.chpl -o base64_encoding
$ ./base64_encoding
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~

The string encodes to slightly different values with the standard and URL base64 encoders (trailing + vs -) but they both decode to the original string as desired.

In Chapel, we use the Base64 module which provides encode and decode functions for base64 operations. The url parameter in these functions allows us to switch between standard and URL-compatible base64 encoding.

Note that Chapel’s encode function expects a bytes object, which we create by calling .bytes() on our string. The decode function returns the decoded string directly.

Error handling in Chapel is typically done through exceptions, so you might want to wrap the decode calls in a try-catch block if you’re unsure about the input’s format.