Skip to content

Commit 927ac63

Browse files
committed
py2 use conversion functions to convert bytes and strings
1 parent b8a65c4 commit 927ac63

5 files changed

Lines changed: 35 additions & 19 deletions

File tree

python/google/protobuf/internal/decoder.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@
8383
import struct
8484
from google.protobuf.internal import encoder
8585
from google.protobuf.internal import wire_format
86+
from google.protobuf.internal.utils import bytestr_to_string, byte_ord
8687
from google.protobuf import message
8788

8889

@@ -108,12 +109,11 @@ def _VarintDecoder(mask):
108109
decoder returns a (value, new_pos) pair.
109110
"""
110111

111-
local_ord = ord
112112
def DecodeVarint(buffer, pos):
113113
result = 0
114114
shift = 0
115115
while 1:
116-
b = local_ord(buffer[pos])
116+
b = byte_ord(buffer[pos])
117117
result |= ((b & 0x7f) << shift)
118118
pos += 1
119119
if not (b & 0x80):
@@ -128,12 +128,11 @@ def DecodeVarint(buffer, pos):
128128
def _SignedVarintDecoder(mask):
129129
"""Like _VarintDecoder() but decodes signed values."""
130130

131-
local_ord = ord
132131
def DecodeVarint(buffer, pos):
133132
result = 0
134133
shift = 0
135134
while 1:
136-
b = local_ord(buffer[pos])
135+
b = byte_ord(buffer[pos])
137136
result |= ((b & 0x7f) << shift)
138137
pos += 1
139138
if not (b & 0x80):
@@ -169,7 +168,7 @@ def ReadTag(buffer, pos):
169168
"""
170169

171170
start = pos
172-
while ord(buffer[pos]) & 0x80:
171+
while byte_ord(buffer[pos]) & 0x80:
173172
pos += 1
174173
pos += 1
175174
return (buffer[start:pos], pos)
@@ -378,7 +377,6 @@ def StringDecoder(field_number, is_repeated, is_packed, key, new_default):
378377
"""Returns a decoder for a string field."""
379378

380379
local_DecodeVarint = _DecodeVarint
381-
local_unicode = unicode
382380

383381
assert not is_packed
384382
if is_repeated:
@@ -394,7 +392,7 @@ def DecodeRepeatedField(buffer, pos, end, message, field_dict):
394392
new_pos = pos + size
395393
if new_pos > end:
396394
raise _DecodeError('Truncated string.')
397-
value.append(local_unicode(buffer[pos:new_pos], 'utf-8'))
395+
value.append(bytestr_to_string(buffer[pos:new_pos]))
398396
# Predict that the next tag is another copy of the same repeated field.
399397
pos = new_pos + tag_len
400398
if buffer[new_pos:pos] != tag_bytes or new_pos == end:
@@ -407,7 +405,7 @@ def DecodeField(buffer, pos, end, message, field_dict):
407405
new_pos = pos + size
408406
if new_pos > end:
409407
raise _DecodeError('Truncated string.')
410-
field_dict[key] = local_unicode(buffer[pos:new_pos], 'utf-8')
408+
field_dict[key] = bytestr_to_string(buffer[pos:new_pos])
411409
return new_pos
412410
return DecodeField
413411

@@ -626,7 +624,7 @@ def DecodeItem(buffer, pos, end, message, field_dict):
626624
def _SkipVarint(buffer, pos, end):
627625
"""Skip a varint value. Returns the new position."""
628626

629-
while ord(buffer[pos]) & 0x80:
627+
while byte_ord(buffer[pos]) & 0x80:
630628
pos += 1
631629
pos += 1
632630
if pos > end:
@@ -693,7 +691,6 @@ def _FieldSkipper():
693691
]
694692

695693
wiretype_mask = wire_format.TAG_TYPE_MASK
696-
local_ord = ord
697694

698695
def SkipField(buffer, pos, end, tag_bytes):
699696
"""Skips a field with the specified tag.
@@ -706,7 +703,7 @@ def SkipField(buffer, pos, end, tag_bytes):
706703
"""
707704

708705
# The wire type is always in the first byte since varints are little-endian.
709-
wire_type = local_ord(tag_bytes[0]) & wiretype_mask
706+
wire_type = byte_ord(tag_bytes[0]) & wiretype_mask
710707
return WIRETYPE_TO_SKIPPER[wire_type](buffer, pos, end)
711708

