1 import sys
2 import base64
3
4 __all__ = ['PY2', 'string_types', 'integer_types', 'text_type', 'bytes_types', 'bytes', 'long', 'input',
5 'decodebytes', 'encodebytes', 'bytestring', 'byte_ord', 'byte_chr', 'byte_mask',
6 'b', 'u', 'b2s', 'StringIO', 'BytesIO', 'is_callable', 'MAXSIZE', 'next']
7
8 PY2 = sys.version_info[0] < 3
9
10 if PY2:
11 string_types = basestring
12 text_type = unicode
13 bytes_types = str
14 bytes = str
15 integer_types = (int, long)
16 long = long
17 input = raw_input
18 decodebytes = base64.decodestring
19 encodebytes = base64.encodestring
20
21
23 if isinstance(s, unicode):
24 return s.encode('utf-8')
25 return s
26
27
28 byte_ord = ord
29 byte_chr = chr
30
31
33 return chr(ord(c) & mask)
34
35
36 - def b(s, encoding='utf8'):
37 """cast unicode or bytes to bytes"""
38 if isinstance(s, str):
39 return s
40 elif isinstance(s, unicode):
41 return s.encode(encoding)
42 elif isinstance(s, buffer):
43 return s
44 else:
45 raise TypeError("Expected unicode or bytes, got %r" % s)
46
47
48 - def u(s, encoding='utf8'):
49 """cast bytes or unicode to unicode"""
50 if isinstance(s, str):
51 return s.decode(encoding)
52 elif isinstance(s, unicode):
53 return s
54 elif isinstance(s, buffer):
55 return s.decode(encoding)
56 else:
57 raise TypeError("Expected unicode or bytes, got %r" % s)
58
59
62
63
64 try:
65 import cStringIO
66
67 StringIO = cStringIO.StringIO
68 except ImportError:
69 import StringIO
70
71 StringIO = StringIO.StringIO
72
73 BytesIO = StringIO
74
75
77 return callable(c)
78
79
81 return c.next
82
83
86
87
91
92
93 try:
94 len(X())
95 except OverflowError:
96
97 MAXSIZE = int((1 << 31) - 1)
98 else:
99
100 MAXSIZE = int((1 << 63) - 1)
101 del X
102 else:
103 import collections
104 import struct
105 string_types = str
106 text_type = str
107 bytes = bytes
108 bytes_types = bytes
109 integer_types = int
112 input = input
113 decodebytes = base64.decodebytes
114 encodebytes = base64.encodebytes
115
118
120
121 if not isinstance(c, int):
122 c = ord(c)
123 return c
124
126 assert isinstance(c, int)
127 return struct.pack('B', c)
128
130 assert isinstance(c, int)
131 return struct.pack('B', c & mask)
132
133 - def b(s, encoding='utf8'):
134 """cast unicode or bytes to bytes"""
135 if isinstance(s, bytes):
136 return s
137 elif isinstance(s, str):
138 return s.encode(encoding)
139 else:
140 raise TypeError("Expected unicode or bytes, got %r" % s)
141
142 - def u(s, encoding='utf8'):
143 """cast bytes or unicode to unicode"""
144 if isinstance(s, bytes):
145 return s.decode(encoding)
146 elif isinstance(s, str):
147 return s
148 else:
149 raise TypeError("Expected unicode or bytes, got %r" % s)
150
152 return s.decode() if isinstance(s, bytes) else s
153
154 import io
155 StringIO = io.StringIO
156 BytesIO = io.BytesIO
157
159 return isinstance(c, collections.Callable)
160
163
164 next = next
165
166 MAXSIZE = sys.maxsize
167