Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions multibase/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
Encoding,
decode,
encode,
encoder_by_name,
get_codec,
get_encoding_info,
is_encoded,
Expand Down
20 changes: 20 additions & 0 deletions multibase/multibase.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,26 @@ def decode(data, return_encoding=False):
raise DecodingError(f"Failed to decode multibase data: {e}") from e


def encoder_by_name(name_or_prefix):
"""
Create an Encoder from a name or single-character prefix.

:param name_or_prefix: encoding name or prefix character
:type name_or_prefix: str
:return: an Encoder instance
:rtype: Encoder
:raises UnsupportedEncodingError: if the encoding is not supported
"""
if name_or_prefix in ENCODINGS_LOOKUP:
return Encoder(name_or_prefix)

prefix_bytes = name_or_prefix.encode("utf-8")
if prefix_bytes in ENCODINGS_LOOKUP:
return Encoder(ENCODINGS_LOOKUP[prefix_bytes].encoding)

raise UnsupportedEncodingError(f"Encoding {name_or_prefix!r} not supported.")


class Encoder:
"""Reusable encoder for a specific encoding."""

Expand Down
19 changes: 19 additions & 0 deletions tests/test_multibase.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
UnsupportedEncodingError,
decode,
encode,
encoder_by_name,
get_encoding_info,
is_encoded,
is_encoding_supported,
Expand Down Expand Up @@ -192,6 +193,24 @@ def test_encoder_class():
Encoder("base999")


def test_encoder_by_name():
"""Test encoder_by_name factory function."""
enc1 = encoder_by_name("base16")
assert enc1.encoding == "base16"

enc2 = encoder_by_name("f")
assert enc2.encoding == "base16"

enc3 = encoder_by_name("🚀")
assert enc3.encoding == "base256emoji"

with pytest.raises(UnsupportedEncodingError):
encoder_by_name("base999")

with pytest.raises(UnsupportedEncodingError):
encoder_by_name("?")


def test_decoder_class():
"""Test Decoder class."""
decoder = Decoder()
Expand Down
Loading