Skip to content

Add base32 encode/decode to gleam_stdlib #863

@xikaos

Description

@xikaos

Context

While playing with a TOTP generator/validator, I realized Gleam does not have native base32 encoding/decoding support.

That means gleamlings have two options:

  1. Implement a native Gleam base32 encoder/decoder (ref).
  2. Leverage existing JS/Erlang code trought FFI and expose it to our modules (ref).

Given that base32 is specially useful for:

  • TOTP/HOTP secrets and otpauth:// URIs
  • DNS- and filename-friendly encodings
  • Text-only or case-insensitive channels

I propose adding base32_encode() and base32_decode() as functions in the Gleam stdlib.

Motivations

  • Base32 (RFC 4648) is a standard peer to base16 and base64.
  • Eliminate third-party dependencies when base16/base64 are already part of stdlib.
  • Consistent cross-target availability (Erlang and JavaScript).

Proposed API

Public Gleam functions in bit_array:

  • base32_encode(input: BitArray, padding: Bool) -> String
  • base32_decode(encoded: String) -> Result(BitArray, Nil)

Examples

import gleam/bit_array

// Encode with/without padding
bit_array.base32_encode(<<"foobar":utf8>>, True)  // "MZXW6YTBOI======"
bit_array.base32_encode(<<"foobar":utf8>>, False) // "MZXW6YTBOI"

// Decode (case-insensitive, padding optional)
bit_array.base32_decode("MZXW6YTBOI======") // Ok(<<"foobar":utf8>>)
bit_array.base32_decode("mzxw6ytboi")   

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions