Base64 Encoding in PureScript

Here’s the translation of the Base64 Encoding example from Go to PureScript:

PureScript provides support for base64 encoding/decoding through the purescript-node-buffer and purescript-encoding libraries.

module Main where

import Prelude

import Data.ArrayBuffer.Types (Uint8Array)
import Data.Either (Either(..))
import Data.TextEncoder (encodeUtf8)
import Effect (Effect)
import Effect.Console (log)
import Node.Buffer as Buffer
import Node.Encoding (Encoding(..))

main :: Effect Unit
main = do
  -- Here's the string we'll encode/decode.
  let data = "abc123!?$*&()'-=@~"

  -- PureScript supports both standard and URL-compatible
  -- base64. Here's how to encode using the standard encoder.
  sEnc <- Buffer.toString Base64 =<< Buffer.fromString data UTF8
  log sEnc

  -- Decoding may return an error, which you can check
  -- if you don't already know the input to be well-formed.
  case Buffer.toString UTF8 =<< Buffer.fromString sEnc Base64 of
    Right sDec -> do
      log sDec
      log ""
    Left err -> log $ "Decoding error: " <> show err

  -- This encodes/decodes using a URL-compatible base64 format.
  uEnc <- Buffer.toString Base64URL =<< Buffer.fromString data UTF8
  log uEnc
  
  case Buffer.toString UTF8 =<< Buffer.fromString uEnc Base64URL of
    Right uDec -> log uDec
    Left err -> log $ "Decoding error: " <> show err

To run this program, you’ll need to install the necessary dependencies:

$ spago install node-buffer encoding

Then you can compile and run the program:

$ spago run
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.

Note that PureScript, being a purely functional language, handles effects and potential errors differently from imperative languages. We use the Effect monad to handle side effects, and the Either type to handle potential decoding errors.

The Buffer module from purescript-node-buffer is used for byte-level operations, which is necessary for base64 encoding and decoding. The Encoding type from purescript-node-encoding provides the different encoding options, including Base64 and Base64URL.