Multiformats.Multibase.AnyBase (multiformats_ex v0.2.0)
This module can be used to create custom "any base" encoding/decoding functions.
The module creates code similar to Elixir's own Base
module, except each module is intended to encapsulate a single base rather than multiple ones.
A custom alphabet must be provided, and that alphabet is used to generate encoding and decoding functions at compile time.
By default, the "base" of the module is determined by the number of characters in the provided alphabet, e.g. Base58
has a base of 58 because there are 58 characters.
At this time, padding is not an available option when using this module.
Note: This module is not intended to be able to recreate any multibase codec. The specific logic assumed by the generated code to encode and decode the data might not be applicable to all codecs. Ensure you thoroughly test any custom multibase codecs derived from this module.
Examples
Let's say you wanted to have a base 58 "codec":
defmodule Base58 do
use Multiformats.Multibase.AnyBase
name: :base58btc,
alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
end
Then you can invoke the custom base codec using encode/1
and decode/1
:
Base58.encode("it's multiformats!")
# => "5NgpeksG5ZXZxPmAGtXZq7a7r"
Base58.decode("5NgpeksG5ZXZxPmAGtXZq7a7r")
# => {:ok, "it's multiformats!"}
Additionally, there are overridable "hook" functions that allow custom modules to have more control over the encoding and decoding algorithms. These functions are executed at runtime, not during compilation.
before_encode/1
after_encode/1
before_decode/1
after_decode/1
Because the encoding and decoding algorithms assume that binary strings are the inputs and outputs, each hook function should expect a binary string input and return a binary string output.