blob: 95abb056248af8ba1a90cc6232d42d6af24735c7 [file] [log] [blame]
Guido van Rossum0229bf62000-03-10 23:17:24 +00001""" Python 'utf-16' Codec
2
3
4Written by Marc-Andre Lemburg (mal@lemburg.com).
5
6(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
7
8"""
Marc-André Lemburg92b550c2001-06-19 20:07:51 +00009import codecs, sys
Guido van Rossum0229bf62000-03-10 23:17:24 +000010
11### Codec APIs
12
Walter Dörwald69652032004-09-07 20:24:22 +000013encode = codecs.utf_16_encode
Guido van Rossum0229bf62000-03-10 23:17:24 +000014
Walter Dörwald69652032004-09-07 20:24:22 +000015def decode(input, errors='strict'):
16 return codecs.utf_16_decode(input, errors, True)
Guido van Rossum0229bf62000-03-10 23:17:24 +000017
Walter Dörwald69652032004-09-07 20:24:22 +000018class StreamWriter(codecs.StreamWriter):
Marc-André Lemburg92b550c2001-06-19 20:07:51 +000019 def __init__(self, stream, errors='strict'):
Walter Dörwald69652032004-09-07 20:24:22 +000020 self.bom_written = False
Marc-André Lemburg92b550c2001-06-19 20:07:51 +000021 codecs.StreamWriter.__init__(self, stream, errors)
22
Walter Dörwald69652032004-09-07 20:24:22 +000023 def encode(self, input, errors='strict'):
24 self.bom_written = True
25 result = codecs.utf_16_encode(input, errors)
26 if sys.byteorder == 'little':
27 self.encode = codecs.utf_16_le_encode
28 else:
29 self.encode = codecs.utf_16_be_encode
Marc-André Lemburg92b550c2001-06-19 20:07:51 +000030 return result
Tim Peters469cdad2002-08-08 20:19:19 +000031
Walter Dörwald69652032004-09-07 20:24:22 +000032class StreamReader(codecs.StreamReader):
Marc-André Lemburg92b550c2001-06-19 20:07:51 +000033
Walter Dörwald729c31f2005-03-14 19:06:30 +000034 def reset(self):
35 codecs.StreamReader.reset(self)
36 try:
37 del self.decode
38 except AttributeError:
39 pass
40
Walter Dörwald69652032004-09-07 20:24:22 +000041 def decode(self, input, errors='strict'):
42 (object, consumed, byteorder) = \
43 codecs.utf_16_ex_decode(input, errors, 0, False)
44 if byteorder == -1:
45 self.decode = codecs.utf_16_le_decode
46 elif byteorder == 1:
47 self.decode = codecs.utf_16_be_decode
48 elif consumed>=2:
49 raise UnicodeError,"UTF-16 stream does not start with BOM"
50 return (object, consumed)
Marc-André Lemburg3ccb09c2002-04-05 12:12:00 +000051
Guido van Rossum0229bf62000-03-10 23:17:24 +000052### encodings module API
53
54def getregentry():
55
Walter Dörwald69652032004-09-07 20:24:22 +000056 return (encode,decode,StreamReader,StreamWriter)