1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
|
# implements a factory to create codec instances for a given java charset
import codecs
from array import array
from functools import partial
from java.lang import StringBuilder
from java.nio import ByteBuffer, CharBuffer
from java.nio.charset import Charset, IllegalCharsetNameException
from StringIO import StringIO
python_to_java = {
'cp932': 'cp942',
'iso2022_jp': 'ISO-2022-JP',
'iso2022_jp_2': 'ISO-2022-JP-2',
'iso2022_kr': 'ISO-2022-KR',
'shift_jisx0213': 'x-SJIS_0213',
}
def _java_factory(encoding):
encoding = python_to_java.get(encoding, encoding)
supported = False
try:
supported = Charset.isSupported(encoding)
except IllegalCharsetNameException:
pass
if not supported:
return None, set()
charset = Charset.forName(encoding) # FIXME should we return this canonical name? could be best... TBD
entry = codecs.CodecInfo(
name=encoding,
encode=Codec(encoding).encode,
decode=Codec(encoding).decode,
incrementalencoder=partial(IncrementalEncoder, encoding=encoding),
incrementaldecoder=partial(IncrementalDecoder, encoding=encoding),
streamreader=partial(StreamReader, encoding=encoding),
streamwriter=partial(StreamWriter, encoding=encoding)
)
return entry, charset.aliases()
class Codec(object): # (codecs.Codec):
def __init__(self, encoding):
self.encoding = encoding
def decode(self, input, errors='strict', final=True):
error_function = codecs.lookup_error(errors)
input_buffer = ByteBuffer.wrap(array('b', input))
decoder = Charset.forName(self.encoding).newDecoder()
output_buffer = CharBuffer.allocate(min(max(int(len(input) / 2), 256), 1024))
builder = StringBuilder(int(decoder.averageCharsPerByte() * len(input)))
while True:
result = decoder.decode(input_buffer, output_buffer, False)
pos = output_buffer.position()
output_buffer.rewind()
builder.append(output_buffer.subSequence(0, pos))
if result.isUnderflow():
if final:
_process_incomplete_decode(self.encoding, input, error_function, input_buffer, builder)
break
_process_decode_errors(self.encoding, input, result, error_function, input_buffer, builder)
return builder.toString(), input_buffer.position()
def encode(self, input, errors='strict'):
error_function = codecs.lookup_error(errors)
# workaround non-BMP issues - need to get the exact count of chars, not codepoints
input_buffer = CharBuffer.allocate(StringBuilder(input).length())
input_buffer.put(input)
input_buffer.rewind()
encoder = Charset.forName(self.encoding).newEncoder()
output_buffer = ByteBuffer.allocate(min(max(len(input) * 2, 256), 1024))
builder = StringIO()
while True:
result = encoder.encode(input_buffer, output_buffer, True)
pos = output_buffer.position()
output_buffer.rewind()
builder.write(output_buffer.array()[0:pos].tostring())
if result.isUnderflow():
break
_process_encode_errors(self.encoding, input, result, error_function, input_buffer, builder)
return builder.getvalue(), len(input)
class NonfinalCodec(Codec):
def decode(self, input, errors='strict'):
return Codec.decode(self, input, errors, final=False)
class IncrementalEncoder(codecs.IncrementalEncoder):
def __init__(self, errors='strict', encoding=None):
assert encoding
self.encoding = encoding
self.errors = errors
self.encoder = Charset.forName(self.encoding).newEncoder()
self.output_buffer = ByteBuffer.allocate(1024)
def encode(self, input, final=False):
error_function = codecs.lookup_error(self.errors)
# workaround non-BMP issues - need to get the exact count of chars, not codepoints
input_buffer = CharBuffer.allocate(StringBuilder(input).length())
input_buffer.put(input)
input_buffer.rewind()
self.output_buffer.rewind()
builder = StringIO()
while True:
result = self.encoder.encode(input_buffer, self.output_buffer, final)
pos = self.output_buffer.position()
self.output_buffer.rewind()
builder.write(self.output_buffer.array()[0:pos].tostring())
if result.isUnderflow():
break
_process_encode_errors(self.encoding, input, result, error_function, input_buffer, builder)
return builder.getvalue()
class IncrementalDecoder(codecs.IncrementalDecoder):
def __init__(self, errors='strict', encoding=None,):
assert encoding
self.encoding = encoding
self.errors = errors
self.decoder = Charset.forName(self.encoding).newDecoder()
self.output_buffer = CharBuffer.allocate(1024)
self.buffer = ''
def decode(self, input, final=False):
error_function = codecs.lookup_error(self.errors)
input_array = array('b', self.buffer + str(input))
input_buffer = ByteBuffer.wrap(input_array)
builder = StringBuilder(int(self.decoder.averageCharsPerByte() * len(input)))
self.output_buffer.rewind()
while True:
result = self.decoder.decode(input_buffer, self.output_buffer, final)
pos = self.output_buffer.position()
self.output_buffer.rewind()
builder.append(self.output_buffer.subSequence(0, pos))
if result.isUnderflow():
if not final:
# Keep around any remaining input for next call to decode
self.buffer = input_array[input_buffer.position():input_buffer.limit()].tostring()
else:
_process_incomplete_decode(self.encoding, input, error_function, input_buffer, builder)
break
_process_decode_errors(self.encoding, input, result, error_function, input_buffer, builder)
return builder.toString()
def reset(self):
self.buffer = ""
self.decoder.reset()
def getstate(self):
# No way to extract the internal state of a Java decoder.
return self.buffer or "", 0
def setstate(self, state):
self.buffer, _ = state or ("", 0)
# No way to restore: reset possible EOF state.
self.decoder.reset()
class StreamWriter(NonfinalCodec, codecs.StreamWriter):
def __init__(self, stream, errors='strict', encoding=None, ):
NonfinalCodec.__init__(self, encoding)
codecs.StreamWriter.__init__(self, stream, errors)
class StreamReader(NonfinalCodec, codecs.StreamReader):
def __init__(self, stream, errors='strict', encoding=None, ):
NonfinalCodec.__init__(self, encoding)
codecs.StreamReader.__init__(self, stream, errors)
def _process_decode_errors(encoding, input, result, error_function, input_buffer, builder):
if result.isError():
e = UnicodeDecodeError(
encoding,
input,
input_buffer.position(),
input_buffer.position() + result.length(),
'illegal multibyte sequence')
replacement, pos = error_function(e)
if not isinstance(replacement, unicode):
raise TypeError()
pos = int(pos)
if pos < 0:
pos = input_buffer.limit() + pos
if pos > input_buffer.limit():
raise IndexError()
builder.append(replacement)
input_buffer.position(pos)
def _process_incomplete_decode(encoding, input, error_function, input_buffer, builder):
if input_buffer.position() < input_buffer.limit():
e = UnicodeDecodeError(
encoding,
input,
input_buffer.position(),
input_buffer.limit(),
'illegal multibyte sequence')
replacement, pos = error_function(e)
if not isinstance(replacement, unicode):
raise TypeError()
pos = int(pos)
if pos < 0:
pos = input_buffer.limit() + pos
if pos > input_buffer.limit():
raise IndexError()
builder.append(replacement)
input_buffer.position(pos)
def _get_unicode(input_buffer, result):
return input_buffer.subSequence(0, result.length()).toString()
def _process_encode_errors(encoding, input, result, error_function, input_buffer, builder):
if result.isError():
e = UnicodeEncodeError(
encoding,
input,
input_buffer.position(),
input_buffer.position() + result.length(),
'illegal multibyte sequence')
replacement, pos = error_function(e)
if not isinstance(replacement, unicode):
raise TypeError()
pos = int(pos)
if pos < 0:
pos = input_buffer.limit() + pos
if pos > input_buffer.limit():
raise IndexError()
builder.write(str(replacement))
input_buffer.position(pos)
|