|
| 1 | +"""Byte size model with unit conversions.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from dataclasses import dataclass |
| 6 | + |
| 7 | + |
| 8 | +@dataclass(frozen=True, order=True) |
| 9 | +class ByteSize: |
| 10 | + """Represents a size in bytes, with convenience conversions and formatting.""" |
| 11 | + |
| 12 | + value: int |
| 13 | + |
| 14 | + # Binary (1024-based) unit thresholds |
| 15 | + KIBI = 1024 |
| 16 | + MEBI = 1024**2 |
| 17 | + GIBI = 1024**3 |
| 18 | + TEBI = 1024**4 |
| 19 | + |
| 20 | + def __post_init__(self) -> None: |
| 21 | + if self.value < 0: |
| 22 | + raise ValueError(f"ByteSize cannot be negative: {self.value}") |
| 23 | + if not isinstance(self.value, int): |
| 24 | + raise TypeError(f"ByteSize value must be int, got {type(self.value).__name__}") |
| 25 | + |
| 26 | + def to_bytes(self) -> int: |
| 27 | + """Return the size in bytes.""" |
| 28 | + return self.value |
| 29 | + |
| 30 | + def to_kibi(self) -> float: |
| 31 | + """Return the size in kibibytes (KiB).""" |
| 32 | + return self.value / self.KIBI |
| 33 | + |
| 34 | + def to_mibi(self) -> float: |
| 35 | + """Return the size in mebibytes (MiB).""" |
| 36 | + return self.value / self.MEBI |
| 37 | + |
| 38 | + def to_gibi(self) -> float: |
| 39 | + """Return the size in gibibytes (GiB).""" |
| 40 | + return self.value / self.GIBI |
| 41 | + |
| 42 | + def to_tebi(self) -> float: |
| 43 | + """Return the size in tebibytes (TiB).""" |
| 44 | + return self.value / self.TEBI |
| 45 | + |
| 46 | + def to_human(self) -> str: |
| 47 | + """Return a human-readable string with the appropriate binary unit.""" |
| 48 | + if self.value < self.KIBI: |
| 49 | + return f"{self.value}B" |
| 50 | + elif self.value < self.MEBI: |
| 51 | + return f"{self.to_kibi():.2f}KiB" |
| 52 | + elif self.value < self.GIBI: |
| 53 | + return f"{self.to_mibi():.2f}MiB" |
| 54 | + elif self.value < self.TEBI: |
| 55 | + return f"{self.to_gibi():.2f}GiB" |
| 56 | + else: |
| 57 | + return f"{self.to_tebi():.2f}TiB" |
| 58 | + |
| 59 | + def __str__(self) -> str: |
| 60 | + return self.to_human() |
| 61 | + |
| 62 | + def __repr__(self) -> str: |
| 63 | + return f"ByteSize({self.value}B)" |
| 64 | + |
| 65 | + def __add__(self, other: ByteSize) -> ByteSize: |
| 66 | + return ByteSize(self.value + other.value) |
| 67 | + |
| 68 | + def __sub__(self, other: ByteSize) -> ByteSize: |
| 69 | + result = self.value - other.value |
| 70 | + if result < 0: |
| 71 | + raise ValueError("Subtraction would result in negative ByteSize") |
| 72 | + return ByteSize(result) |
| 73 | + |
| 74 | + def __radd__(self, other: int) -> ByteSize: |
| 75 | + # allows sum([ByteSize(1), ByteSize(2)]) to work, since sum() starts with 0 |
| 76 | + if other == 0: |
| 77 | + return self |
| 78 | + return NotImplemented |
| 79 | + |
| 80 | + @classmethod |
| 81 | + def from_bytes(cls, bs: int) -> ByteSize: |
| 82 | + """Create a ByteSize from a byte count.""" |
| 83 | + return ByteSize(value=bs) |
| 84 | + |
| 85 | + @classmethod |
| 86 | + def from_kibi(cls, kb: float) -> ByteSize: |
| 87 | + """Create a ByteSize from a kibibyte value.""" |
| 88 | + return ByteSize(value=int(kb * cls.KIBI)) |
| 89 | + |
| 90 | + @classmethod |
| 91 | + def from_mibi(cls, mb: float) -> ByteSize: |
| 92 | + """Create a ByteSize from a mebibyte value.""" |
| 93 | + return ByteSize(value=int(mb * cls.MEBI)) |
| 94 | + |
| 95 | + @classmethod |
| 96 | + def from_gibi(cls, gb: float) -> ByteSize: |
| 97 | + """Create a ByteSize from a gibibyte value.""" |
| 98 | + return ByteSize(value=int(gb * cls.GIBI)) |
| 99 | + |
| 100 | + @classmethod |
| 101 | + def from_tebi(cls, tib: float) -> ByteSize: |
| 102 | + """Create a ByteSize from a tebibyte value.""" |
| 103 | + return cls(value=round(tib * cls.TEBI)) |
| 104 | + |
| 105 | + @classmethod |
| 106 | + def zero(cls) -> ByteSize: |
| 107 | + """Create a byte size with value 0.""" |
| 108 | + return ByteSize(0) |
0 commit comments