From 7eb1f47084359d0395fd87a108b02e31b6253f16 Mon Sep 17 00:00:00 2001 From: codefiles <11915375+codefiles@users.noreply.github.com> Date: Sat, 23 Nov 2024 02:53:32 -0500 Subject: [PATCH] Use binary units (#2917) --- archinstall/lib/disk/device_model.py | 41 +++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/archinstall/lib/disk/device_model.py b/archinstall/lib/disk/device_model.py index 9d5fb2c9cb..e84cbd5f12 100644 --- a/archinstall/lib/disk/device_model.py +++ b/archinstall/lib/disk/device_model.py @@ -146,6 +146,11 @@ class PartitionTable(Enum): MBR = 'msdos' +class Units(Enum): + BINARY = 'binary' + DECIMAL = 'decimal' + + class Unit(Enum): B = 1 # byte kB = 1000 ** 1 # kilobyte @@ -176,6 +181,10 @@ def get_all_units() -> list[str]: def get_si_units() -> list[Unit]: return [u for u in Unit if 'i' not in u.name and u.name != 'sectors'] + @staticmethod + def get_binary_units() -> list[Unit]: + return [u for u in Unit if 'i' in u.name or u.name == 'B'] + @dataclass class SectorSize: @@ -278,8 +287,32 @@ def format_size( return f'{target_size.value} {target_unit.name}' return f'{target_size.value}' - def format_highest(self, include_unit: bool = True) -> str: + def binary_unit_highest(self, include_unit: bool = True) -> str: + binary_units = Unit.get_binary_units() + + size = float(self._normalize()) + unit = Unit.KiB + base_value = unit.value + + for binary_unit in binary_units: + unit = binary_unit + if size < base_value: + break + size /= base_value + + formatted_size = f"{size:.1f}" + + if formatted_size.endswith('.0'): + formatted_size = formatted_size[:-2] + + if not include_unit: + return formatted_size + + return f'{formatted_size} {unit.name}' + + def si_unit_highest(self, include_unit: bool = True) -> str: si_units = Unit.get_si_units() + all_si_values = [self.convert(si) for si in si_units] filtered = filter(lambda x: x.value >= 1, all_si_values) @@ -291,6 +324,12 @@ def format_highest(self, include_unit: bool = True) -> str: return f'{si_value.value} {si_value.unit.name}' return f'{si_value.value}' + def format_highest(self, include_unit: bool = True, units: Units = Units.BINARY) -> str: + if units == Units.BINARY: + return self.binary_unit_highest(include_unit) + else: + return self.si_unit_highest(include_unit) + def _normalize(self) -> int: """ will normalize the value of the unit to Byte