Skip to content
heff

std.base64

Base64 (RFC 4648): bytes written as text, each three of them as four digits of 64, A-Z, a-z, 0-9 and two more, the text padded with = to a multiple of four. encode and decode take the standard digits, + and / (Go’s base64.StdEncoding); encodeURL and decodeURL those safe in a URL or a file name, - and _ (Go’s base64.URLEncoding), padded too. Reading is strict, as Go’s Strict reads: the padding is required, nothing but digits and it is read (no white space), and the bits left over in the last digit are 0. Import it by a name, import std.base64 as Base64.

import bytes as Bytes
import std.base64 as Base64
-- | >>> greeting
-- | "aGk/Pz4="
greeting : String
greeting = Base64.encode (Bytes.fromString "hi??>")

encode

encode : Bytes -> String

The bytes as base64’s standard digits, padded with = (Go’s base64.StdEncoding). RFC 4648’s examples:

>>> List.map (\s -> encode (Bytes.fromString s)) ["", "f", "fo", "foo", "foob", "fooba", "foobar"]
["", "Zg==", "Zm8=", "Zm9v", "Zm9vYg==", "Zm9vYmE=", "Zm9vYmFy"]
>>> encode b[0, 16, 131, 16, 81, 135, 32, 146, 139, 48, 211, 143, 65, 20, 147, 81, 85, 151, 97, 150, 155, 113, 215, 159, 130, 24, 163, 146, 89, 167, 162, 154, 171, 178, 219, 175, 195, 28, 179, 211, 93, 183, 227, 158, 187, 243, 223, 191]
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

decode

decode : String -> Maybe Bytes

The bytes the standard digits are, read strictly: Nothing where the text is not a multiple of four digits long, has anything but digits and its padding (white space too), lacks its padding, or has bits left over in its last digit that are not 0.

>>> List.map decode ["", "Zg==", "Zm8=", "Zm9v", "Zm9vYg==", "Zm9vYmE=", "Zm9vYmFy"]
[Just b[], Just b["f"], Just b["fo"], Just b["foo"], Just b["foob"], Just b["fooba"], Just b["foobar"]]
>>> decode "+/8="
Just b[251, 255]

(no padding, padding but at the end, white space, URL’s digits, bits left over)

>>> List.map decode ["Zg", "Zm8", "Zg==Zm9v", "Zm9v\n", "Zm 9v", "-_8=", "Zh==", "Zm9=", "Z===", "===="]
[Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing]

encodeURL

encodeURL : Bytes -> String

The bytes as the base64 digits safe in a URL, - and _ for + and /, padded with = (Go’s base64.URLEncoding).

>>> encodeURL b[251, 255, 191]
"-_-_"
>>> encodeURL (Bytes.fromString "foob")
"Zm9vYg=="

decodeURL

decodeURL : String -> Maybe Bytes

The bytes the digits safe in a URL are, read as strictly as decode reads.

>>> decodeURL "-_-_"
Just b[251, 255, 191]
>>> List.map decodeURL ["+/+/", "Zm9vYg", "Zm9vYg=="]
[Nothing, Nothing, Just b["foob"]]