From 68ec4004e10a88dc2676c3ae1dc780110f243d24 Mon Sep 17 00:00:00 2001 From: Bert Vanderbauwhede Date: Sat, 13 Jul 2013 23:12:14 +0200 Subject: [PATCH] Add function safename_decode --- src/fnord/safename/codec.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/fnord/safename/codec.py b/src/fnord/safename/codec.py index db5288e..ba6f6db 100644 --- a/src/fnord/safename/codec.py +++ b/src/fnord/safename/codec.py @@ -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``. @@ -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])