patman: Move unicode helpers to tools
Create helper functions in the tools module to deal with the differences
between unicode in Python 2 (where we use the 'unicode' type) and Python 3
(where we use the 'str' type).
Signed-off-by: Simon Glass <sjg@chromium.org>
diff --git a/tools/patman/tools.py b/tools/patman/tools.py
index 0ad0fb9..7e6a45a 100644
--- a/tools/patman/tools.py
+++ b/tools/patman/tools.py
@@ -258,3 +258,35 @@
else:
data = chr(byte) * size
return data
+
+def ToUnicode(val):
+ """Make sure a value is a unicode string
+
+ This allows some amount of compatibility between Python 2 and Python3. For
+ the former, it returns a unicode object.
+
+ Args:
+ val: string or unicode object
+
+ Returns:
+ unicode version of val
+ """
+ if sys.version_info[0] >= 3:
+ return val
+ return val if isinstance(val, unicode) else val.decode('utf-8')
+
+def FromUnicode(val):
+ """Make sure a value is a non-unicode string
+
+ This allows some amount of compatibility between Python 2 and Python3. For
+ the former, it converts a unicode object to a string.
+
+ Args:
+ val: string or unicode object
+
+ Returns:
+ non-unicode version of val
+ """
+ if sys.version_info[0] >= 3:
+ return val
+ return val if isinstance(val, str) else val.encode('utf-8')