Debian Codegraph @

rpython/rlib/rstruct/unichar.py

raw symbols SCIP
1 """
2 Helpers to pack and unpack a unicode character into raw bytes.
3 """
4
5 import sys
6
7 UNICODE_SIZE = 4
8 BIGENDIAN = sys.byteorder == "big"
9
10 def pack_unichar(unich, buf, pos):
11 pack_codepoint(ord(unich), buf, pos)
12
13 def pack_codepoint(unich, buf, pos):
14 if UNICODE_SIZE == 2:
15 if BIGENDIAN:
16 buf.setitem(pos, chr(unich >> 8))
17 buf.setitem(pos+1, chr(unich & 0xFF))
18 else:
19 buf.setitem(pos, chr(unich & 0xFF))
20 buf.setitem(pos+1, chr(unich >> 8))
21 else:
22 if BIGENDIAN:
23 buf.setitem(pos, chr(unich >> 24))
24 buf.setitem(pos+1, chr((unich >> 16) & 0xFF))
25 buf.setitem(pos+2, chr((unich >> 8) & 0xFF))
26 buf.setitem(pos+3, chr(unich & 0xFF))
27 else:
28 buf.setitem(pos, chr(unich & 0xFF))
29 buf.setitem(pos+1, chr((unich >> 8) & 0xFF))
30 buf.setitem(pos+2, chr((unich >> 16) & 0xFF))
31 buf.setitem(pos+3, chr(unich >> 24))
32
33 def unpack_codepoint(rawstring):
34 assert len(rawstring) == UNICODE_SIZE
35 if UNICODE_SIZE == 2:
36 if BIGENDIAN:
37 n = (ord(rawstring[0]) << 8 |
38 ord(rawstring[1]))
39 else:
40 n = (ord(rawstring[0]) |
41 ord(rawstring[1]) << 8)
42 else:
43 if BIGENDIAN:
44 n = (ord(rawstring[0]) << 24 |
45 ord(rawstring[1]) << 16 |
46 ord(rawstring[2]) << 8 |
47 ord(rawstring[3]))
48 else:
49 n = (ord(rawstring[0]) |
50 ord(rawstring[1]) << 8 |
51 ord(rawstring[2]) << 16 |
52 ord(rawstring[3]) << 24)
53 return n
54
55 def unpack_unichar(rawstring):
56 return unichr(unpack_codepoint(rawstring))