aboutsummaryrefslogtreecommitdiffhomepage
path: root/python/google/protobuf/text_format.py
diff options
context:
space:
mode:
authorGravatar Feng Xiao <xfxyjwf@gmail.com>2015-08-26 15:47:35 -0700
committerGravatar Feng Xiao <xfxyjwf@gmail.com>2015-08-26 15:47:35 -0700
commite94e062b589cfc1c5d486ec4470af104e102232b (patch)
tree42501d8c22cd93f77ba4bf0434dc6e7553794bdf /python/google/protobuf/text_format.py
parentfecc3d5963ed74337504953c98f288dfa0b024a8 (diff)
parentc7a1f8ec3b7ab4f6763e4d5c2663ad39e13a6aa0 (diff)
Merge branch 'master' of github.com:google/protobuf into beta-1
Diffstat (limited to 'python/google/protobuf/text_format.py')
-rwxr-xr-xpython/google/protobuf/text_format.py27
1 files changed, 21 insertions, 6 deletions
diff --git a/python/google/protobuf/text_format.py b/python/google/protobuf/text_format.py
index dd205cf1..1399223f 100755
--- a/python/google/protobuf/text_format.py
+++ b/python/google/protobuf/text_format.py
@@ -67,6 +67,25 @@ class Error(Exception):
class ParseError(Error):
"""Thrown in case of ASCII parsing error."""
+class TextWriter(object):
+ def __init__(self, as_utf8):
+ if six.PY2:
+ self._writer = io.BytesIO()
+ else:
+ self._writer = io.StringIO()
+
+ def write(self, val):
+ if six.PY2:
+ if isinstance(val, six.text_type):
+ val = val.encode('utf-8')
+ return self._writer.write(val)
+
+ def close(self):
+ return self._writer.close()
+
+ def getvalue(self):
+ return self._writer.getvalue()
+
def MessageToString(message, as_utf8=False, as_one_line=False,
pointy_brackets=False, use_index_order=False,
@@ -92,7 +111,7 @@ def MessageToString(message, as_utf8=False, as_one_line=False,
Returns:
A string of the text formatted protocol buffer message.
"""
- out = io.BytesIO()
+ out = TextWriter(as_utf8)
PrintMessage(message, out, as_utf8=as_utf8, as_one_line=as_one_line,
pointy_brackets=pointy_brackets,
use_index_order=use_index_order,
@@ -159,11 +178,7 @@ def PrintField(field, value, out, indent=0, as_utf8=False, as_one_line=False,
# For groups, use the capitalized name.
out.write(field.message_type.name)
else:
- if isinstance(field.name, six.text_type):
- name = field.name.encode('utf-8')
- else:
- name = field.name
- out.write(name)
+ out.write(field.name)
if field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
# The colon is optional in this case, but our cross-language golden files