Skip to content

Commit

Permalink
fix: common_prefixed
Browse files Browse the repository at this point in the history
  • Loading branch information
thorwhalen committed Jan 15, 2024
1 parent 1ba616f commit 9878409
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions dol/kv_codecs.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,15 +417,30 @@ def tuple_of_dict(keys):


def _affix_encoder(string: str, prefix: str = '', suffix: str = ''):
"""Affix a prefix and suffix to a string
>>> _affix_encoder('name', prefix='/folder/', suffix='.txt')
'/folder/name.txt'
"""
return f'{prefix}{string}{suffix}'


def _affix_decoder(string: str, prefix: str = '', suffix: str = ''):
return string[len(prefix) : -len(suffix)]
"""Remove prefix and suffix from string
>>> _affix_decoder('/folder/name.txt', prefix='/folder/', suffix='.txt')
'name'
"""
end_idx = -len(suffix) or None # if suffix is empty, end_idx should be None
return string[len(prefix) : end_idx]


def affix_key_codec(prefix: str = '', suffix: str = ''):
"""A factory that creates a key codec that affixes a prefix and suffix to the key"""
"""A factory that creates a key codec that affixes a prefix and suffix to the key
>>> codec = affix_key_codec(prefix='/folder/', suffix='.txt')
>>> codec.encoder('name')
'/folder/name.txt'
>>> codec.decoder('/folder/name.txt')
"""
return KeyCodec(
encoder=partial(_affix_encoder, prefix=prefix, suffix=suffix),
decoder=partial(_affix_decoder, prefix=prefix, suffix=suffix),
Expand All @@ -451,7 +466,7 @@ def common_prefixed(keys: Iterable[str]):
from dol.util import max_common_prefix

prefix = max_common_prefix(keys)
return KeyCodecs.prefixed(prefix, simple_str_sep='')
return KeyCodecs.prefixed(prefix)


def common_prefix_keys_wrap(s: Mapping):
Expand Down Expand Up @@ -549,7 +564,9 @@ def key_based(
value codec to use."""

def extension_based(
ext_mapping: dict = dflt_ext_mapping, *, default: Optional[Callable] = None,
ext_mapping: dict = dflt_ext_mapping,
*,
default: Optional[Callable] = None,
):
"""A factory that creates a key-value codec that uses the file extension to
determine the value codec to use."""

0 comments on commit 9878409

Please sign in to comment.