Skip to content

Commit

Permalink
Add function safename_decode
Browse files Browse the repository at this point in the history
  • Loading branch information
batlock666 committed Jul 13, 2013
1 parent 0f6ce29 commit 68ec400
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/fnord/safename/codec.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,21 @@
lambda string: "(%s)" % hex(ord(string))[2:]),
)

_safename_decode_chain = HandlerChain(
Handler(
"\{[a-z]+\}",
lambda string: string[1:-1].upper()),
Handler(
"_+",
lambda string: string.replace("_", " ")),
Handler(
"[a-z0-9\-+!$%&'@~#.,^]+",
lambda string: string),
Handler(
"\([0-9a-f]+\)",
lambda string: unichr(int(string[1:-1], 16))),
)


def safename_encode(string, errors="strict"):
"""Encode a string with codec ``safename``.
Expand All @@ -27,3 +42,15 @@ def safename_encode(string, errors="strict"):
return _safename_encode_chain(string), len(string)
except UnicodeError as error:
raise UnicodeEncodeError(error.args[0])


def safename_decode(string, errors="strict"):
"""Decode a string with codec ``safename``.
"""
if errors != "strict":
raise UnicodeError(u"Unsupported error handling: %s" % errors)

try:
return _safename_decode_chain(string), len(string)
except UnicodeError as error:
raise UnicodeDecodeError(error.args[0])

0 comments on commit 68ec400

Please sign in to comment.