29
29
30
30
import struct
31
31
import logging
32
+ import sys
32
33
33
34
log = logging .getLogger (__name__ )
34
35
@@ -105,6 +106,12 @@ class Utf8String(object):
105
106
106
107
def __init__ (self , * args ):
107
108
self .value = args [0 ] if len (args ) else None
109
+ if sys .version_info >= (3 ,0 ,0 ):
110
+ if not isinstance (self .value , str ):
111
+ self .value = self .value .decode ('utf-8' )
112
+ else :
113
+ if not isinstance (self .value , unicode ):
114
+ self .value = self .value .decode ('utf-8' )
108
115
109
116
def to_bytes (self ):
110
117
"""
@@ -115,28 +122,28 @@ def to_bytes(self):
115
122
>>> Utf8String("\\ xc3\\ xbcber".decode('utf-8')).to_bytes()
116
123
'\\ x05\\ xc3\\ xbcber'
117
124
"""
118
- data = self .value .encode ('utf-8' )
125
+ data = self .value .encode ('utf-8' )
119
126
strlen = len (data )
120
127
121
128
return MultiByteInt31 (strlen ).to_bytes () + data
122
129
123
130
def __str__ (self ):
124
- return self .value .decode ( 'latin1 ' )
131
+ return self .value .encode ( 'utf-8 ' )
125
132
126
133
def __unicode__ (self ):
127
- return self .value
134
+ return self .value
128
135
129
136
@classmethod
130
137
def parse (cls , fp ):
131
- """
132
- >>> from StringIO import StringIO as io
133
- >>> fp = io("\\ x05\\ xc3\\ xbcber")
134
- >>> s = Utf8String.parse(fp)
135
- >>> s.to_bytes()
138
+ """
139
+ >>> from StringIO import StringIO as io
140
+ >>> fp = io("\\ x05\\ xc3\\ xbcber")
141
+ >>> s = Utf8String.parse(fp)
142
+ >>> s.to_bytes()
136
143
'\\ x05\\ xc3\\ xbcber'
137
- >>> print str(s)
138
- ' über'
139
- """
144
+ >>> print str(s)
145
+ über
146
+ """
140
147
lngth = struct .unpack ('<B' , fp .read (1 ))[0 ]
141
148
142
149
return cls (fp .read (lngth ).decode ('utf-8' ))
@@ -187,6 +194,12 @@ def __str__(self):
187
194
188
195
@classmethod
189
196
def parse (cls , fp ):
197
+ """
198
+ >>> from StringIO import StringIO as io
199
+ >>> buf = io('\\ x00\\ x00\\ x06\\ x00\\ x00\\ x00\\ x00\\ x00\\ x80-N\\ x00\\ x00\\ x00\\ x00\\ x00')
200
+ >>> str(Decimal.parse(buf))
201
+ '5.123456'
202
+ """
190
203
log .warn ('Possible false interpretation' )
191
204
fp .read (2 )
192
205
scale = struct .unpack ('<B' , fp .read (1 ))[0 ]
0 commit comments