aboutsummaryrefslogtreecommitdiff
path: root/libs/kstd/gdb/units.py
blob: 2ba533bd189c7e5fbb76e1602689f02727760d01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import gdb


class KstdBytesPrinter(gdb.ValuePrinter):

    def __init__(self, val):
        self.__val = val
        self.__value = val["value"]

    def to_string(self):
        units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']
        size_in_bytes = int(self.__value)

        if size_in_bytes == 0:
            return "0 B"

        sign = "-" if size_in_bytes < 0 else ""
        absolute_size = abs(size_in_bytes)

        import math

        index = int(math.floor(math.log(absolute_size, 1024)))
        index = min(index, len(units) - 1)
        divisor = math.pow(1024, index)
        size = round(absolute_size / divisor, 2)

        return f"{sign}{size} {units[index]}"

    def children(self):
        yield ("value", self.__value)