Debian Codegraph @

pypy/module/binascii/interp_hexlify.py

raw symbols SCIP
1 from pypy.interpreter.error import oefmt
2 from pypy.interpreter.gateway import unwrap_spec
3 from rpython.rlib.rstring import StringBuilder
4 from rpython.rlib.rarithmetic import ovfcheck
5 from pypy.module.binascii.interp_binascii import raise_Error
6 from pypy.module.binascii.interp_binascii import AsciiBufferUnwrapper
7
8 # ____________________________________________________________
9
10 def _value2char(value):
11 if value < 10:
12 return chr(ord('0') + value)
13 else:
14 return chr((ord('a')-10) + value)
15 _value2char._always_inline_ = True
16
17 @unwrap_spec(data='bufferstr')
18 def hexlify(space, data, w_sep=None, w_bytes_per_sep=None):
19 '''Hexadecimal representation of binary data.
20
21 sep
22 An optional single character or byte to separate hex bytes.
23 bytes_per_sep
24 How many bytes between separators. Positive values count from the
25 right, negative values count from the left.
26
27 The return value is a bytes object. This function is also
28 available as "b2a_hex()".'''
29 from pypy.objspace.std.bytearrayobject import _array_to_hexstring, unwrap_hex_sep_arguments
30 from pypy.interpreter.buffer import StringBuffer
31 sep, bytes_per_sep = unwrap_hex_sep_arguments(space, w_sep, w_bytes_per_sep)
32 w_res = _array_to_hexstring(space, StringBuffer(data), 0, 1,
33 len(data), sep=sep, bytes_per_sep=bytes_per_sep)
34 # it's a string, need to turn it into a bytes
35 return space.newbytes(space.text_w(w_res))
36
37 # ____________________________________________________________
38
39 def _char2value(space, c):
40 if c <= '9':
41 if c >= '0':
42 return ord(c) - ord('0')
43 elif c <= 'F':
44 if c >= 'A':
45 return ord(c) - (ord('A')-10)
46 elif c <= 'f':
47 if c >= 'a':
48 return ord(c) - (ord('a')-10)
49 raise_Error(space, 'Non-hexadecimal digit found')
50 _char2value._always_inline_ = True
51
52 @unwrap_spec(hexstr=AsciiBufferUnwrapper)
53 def unhexlify(space, hexstr):
54 '''Binary data of hexadecimal representation.
55 hexstr must contain an even number of hex digits (upper or lower case).
56 This function is also available as "unhexlify()".'''
57 if len(hexstr) & 1:
58 raise_Error(space, 'Odd-length string')
59 res = StringBuilder(len(hexstr) >> 1)
60 for i in range(0, len(hexstr), 2):
61 a = _char2value(space, hexstr[i])
62 b = _char2value(space, hexstr[i+1])
63 res.append(chr((a << 4) | b))
64 return space.newbytes(res.build())