| 1856 | |
| 1857 | |
| 1858 | class HumanBytes: |
| 1859 | # Human-readable formatting of bytes, using binary (powers of 1024) or metric (powers of 1000) representation. |
| 1860 | METRIC_LABELS = ["bytes", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] |
| 1861 | BINARY_LABELS = ["bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"] |
| 1862 | PRECISION_OFFSETS = [0.5, 0.05, 0.005, 0.0005] |
| 1863 | PRECISION_FORMATS = ["{}{:.0f} {}", "{}{:.1f} {}", "{}{:.2f} {}", "{}{:.3f} {}"] |
| 1864 | |
| 1865 | @classmethod |
| 1866 | def format(cls, num, metric=False, precision=1) -> str: |
| 1867 | assert isinstance(precision, int) and precision >= 0 and precision <= 3, "precision must be an int (range 0-3)" |
| 1868 | unit_labels = cls.METRIC_LABELS if metric else cls.BINARY_LABELS |
| 1869 | last_label = unit_labels[-1] |
| 1870 | unit_step = 1000 if metric else 1024 |
| 1871 | unit_step_thresh = unit_step - cls.PRECISION_OFFSETS[precision] |
| 1872 | |
| 1873 | is_negative = num < 0 |
| 1874 | if is_negative: |
| 1875 | num = abs(num) |
| 1876 | if num < unit_step: # return exact bytes when size is too small |
| 1877 | return cls.PRECISION_FORMATS[0].format('-' if is_negative else '', num, unit_labels[0]) |
| 1878 | for unit in unit_labels: |
| 1879 | if num < unit_step_thresh: |
| 1880 | break |
| 1881 | if unit != last_label: |
| 1882 | num /= unit_step |
| 1883 | return cls.PRECISION_FORMATS[precision].format('-' if is_negative else '', num, unit) |
nothing calls this directly
no outgoing calls
no test coverage detected