Upstream version 8.36.161.0
[platform/framework/web/crosswalk.git] / src / third_party / pyelftools / elftools / construct / lib / hex.py
1 from .py3compat import byte2int, int2byte, bytes2str
2
3
4 # Map an integer in the inclusive range 0-255 to its string byte representation
5 _printable = dict((i, ".") for i in range(256))
6 _printable.update((i, bytes2str(int2byte(i))) for i in range(32, 128))
7
8
9 def hexdump(data, linesize):
10     """
11     data is a bytes object. The returned result is a string.
12     """
13     prettylines = []
14     if len(data) < 65536:
15         fmt = "%%04X   %%-%ds   %%s"
16     else:
17         fmt = "%%08X   %%-%ds   %%s"
18     fmt = fmt % (3 * linesize - 1,)
19     for i in range(0, len(data), linesize):
20         line = data[i : i + linesize]
21         hextext = " ".join('%02x' % byte2int(b) for b in line)
22         rawtext = "".join(_printable[byte2int(b)] for b in line)
23         prettylines.append(fmt % (i, str(hextext), str(rawtext)))
24     return prettylines
25
26
27 class HexString(bytes):
28     """
29     Represents bytes that will be hex-dumped to a string when its string
30     representation is requested.
31     """
32     def __init__(self, data, linesize = 16):
33         self.linesize = linesize
34
35     def __new__(cls, data, *args, **kwargs):
36         return bytes.__new__(cls, data)
37         
38     def __str__(self):
39         if not self:
40             return "''"
41         sep = "\n"
42         return sep + sep.join(
43             hexdump(self, self.linesize))
44