Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

codecs.py 35 KB

You have to be logged in to leave a comment. Sign In
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
  1. """ codecs -- Python Codec Registry, API and helpers.
  2. Written by Marc-Andre Lemburg (mal@lemburg.com).
  3. (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
  4. """
  5. import builtins
  6. import sys
  7. ### Registry and builtin stateless codec functions
  8. try:
  9. from _codecs import *
  10. except ImportError as why:
  11. raise SystemError('Failed to load the builtin codecs: %s' % why)
  12. __all__ = ["register", "lookup", "open", "EncodedFile", "BOM", "BOM_BE",
  13. "BOM_LE", "BOM32_BE", "BOM32_LE", "BOM64_BE", "BOM64_LE",
  14. "BOM_UTF8", "BOM_UTF16", "BOM_UTF16_LE", "BOM_UTF16_BE",
  15. "BOM_UTF32", "BOM_UTF32_LE", "BOM_UTF32_BE",
  16. "CodecInfo", "Codec", "IncrementalEncoder", "IncrementalDecoder",
  17. "StreamReader", "StreamWriter",
  18. "StreamReaderWriter", "StreamRecoder",
  19. "getencoder", "getdecoder", "getincrementalencoder",
  20. "getincrementaldecoder", "getreader", "getwriter",
  21. "encode", "decode", "iterencode", "iterdecode",
  22. "strict_errors", "ignore_errors", "replace_errors",
  23. "xmlcharrefreplace_errors",
  24. "backslashreplace_errors", "namereplace_errors",
  25. "register_error", "lookup_error"]
  26. ### Constants
  27. #
  28. # Byte Order Mark (BOM = ZERO WIDTH NO-BREAK SPACE = U+FEFF)
  29. # and its possible byte string values
  30. # for UTF8/UTF16/UTF32 output and little/big endian machines
  31. #
  32. # UTF-8
  33. BOM_UTF8 = b'\xef\xbb\xbf'
  34. # UTF-16, little endian
  35. BOM_LE = BOM_UTF16_LE = b'\xff\xfe'
  36. # UTF-16, big endian
  37. BOM_BE = BOM_UTF16_BE = b'\xfe\xff'
  38. # UTF-32, little endian
  39. BOM_UTF32_LE = b'\xff\xfe\x00\x00'
  40. # UTF-32, big endian
  41. BOM_UTF32_BE = b'\x00\x00\xfe\xff'
  42. if sys.byteorder == 'little':
  43. # UTF-16, native endianness
  44. BOM = BOM_UTF16 = BOM_UTF16_LE
  45. # UTF-32, native endianness
  46. BOM_UTF32 = BOM_UTF32_LE
  47. else:
  48. # UTF-16, native endianness
  49. BOM = BOM_UTF16 = BOM_UTF16_BE
  50. # UTF-32, native endianness
  51. BOM_UTF32 = BOM_UTF32_BE
  52. # Old broken names (don't use in new code)
  53. BOM32_LE = BOM_UTF16_LE
  54. BOM32_BE = BOM_UTF16_BE
  55. BOM64_LE = BOM_UTF32_LE
  56. BOM64_BE = BOM_UTF32_BE
  57. ### Codec base classes (defining the API)
  58. class CodecInfo(tuple):
  59. """Codec details when looking up the codec registry"""
  60. # Private API to allow Python 3.4 to blacklist the known non-Unicode
  61. # codecs in the standard library. A more general mechanism to
  62. # reliably distinguish test encodings from other codecs will hopefully
  63. # be defined for Python 3.5
  64. #
  65. # See http://bugs.python.org/issue19619
  66. _is_text_encoding = True # Assume codecs are text encodings by default
  67. def __new__(cls, encode, decode, streamreader=None, streamwriter=None,
  68. incrementalencoder=None, incrementaldecoder=None, name=None,
  69. *, _is_text_encoding=None):
  70. self = tuple.__new__(cls, (encode, decode, streamreader, streamwriter))
  71. self.name = name
  72. self.encode = encode
  73. self.decode = decode
  74. self.incrementalencoder = incrementalencoder
  75. self.incrementaldecoder = incrementaldecoder
  76. self.streamwriter = streamwriter
  77. self.streamreader = streamreader
  78. if _is_text_encoding is not None:
  79. self._is_text_encoding = _is_text_encoding
  80. return self
  81. def __repr__(self):
  82. return "<%s.%s object for encoding %s at %#x>" % \
  83. (self.__class__.__module__, self.__class__.__qualname__,
  84. self.name, id(self))
  85. class Codec:
  86. """ Defines the interface for stateless encoders/decoders.
  87. The .encode()/.decode() methods may use different error
  88. handling schemes by providing the errors argument. These
  89. string values are predefined:
  90. 'strict' - raise a ValueError error (or a subclass)
  91. 'ignore' - ignore the character and continue with the next
  92. 'replace' - replace with a suitable replacement character;
  93. Python will use the official U+FFFD REPLACEMENT
  94. CHARACTER for the builtin Unicode codecs on
  95. decoding and '?' on encoding.
  96. 'surrogateescape' - replace with private code points U+DCnn.
  97. 'xmlcharrefreplace' - Replace with the appropriate XML
  98. character reference (only for encoding).
  99. 'backslashreplace' - Replace with backslashed escape sequences.
  100. 'namereplace' - Replace with \\N{...} escape sequences
  101. (only for encoding).
  102. The set of allowed values can be extended via register_error.
  103. """
  104. def encode(self, input, errors='strict'):
  105. """ Encodes the object input and returns a tuple (output
  106. object, length consumed).
  107. errors defines the error handling to apply. It defaults to
  108. 'strict' handling.
  109. The method may not store state in the Codec instance. Use
  110. StreamWriter for codecs which have to keep state in order to
  111. make encoding efficient.
  112. The encoder must be able to handle zero length input and
  113. return an empty object of the output object type in this
  114. situation.
  115. """
  116. raise NotImplementedError
  117. def decode(self, input, errors='strict'):
  118. """ Decodes the object input and returns a tuple (output
  119. object, length consumed).
  120. input must be an object which provides the bf_getreadbuf
  121. buffer slot. Python strings, buffer objects and memory
  122. mapped files are examples of objects providing this slot.
  123. errors defines the error handling to apply. It defaults to
  124. 'strict' handling.
  125. The method may not store state in the Codec instance. Use
  126. StreamReader for codecs which have to keep state in order to
  127. make decoding efficient.
  128. The decoder must be able to handle zero length input and
  129. return an empty object of the output object type in this
  130. situation.
  131. """
  132. raise NotImplementedError
  133. class IncrementalEncoder(object):
  134. """
  135. An IncrementalEncoder encodes an input in multiple steps. The input can
  136. be passed piece by piece to the encode() method. The IncrementalEncoder
  137. remembers the state of the encoding process between calls to encode().
  138. """
  139. def __init__(self, errors='strict'):
  140. """
  141. Creates an IncrementalEncoder instance.
  142. The IncrementalEncoder may use different error handling schemes by
  143. providing the errors keyword argument. See the module docstring
  144. for a list of possible values.
  145. """
  146. self.errors = errors
  147. self.buffer = ""
  148. def encode(self, input, final=False):
  149. """
  150. Encodes input and returns the resulting object.
  151. """
  152. raise NotImplementedError
  153. def reset(self):
  154. """
  155. Resets the encoder to the initial state.
  156. """
  157. def getstate(self):
  158. """
  159. Return the current state of the encoder.
  160. """
  161. return 0
  162. def setstate(self, state):
  163. """
  164. Set the current state of the encoder. state must have been
  165. returned by getstate().
  166. """
  167. class BufferedIncrementalEncoder(IncrementalEncoder):
  168. """
  169. This subclass of IncrementalEncoder can be used as the baseclass for an
  170. incremental encoder if the encoder must keep some of the output in a
  171. buffer between calls to encode().
  172. """
  173. def __init__(self, errors='strict'):
  174. IncrementalEncoder.__init__(self, errors)
  175. # unencoded input that is kept between calls to encode()
  176. self.buffer = ""
  177. def _buffer_encode(self, input, errors, final):
  178. # Overwrite this method in subclasses: It must encode input
  179. # and return an (output, length consumed) tuple
  180. raise NotImplementedError
  181. def encode(self, input, final=False):
  182. # encode input (taking the buffer into account)
  183. data = self.buffer + input
  184. (result, consumed) = self._buffer_encode(data, self.errors, final)
  185. # keep unencoded input until the next call
  186. self.buffer = data[consumed:]
  187. return result
  188. def reset(self):
  189. IncrementalEncoder.reset(self)
  190. self.buffer = ""
  191. def getstate(self):
  192. return self.buffer or 0
  193. def setstate(self, state):
  194. self.buffer = state or ""
  195. class IncrementalDecoder(object):
  196. """
  197. An IncrementalDecoder decodes an input in multiple steps. The input can
  198. be passed piece by piece to the decode() method. The IncrementalDecoder
  199. remembers the state of the decoding process between calls to decode().
  200. """
  201. def __init__(self, errors='strict'):
  202. """
  203. Create an IncrementalDecoder instance.
  204. The IncrementalDecoder may use different error handling schemes by
  205. providing the errors keyword argument. See the module docstring
  206. for a list of possible values.
  207. """
  208. self.errors = errors
  209. def decode(self, input, final=False):
  210. """
  211. Decode input and returns the resulting object.
  212. """
  213. raise NotImplementedError
  214. def reset(self):
  215. """
  216. Reset the decoder to the initial state.
  217. """
  218. def getstate(self):
  219. """
  220. Return the current state of the decoder.
  221. This must be a (buffered_input, additional_state_info) tuple.
  222. buffered_input must be a bytes object containing bytes that
  223. were passed to decode() that have not yet been converted.
  224. additional_state_info must be a non-negative integer
  225. representing the state of the decoder WITHOUT yet having
  226. processed the contents of buffered_input. In the initial state
  227. and after reset(), getstate() must return (b"", 0).
  228. """
  229. return (b"", 0)
  230. def setstate(self, state):
  231. """
  232. Set the current state of the decoder.
  233. state must have been returned by getstate(). The effect of
  234. setstate((b"", 0)) must be equivalent to reset().
  235. """
  236. class BufferedIncrementalDecoder(IncrementalDecoder):
  237. """
  238. This subclass of IncrementalDecoder can be used as the baseclass for an
  239. incremental decoder if the decoder must be able to handle incomplete
  240. byte sequences.
  241. """
  242. def __init__(self, errors='strict'):
  243. IncrementalDecoder.__init__(self, errors)
  244. # undecoded input that is kept between calls to decode()
  245. self.buffer = b""
  246. def _buffer_decode(self, input, errors, final):
  247. # Overwrite this method in subclasses: It must decode input
  248. # and return an (output, length consumed) tuple
  249. raise NotImplementedError
  250. def decode(self, input, final=False):
  251. # decode input (taking the buffer into account)
  252. data = self.buffer + input
  253. (result, consumed) = self._buffer_decode(data, self.errors, final)
  254. # keep undecoded input until the next call
  255. self.buffer = data[consumed:]
  256. return result
  257. def reset(self):
  258. IncrementalDecoder.reset(self)
  259. self.buffer = b""
  260. def getstate(self):
  261. # additional state info is always 0
  262. return (self.buffer, 0)
  263. def setstate(self, state):
  264. # ignore additional state info
  265. self.buffer = state[0]
  266. #
  267. # The StreamWriter and StreamReader class provide generic working
  268. # interfaces which can be used to implement new encoding submodules
  269. # very easily. See encodings/utf_8.py for an example on how this is
  270. # done.
  271. #
  272. class StreamWriter(Codec):
  273. def __init__(self, stream, errors='strict'):
  274. """ Creates a StreamWriter instance.
  275. stream must be a file-like object open for writing.
  276. The StreamWriter may use different error handling
  277. schemes by providing the errors keyword argument. These
  278. parameters are predefined:
  279. 'strict' - raise a ValueError (or a subclass)
  280. 'ignore' - ignore the character and continue with the next
  281. 'replace'- replace with a suitable replacement character
  282. 'xmlcharrefreplace' - Replace with the appropriate XML
  283. character reference.
  284. 'backslashreplace' - Replace with backslashed escape
  285. sequences.
  286. 'namereplace' - Replace with \\N{...} escape sequences.
  287. The set of allowed parameter values can be extended via
  288. register_error.
  289. """
  290. self.stream = stream
  291. self.errors = errors
  292. def write(self, object):
  293. """ Writes the object's contents encoded to self.stream.
  294. """
  295. data, consumed = self.encode(object, self.errors)
  296. self.stream.write(data)
  297. def writelines(self, list):
  298. """ Writes the concatenated list of strings to the stream
  299. using .write().
  300. """
  301. self.write(''.join(list))
  302. def reset(self):
  303. """ Flushes and resets the codec buffers used for keeping state.
  304. Calling this method should ensure that the data on the
  305. output is put into a clean state, that allows appending
  306. of new fresh data without having to rescan the whole
  307. stream to recover state.
  308. """
  309. pass
  310. def seek(self, offset, whence=0):
  311. self.stream.seek(offset, whence)
  312. if whence == 0 and offset == 0:
  313. self.reset()
  314. def __getattr__(self, name,
  315. getattr=getattr):
  316. """ Inherit all other methods from the underlying stream.
  317. """
  318. return getattr(self.stream, name)
  319. def __enter__(self):
  320. return self
  321. def __exit__(self, type, value, tb):
  322. self.stream.close()
  323. ###
  324. class StreamReader(Codec):
  325. charbuffertype = str
  326. def __init__(self, stream, errors='strict'):
  327. """ Creates a StreamReader instance.
  328. stream must be a file-like object open for reading.
  329. The StreamReader may use different error handling
  330. schemes by providing the errors keyword argument. These
  331. parameters are predefined:
  332. 'strict' - raise a ValueError (or a subclass)
  333. 'ignore' - ignore the character and continue with the next
  334. 'replace'- replace with a suitable replacement character
  335. 'backslashreplace' - Replace with backslashed escape sequences;
  336. The set of allowed parameter values can be extended via
  337. register_error.
  338. """
  339. self.stream = stream
  340. self.errors = errors
  341. self.bytebuffer = b""
  342. self._empty_charbuffer = self.charbuffertype()
  343. self.charbuffer = self._empty_charbuffer
  344. self.linebuffer = None
  345. def decode(self, input, errors='strict'):
  346. raise NotImplementedError
  347. def read(self, size=-1, chars=-1, firstline=False):
  348. """ Decodes data from the stream self.stream and returns the
  349. resulting object.
  350. chars indicates the number of decoded code points or bytes to
  351. return. read() will never return more data than requested,
  352. but it might return less, if there is not enough available.
  353. size indicates the approximate maximum number of decoded
  354. bytes or code points to read for decoding. The decoder
  355. can modify this setting as appropriate. The default value
  356. -1 indicates to read and decode as much as possible. size
  357. is intended to prevent having to decode huge files in one
  358. step.
  359. If firstline is true, and a UnicodeDecodeError happens
  360. after the first line terminator in the input only the first line
  361. will be returned, the rest of the input will be kept until the
  362. next call to read().
  363. The method should use a greedy read strategy, meaning that
  364. it should read as much data as is allowed within the
  365. definition of the encoding and the given size, e.g. if
  366. optional encoding endings or state markers are available
  367. on the stream, these should be read too.
  368. """
  369. # If we have lines cached, first merge them back into characters
  370. if self.linebuffer:
  371. self.charbuffer = self._empty_charbuffer.join(self.linebuffer)
  372. self.linebuffer = None
  373. if chars < 0:
  374. # For compatibility with other read() methods that take a
  375. # single argument
  376. chars = size
  377. # read until we get the required number of characters (if available)
  378. while True:
  379. # can the request be satisfied from the character buffer?
  380. if chars >= 0:
  381. if len(self.charbuffer) >= chars:
  382. break
  383. # we need more data
  384. if size < 0:
  385. newdata = self.stream.read()
  386. else:
  387. newdata = self.stream.read(size)
  388. # decode bytes (those remaining from the last call included)
  389. data = self.bytebuffer + newdata
  390. if not data:
  391. break
  392. try:
  393. newchars, decodedbytes = self.decode(data, self.errors)
  394. except UnicodeDecodeError as exc:
  395. if firstline:
  396. newchars, decodedbytes = \
  397. self.decode(data[:exc.start], self.errors)
  398. lines = newchars.splitlines(keepends=True)
  399. if len(lines)<=1:
  400. raise
  401. else:
  402. raise
  403. # keep undecoded bytes until the next call
  404. self.bytebuffer = data[decodedbytes:]
  405. # put new characters in the character buffer
  406. self.charbuffer += newchars
  407. # there was no data available
  408. if not newdata:
  409. break
  410. if chars < 0:
  411. # Return everything we've got
  412. result = self.charbuffer
  413. self.charbuffer = self._empty_charbuffer
  414. else:
  415. # Return the first chars characters
  416. result = self.charbuffer[:chars]
  417. self.charbuffer = self.charbuffer[chars:]
  418. return result
  419. def readline(self, size=None, keepends=True):
  420. """ Read one line from the input stream and return the
  421. decoded data.
  422. size, if given, is passed as size argument to the
  423. read() method.
  424. """
  425. # If we have lines cached from an earlier read, return
  426. # them unconditionally
  427. if self.linebuffer:
  428. line = self.linebuffer[0]
  429. del self.linebuffer[0]
  430. if len(self.linebuffer) == 1:
  431. # revert to charbuffer mode; we might need more data
  432. # next time
  433. self.charbuffer = self.linebuffer[0]
  434. self.linebuffer = None
  435. if not keepends:
  436. line = line.splitlines(keepends=False)[0]
  437. return line
  438. readsize = size or 72
  439. line = self._empty_charbuffer
  440. # If size is given, we call read() only once
  441. while True:
  442. data = self.read(readsize, firstline=True)
  443. if data:
  444. # If we're at a "\r" read one extra character (which might
  445. # be a "\n") to get a proper line ending. If the stream is
  446. # temporarily exhausted we return the wrong line ending.
  447. if (isinstance(data, str) and data.endswith("\r")) or \
  448. (isinstance(data, bytes) and data.endswith(b"\r")):
  449. data += self.read(size=1, chars=1)
  450. line += data
  451. lines = line.splitlines(keepends=True)
  452. if lines:
  453. if len(lines) > 1:
  454. # More than one line result; the first line is a full line
  455. # to return
  456. line = lines[0]
  457. del lines[0]
  458. if len(lines) > 1:
  459. # cache the remaining lines
  460. lines[-1] += self.charbuffer
  461. self.linebuffer = lines
  462. self.charbuffer = None
  463. else:
  464. # only one remaining line, put it back into charbuffer
  465. self.charbuffer = lines[0] + self.charbuffer
  466. if not keepends:
  467. line = line.splitlines(keepends=False)[0]
  468. break
  469. line0withend = lines[0]
  470. line0withoutend = lines[0].splitlines(keepends=False)[0]
  471. if line0withend != line0withoutend: # We really have a line end
  472. # Put the rest back together and keep it until the next call
  473. self.charbuffer = self._empty_charbuffer.join(lines[1:]) + \
  474. self.charbuffer
  475. if keepends:
  476. line = line0withend
  477. else:
  478. line = line0withoutend
  479. break
  480. # we didn't get anything or this was our only try
  481. if not data or size is not None:
  482. if line and not keepends:
  483. line = line.splitlines(keepends=False)[0]
  484. break
  485. if readsize < 8000:
  486. readsize *= 2
  487. return line
  488. def readlines(self, sizehint=None, keepends=True):
  489. """ Read all lines available on the input stream
  490. and return them as a list.
  491. Line breaks are implemented using the codec's decoder
  492. method and are included in the list entries.
  493. sizehint, if given, is ignored since there is no efficient
  494. way to finding the true end-of-line.
  495. """
  496. data = self.read()
  497. return data.splitlines(keepends)
  498. def reset(self):
  499. """ Resets the codec buffers used for keeping state.
  500. Note that no stream repositioning should take place.
  501. This method is primarily intended to be able to recover
  502. from decoding errors.
  503. """
  504. self.bytebuffer = b""
  505. self.charbuffer = self._empty_charbuffer
  506. self.linebuffer = None
  507. def seek(self, offset, whence=0):
  508. """ Set the input stream's current position.
  509. Resets the codec buffers used for keeping state.
  510. """
  511. self.stream.seek(offset, whence)
  512. self.reset()
  513. def __next__(self):
  514. """ Return the next decoded line from the input stream."""
  515. line = self.readline()
  516. if line:
  517. return line
  518. raise StopIteration
  519. def __iter__(self):
  520. return self
  521. def __getattr__(self, name,
  522. getattr=getattr):
  523. """ Inherit all other methods from the underlying stream.
  524. """
  525. return getattr(self.stream, name)
  526. def __enter__(self):
  527. return self
  528. def __exit__(self, type, value, tb):
  529. self.stream.close()
  530. ###
  531. class StreamReaderWriter:
  532. """ StreamReaderWriter instances allow wrapping streams which
  533. work in both read and write modes.
  534. The design is such that one can use the factory functions
  535. returned by the codec.lookup() function to construct the
  536. instance.
  537. """
  538. # Optional attributes set by the file wrappers below
  539. encoding = 'unknown'
  540. def __init__(self, stream, Reader, Writer, errors='strict'):
  541. """ Creates a StreamReaderWriter instance.
  542. stream must be a Stream-like object.
  543. Reader, Writer must be factory functions or classes
  544. providing the StreamReader, StreamWriter interface resp.
  545. Error handling is done in the same way as defined for the
  546. StreamWriter/Readers.
  547. """
  548. self.stream = stream
  549. self.reader = Reader(stream, errors)
  550. self.writer = Writer(stream, errors)
  551. self.errors = errors
  552. def read(self, size=-1):
  553. return self.reader.read(size)
  554. def readline(self, size=None):
  555. return self.reader.readline(size)
  556. def readlines(self, sizehint=None):
  557. return self.reader.readlines(sizehint)
  558. def __next__(self):
  559. """ Return the next decoded line from the input stream."""
  560. return next(self.reader)
  561. def __iter__(self):
  562. return self
  563. def write(self, data):
  564. return self.writer.write(data)
  565. def writelines(self, list):
  566. return self.writer.writelines(list)
  567. def reset(self):
  568. self.reader.reset()
  569. self.writer.reset()
  570. def seek(self, offset, whence=0):
  571. self.stream.seek(offset, whence)
  572. self.reader.reset()
  573. if whence == 0 and offset == 0:
  574. self.writer.reset()
  575. def __getattr__(self, name,
  576. getattr=getattr):
  577. """ Inherit all other methods from the underlying stream.
  578. """
  579. return getattr(self.stream, name)
  580. # these are needed to make "with StreamReaderWriter(...)" work properly
  581. def __enter__(self):
  582. return self
  583. def __exit__(self, type, value, tb):
  584. self.stream.close()
  585. ###
  586. class StreamRecoder:
  587. """ StreamRecoder instances translate data from one encoding to another.
  588. They use the complete set of APIs returned by the
  589. codecs.lookup() function to implement their task.
  590. Data written to the StreamRecoder is first decoded into an
  591. intermediate format (depending on the "decode" codec) and then
  592. written to the underlying stream using an instance of the provided
  593. Writer class.
  594. In the other direction, data is read from the underlying stream using
  595. a Reader instance and then encoded and returned to the caller.
  596. """
  597. # Optional attributes set by the file wrappers below
  598. data_encoding = 'unknown'
  599. file_encoding = 'unknown'
  600. def __init__(self, stream, encode, decode, Reader, Writer,
  601. errors='strict'):
  602. """ Creates a StreamRecoder instance which implements a two-way
  603. conversion: encode and decode work on the frontend (the
  604. data visible to .read() and .write()) while Reader and Writer
  605. work on the backend (the data in stream).
  606. You can use these objects to do transparent
  607. transcodings from e.g. latin-1 to utf-8 and back.
  608. stream must be a file-like object.
  609. encode and decode must adhere to the Codec interface; Reader and
  610. Writer must be factory functions or classes providing the
  611. StreamReader and StreamWriter interfaces resp.
  612. Error handling is done in the same way as defined for the
  613. StreamWriter/Readers.
  614. """
  615. self.stream = stream
  616. self.encode = encode
  617. self.decode = decode
  618. self.reader = Reader(stream, errors)
  619. self.writer = Writer(stream, errors)
  620. self.errors = errors
  621. def read(self, size=-1):
  622. data = self.reader.read(size)
  623. data, bytesencoded = self.encode(data, self.errors)
  624. return data
  625. def readline(self, size=None):
  626. if size is None:
  627. data = self.reader.readline()
  628. else:
  629. data = self.reader.readline(size)
  630. data, bytesencoded = self.encode(data, self.errors)
  631. return data
  632. def readlines(self, sizehint=None):
  633. data = self.reader.read()
  634. data, bytesencoded = self.encode(data, self.errors)
  635. return data.splitlines(keepends=True)
  636. def __next__(self):
  637. """ Return the next decoded line from the input stream."""
  638. data = next(self.reader)
  639. data, bytesencoded = self.encode(data, self.errors)
  640. return data
  641. def __iter__(self):
  642. return self
  643. def write(self, data):
  644. data, bytesdecoded = self.decode(data, self.errors)
  645. return self.writer.write(data)
  646. def writelines(self, list):
  647. data = ''.join(list)
  648. data, bytesdecoded = self.decode(data, self.errors)
  649. return self.writer.write(data)
  650. def reset(self):
  651. self.reader.reset()
  652. self.writer.reset()
  653. def __getattr__(self, name,
  654. getattr=getattr):
  655. """ Inherit all other methods from the underlying stream.
  656. """
  657. return getattr(self.stream, name)
  658. def __enter__(self):
  659. return self
  660. def __exit__(self, type, value, tb):
  661. self.stream.close()
  662. ### Shortcuts
  663. def open(filename, mode='r', encoding=None, errors='strict', buffering=1):
  664. """ Open an encoded file using the given mode and return
  665. a wrapped version providing transparent encoding/decoding.
  666. Note: The wrapped version will only accept the object format
  667. defined by the codecs, i.e. Unicode objects for most builtin
  668. codecs. Output is also codec dependent and will usually be
  669. Unicode as well.
  670. Underlying encoded files are always opened in binary mode.
  671. The default file mode is 'r', meaning to open the file in read mode.
  672. encoding specifies the encoding which is to be used for the
  673. file.
  674. errors may be given to define the error handling. It defaults
  675. to 'strict' which causes ValueErrors to be raised in case an
  676. encoding error occurs.
  677. buffering has the same meaning as for the builtin open() API.
  678. It defaults to line buffered.
  679. The returned wrapped file object provides an extra attribute
  680. .encoding which allows querying the used encoding. This
  681. attribute is only available if an encoding was specified as
  682. parameter.
  683. """
  684. if encoding is not None and \
  685. 'b' not in mode:
  686. # Force opening of the file in binary mode
  687. mode = mode + 'b'
  688. file = builtins.open(filename, mode, buffering)
  689. if encoding is None:
  690. return file
  691. info = lookup(encoding)
  692. srw = StreamReaderWriter(file, info.streamreader, info.streamwriter, errors)
  693. # Add attributes to simplify introspection
  694. srw.encoding = encoding
  695. return srw
  696. def EncodedFile(file, data_encoding, file_encoding=None, errors='strict'):
  697. """ Return a wrapped version of file which provides transparent
  698. encoding translation.
  699. Data written to the wrapped file is decoded according
  700. to the given data_encoding and then encoded to the underlying
  701. file using file_encoding. The intermediate data type
  702. will usually be Unicode but depends on the specified codecs.
  703. Bytes read from the file are decoded using file_encoding and then
  704. passed back to the caller encoded using data_encoding.
  705. If file_encoding is not given, it defaults to data_encoding.
  706. errors may be given to define the error handling. It defaults
  707. to 'strict' which causes ValueErrors to be raised in case an
  708. encoding error occurs.
  709. The returned wrapped file object provides two extra attributes
  710. .data_encoding and .file_encoding which reflect the given
  711. parameters of the same name. The attributes can be used for
  712. introspection by Python programs.
  713. """
  714. if file_encoding is None:
  715. file_encoding = data_encoding
  716. data_info = lookup(data_encoding)
  717. file_info = lookup(file_encoding)
  718. sr = StreamRecoder(file, data_info.encode, data_info.decode,
  719. file_info.streamreader, file_info.streamwriter, errors)
  720. # Add attributes to simplify introspection
  721. sr.data_encoding = data_encoding
  722. sr.file_encoding = file_encoding
  723. return sr
  724. ### Helpers for codec lookup
  725. def getencoder(encoding):
  726. """ Lookup up the codec for the given encoding and return
  727. its encoder function.
  728. Raises a LookupError in case the encoding cannot be found.
  729. """
  730. return lookup(encoding).encode
  731. def getdecoder(encoding):
  732. """ Lookup up the codec for the given encoding and return
  733. its decoder function.
  734. Raises a LookupError in case the encoding cannot be found.
  735. """
  736. return lookup(encoding).decode
  737. def getincrementalencoder(encoding):
  738. """ Lookup up the codec for the given encoding and return
  739. its IncrementalEncoder class or factory function.
  740. Raises a LookupError in case the encoding cannot be found
  741. or the codecs doesn't provide an incremental encoder.
  742. """
  743. encoder = lookup(encoding).incrementalencoder
  744. if encoder is None:
  745. raise LookupError(encoding)
  746. return encoder
  747. def getincrementaldecoder(encoding):
  748. """ Lookup up the codec for the given encoding and return
  749. its IncrementalDecoder class or factory function.
  750. Raises a LookupError in case the encoding cannot be found
  751. or the codecs doesn't provide an incremental decoder.
  752. """
  753. decoder = lookup(encoding).incrementaldecoder
  754. if decoder is None:
  755. raise LookupError(encoding)
  756. return decoder
  757. def getreader(encoding):
  758. """ Lookup up the codec for the given encoding and return
  759. its StreamReader class or factory function.
  760. Raises a LookupError in case the encoding cannot be found.
  761. """
  762. return lookup(encoding).streamreader
  763. def getwriter(encoding):
  764. """ Lookup up the codec for the given encoding and return
  765. its StreamWriter class or factory function.
  766. Raises a LookupError in case the encoding cannot be found.
  767. """
  768. return lookup(encoding).streamwriter
  769. def iterencode(iterator, encoding, errors='strict', **kwargs):
  770. """
  771. Encoding iterator.
  772. Encodes the input strings from the iterator using an IncrementalEncoder.
  773. errors and kwargs are passed through to the IncrementalEncoder
  774. constructor.
  775. """
  776. encoder = getincrementalencoder(encoding)(errors, **kwargs)
  777. for input in iterator:
  778. output = encoder.encode(input)
  779. if output:
  780. yield output
  781. output = encoder.encode("", True)
  782. if output:
  783. yield output
  784. def iterdecode(iterator, encoding, errors='strict', **kwargs):
  785. """
  786. Decoding iterator.
  787. Decodes the input strings from the iterator using an IncrementalDecoder.
  788. errors and kwargs are passed through to the IncrementalDecoder
  789. constructor.
  790. """
  791. decoder = getincrementaldecoder(encoding)(errors, **kwargs)
  792. for input in iterator:
  793. output = decoder.decode(input)
  794. if output:
  795. yield output
  796. output = decoder.decode(b"", True)
  797. if output:
  798. yield output
  799. ### Helpers for charmap-based codecs
  800. def make_identity_dict(rng):
  801. """ make_identity_dict(rng) -> dict
  802. Return a dictionary where elements of the rng sequence are
  803. mapped to themselves.
  804. """
  805. return {i:i for i in rng}
  806. def make_encoding_map(decoding_map):
  807. """ Creates an encoding map from a decoding map.
  808. If a target mapping in the decoding map occurs multiple
  809. times, then that target is mapped to None (undefined mapping),
  810. causing an exception when encountered by the charmap codec
  811. during translation.
  812. One example where this happens is cp875.py which decodes
  813. multiple character to \\u001a.
  814. """
  815. m = {}
  816. for k,v in decoding_map.items():
  817. if not v in m:
  818. m[v] = k
  819. else:
  820. m[v] = None
  821. return m
  822. ### error handlers
  823. try:
  824. strict_errors = lookup_error("strict")
  825. ignore_errors = lookup_error("ignore")
  826. replace_errors = lookup_error("replace")
  827. xmlcharrefreplace_errors = lookup_error("xmlcharrefreplace")
  828. backslashreplace_errors = lookup_error("backslashreplace")
  829. namereplace_errors = lookup_error("namereplace")
  830. except LookupError:
  831. # In --disable-unicode builds, these error handler are missing
  832. strict_errors = None
  833. ignore_errors = None
  834. replace_errors = None
  835. xmlcharrefreplace_errors = None
  836. backslashreplace_errors = None
  837. namereplace_errors = None
  838. # Tell modulefinder that using codecs probably needs the encodings
  839. # package
  840. _false = 0
  841. if _false:
  842. import encodings
  843. ### Tests
  844. if __name__ == '__main__':
  845. # Make stdout translate Latin-1 output into UTF-8 output
  846. sys.stdout = EncodedFile(sys.stdout, 'latin-1', 'utf-8')
  847. # Have stdin translate Latin-1 input into UTF-8 input
  848. sys.stdin = EncodedFile(sys.stdin, 'utf-8', 'latin-1')
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...