712709
return SkipField

python/google/protobuf/internal/encoder.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868

6969
import struct
7070
from google.protobuf.internal import wire_format
71+
from google.protobuf.internal.utils import string_to_bytestr
7172

7273

7374
# This will overflow and thus become IEEE-754 "infinity". We would use
@@ -659,14 +660,14 @@ def StringEncoder(field_number, is_repeated, is_packed):
659660
if is_repeated:
660661
def EncodeRepeatedField(write, value):
661662
for element in value:
662-
encoded = element.encode('utf-8')
663+
encoded = string_to_bytestr(element)
663664
write(tag)
664665
local_EncodeVarint(write, local_len(encoded))
665666
write(encoded)
666667
return EncodeRepeatedField
667668
else:
668669
def EncodeField(write, value):
669-
encoded = value.encode('utf-8')
670+
encoded = string_to_bytestr(value)
670671
write(tag)
671672
local_EncodeVarint(write, local_len(encoded))
672673
return write(encoded)

python/google/protobuf/internal/utils.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,19 @@
66
def cmp(a, b):
77
return (a > b) - (a < b)
88

9+
10+
11+
def bytestr_to_string(bytestr):
12+
return unicode(bytestr, 'utf-8')
13+
14+
def string_to_bytestr(string):
15+
#return b''.join([chr(b) for b in string.encode('utf-8')])
16+
return string.encode('utf-8')
17+
18+
19+
def byte_ord(bytes):
20+
return ord(bytes)
21+
22+
def char_byte(char):
23+
return char
24+

python/google/protobuf/internal/wire_format.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
import struct
3636
from google.protobuf import descriptor
3737
from google.protobuf import message
38+
from google.protobuf.internal.utils import string_to_bytestr
3839

3940

4041
TAG_TYPE_BITS = 3 # Number of bits used to hold type info in a proto tag.
@@ -181,7 +182,7 @@ def EnumByteSize(field_number, enum):
181182

182183

183184
def StringByteSize(field_number, string):
184-
return BytesByteSize(field_number, string.encode('utf-8'))
185+
return BytesByteSize(field_number, string_to_bytestr(string))
185186

186187

187188
def BytesByteSize(field_number, b):

python/google/protobuf/text_format.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737

3838
from collections import deque
3939
from google.protobuf.internal import type_checkers
40+
from google.protobuf.internal.utils import char_byte, bytestr_to_string
4041
from google.protobuf import descriptor
4142

4243
__all__ = [ 'MessageToString', 'PrintMessage', 'PrintField',
@@ -403,7 +404,7 @@ def LookingAtInteger(self):
403404
if not self.token:
404405
return False
405406
c = self.token[0]
406-
return (c >= '0' and c <= '9') or c == '-' or c == '+'
407+
return (c >= char_byte('0') and c <= char_byte('9')) or c == char_byte('-') or c == char_byte('+')
407408

408409
def ConsumeIdentifier(self):
409410
"""Consumes protocol message field identifier.
@@ -538,9 +539,9 @@ def ConsumeString(self):
538539
Raises:
539540
ParseError: If a string value couldn't be consumed.
540541
"""
541-
bytes = self.ConsumeByteString()
542+
bytestr = self.ConsumeByteString()
542543
try:
543-
return unicode(bytes, 'utf-8')
544+
return bytestr_to_string(bytestr)
544545
except UnicodeDecodeError, e:
545546
raise self._StringParseError(e)
546547

@@ -554,7 +555,7 @@ def ConsumeByteString(self):
554555
ParseError: If a byte array value couldn't be consumed.
555556
"""
556557
list = [self._ConsumeSingleByteString()]
557-
while len(self.token) > 0 and self.token[0] in ('\'', '"'):
558+
while len(self.token) > 0 and self.token[0] in (char_byte('\''), char_byte('"')):
558559
list.append(self._ConsumeSingleByteString())
559560
return "".join(list)
560561

@@ -566,7 +567,7 @@ def _ConsumeSingleByteString(self):
566567
method only consumes one token.
567568
"""
568569
text = self.token
569-
if len(text) < 1 or text[0] not in ('\'', '"'):
570+
if len(text) < 1 or text[0] not in (char_byte('\''), char_byte('"')):
570571
raise self._ParseError('Exptected string.')
571572

572573
if len(text) < 2 or text[-1] != text[0]:

0 commit comments

Comments
 (0)