Source Edit

This module implements a base64 encoder and decoder.

Unstable API.

Base64 is an encoding and decoding technique used to convert binary data to an ASCII string format. Each Base64 digit represents exactly 6 bits of data. Three 8-bit bytes (i.e., a total of 24 bits) can therefore be represented by four 6-bit Base64 digits.

Basic usage

Encoding data

Example:

  1. import std/base64
  2. let encoded = encode("Hello World")
  3. assert encoded == "SGVsbG8gV29ybGQ="

Apart from strings you can also encode lists of integers or characters:

Example:

  1. import std/base64
  2. let encodedInts = encode([1'u8,2,3])
  3. assert encodedInts == "AQID"
  4. let encodedChars = encode(['h','e','y'])
  5. assert encodedChars == "aGV5"

Decoding data

Example:

  1. import std/base64
  2. let decoded = decode("SGVsbG8gV29ybGQ=")
  3. assert decoded == "Hello World"

URL Safe Base64

Example:

  1. import std/base64
  2. assert encode("c\xf7>", safe = true) == "Y_c-"
  3. assert encode("c\xf7>", safe = false) == "Y/c+"

See also

Procs

  1. proc decode(s: string): string {....raises: [ValueError], tags: [], forbids: [].}

Decodes string s in base64 representation back into its original form. The initial whitespace is skipped.

See also:

Example:

  1. assert decode("SGVsbG8gV29ybGQ=") == "Hello World"
  2. assert decode(" SGVsbG8gV29ybGQ=") == "Hello World"

Source Edit

  1. proc encode[T: byte | char](s: openArray[T]; safe = false): string

Encodes s into base64 representation.

If safe is true then it will encode using the URL-Safe and Filesystem-safe standard alphabet characters, which substitutes - instead of + and _ instead of /.

See also:

Example:

  1. assert encode("Hello World") == "SGVsbG8gV29ybGQ="
  2. assert encode(['n', 'i', 'm']) == "bmlt"
  3. assert encode(@['n', 'i', 'm']) == "bmlt"
  4. assert encode([1'u8, 2, 3, 4, 5]) == "AQIDBAU="

Source Edit

  1. proc encode[T: SomeInteger and not byte](s: openArray[T]; safe = false): string {.
  2. ...deprecated: "use `byte` or `char` instead".}

Deprecated: use `byte` or `char` instead

Source Edit

  1. proc encodeMime(s: string; lineLen = 75.Positive; newLine = "\r\n"; safe = false): string {.
  2. ...raises: [], tags: [], forbids: [].}

Encodes s into base64 representation as lines. Used in email MIME format, use lineLen and newline.

This procedure encodes a string according to MIME spec.

If safe is true then it will encode using the URL-Safe and Filesystem-safe standard alphabet characters, which substitutes - instead of + and _ instead of /.

See also:

Example:

  1. assert encodeMime("Hello World", 4, "\n") == "SGVs\nbG8g\nV29y\nbGQ="

Source Edit

  1. proc initDecodeTable(): array[256, char] {....raises: [], tags: [], forbids: [].}

Source Edit