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 else:
43 raise TypeError("Expected unicode or bytes, got %r" % s)
44
45
46 - def u(s, encoding='utf8'):
47 """cast bytes or unicode to unicode"""
48 if isinstance(s, str):
49 return s.decode(encoding)
50 elif isinstance(s, unicode):
51 return s
52 else:
53 raise TypeError("Expected unicode or bytes, got %r" % s)
54
55
58
59
60 try:
61 import cStringIO
62
63 StringIO = cStringIO.StringIO
64 except ImportError:
65 import StringIO
66
67 StringIO = StringIO.StringIO
68
69 BytesIO = StringIO
70
71
73 return callable(c)
74
75
77 return c.next
78
79
82
83
87
88
89 try:
90 len(X())
91 except OverflowError:
92
93 MAXSIZE = int((1 << 31) - 1)
94 else:
95
96 MAXSIZE = int((1 << 63) - 1)
97 del X
98 else:
99 import collections
100 import struct
101 string_types = str
102 text_type = str
103 bytes = bytes
104 bytes_types = bytes
105 integer_types = int
108 input = input
109 decodebytes = base64.decodebytes
110 encodebytes = base64.encodebytes
111
114
116
117 if not isinstance(c, int):
118 c = ord(c)
119 return c
120
122 assert isinstance(c, int)
123 return struct.pack('B', c)
124
126 assert isinstance(c, int)
127 return struct.pack('B', c & mask)
128
129 - def b(s, encoding='utf8'):
130 """cast unicode or bytes to bytes"""
131 if isinstance(s, bytes):
132 return s
133 elif isinstance(s, str):
134 return s.encode(encoding)
135 else:
136 raise TypeError("Expected unicode or bytes, got %r" % s)
137
138 - def u(s, encoding='utf8'):
139 """cast bytes or unicode to unicode"""
140 if isinstance(s, bytes):
141 return s.decode(encoding)
142 elif isinstance(s, str):
143 return s
144 else:
145 raise TypeError("Expected unicode or bytes, got %r" % s)
146
148 return s.decode() if isinstance(s, bytes) else s
149
150 import io
151 StringIO = io.StringIO
152 BytesIO = io.BytesIO
153
155 return isinstance(c, collections.Callable)
156
159
160 next = next
161
162 MAXSIZE = sys.maxsize
163