|
| 1 | +################################################################################ |
| 2 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 3 | +# or more contributor license agreements. See the NOTICE file |
| 4 | +# distributed with this work for additional information |
| 5 | +# regarding copyright ownership. The ASF licenses this file |
| 6 | +# to you under the Apache License, Version 2.0 (the |
| 7 | +# "License"); you may not use this file except in compliance |
| 8 | +# with the License. You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, software |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +# See the License for the specific language governing permissions and |
| 16 | +# limitations under the License. |
| 17 | +################################################################################ |
| 18 | + |
| 19 | +from typing import Optional |
| 20 | + |
| 21 | + |
| 22 | +class MemorySize: |
| 23 | + """MemorySize is a representation of a number of bytes, viewable in different units.""" |
| 24 | + |
| 25 | + ZERO = None |
| 26 | + MAX_VALUE = None |
| 27 | + |
| 28 | + def __init__(self, bytes: int): |
| 29 | + """Constructs a new MemorySize.""" |
| 30 | + if bytes < 0: |
| 31 | + raise ValueError("bytes must be >= 0") |
| 32 | + self.bytes = bytes |
| 33 | + |
| 34 | + @staticmethod |
| 35 | + def of_mebi_bytes(mebi_bytes: int) -> 'MemorySize': |
| 36 | + return MemorySize(mebi_bytes << 20) |
| 37 | + |
| 38 | + @staticmethod |
| 39 | + def of_kibi_bytes(kibi_bytes: int) -> 'MemorySize': |
| 40 | + return MemorySize(kibi_bytes << 10) |
| 41 | + |
| 42 | + @staticmethod |
| 43 | + def of_bytes(bytes: int) -> 'MemorySize': |
| 44 | + return MemorySize(bytes) |
| 45 | + |
| 46 | + def get_bytes(self) -> int: |
| 47 | + return self.bytes |
| 48 | + |
| 49 | + def get_kibi_bytes(self) -> int: |
| 50 | + return self.bytes >> 10 |
| 51 | + |
| 52 | + def get_mebi_bytes(self) -> int: |
| 53 | + return self.bytes >> 20 |
| 54 | + |
| 55 | + def get_gibi_bytes(self) -> int: |
| 56 | + return self.bytes >> 30 |
| 57 | + |
| 58 | + def get_tebi_bytes(self) -> int: |
| 59 | + return self.bytes >> 40 |
| 60 | + |
| 61 | + def __eq__(self, other) -> bool: |
| 62 | + return isinstance(other, MemorySize) and self.bytes == other.bytes |
| 63 | + |
| 64 | + def __hash__(self) -> int: |
| 65 | + return hash(self.bytes) |
| 66 | + |
| 67 | + def __str__(self) -> str: |
| 68 | + return self.format_to_string() |
| 69 | + |
| 70 | + def format_to_string(self) -> str: |
| 71 | + ORDERED_UNITS = [MemoryUnit.BYTES, MemoryUnit.KILO_BYTES, MemoryUnit.MEGA_BYTES, |
| 72 | + MemoryUnit.GIGA_BYTES, MemoryUnit.TERA_BYTES] |
| 73 | + |
| 74 | + highest_integer_unit = MemoryUnit.BYTES |
| 75 | + for idx, unit in enumerate(ORDERED_UNITS): |
| 76 | + if self.bytes % unit.multiplier != 0: |
| 77 | + if idx == 0: |
| 78 | + highest_integer_unit = ORDERED_UNITS[0] |
| 79 | + else: |
| 80 | + highest_integer_unit = ORDERED_UNITS[idx - 1] |
| 81 | + break |
| 82 | + else: |
| 83 | + highest_integer_unit = MemoryUnit.BYTES |
| 84 | + |
| 85 | + return f"{self.bytes // highest_integer_unit.multiplier} {highest_integer_unit.units[1]}" |
| 86 | + |
| 87 | + def __repr__(self) -> str: |
| 88 | + return f"MemorySize({self.bytes})" |
| 89 | + |
| 90 | + def __lt__(self, other: 'MemorySize') -> bool: |
| 91 | + return self.bytes < other.bytes |
| 92 | + |
| 93 | + def __le__(self, other: 'MemorySize') -> bool: |
| 94 | + return self.bytes <= other.bytes |
| 95 | + |
| 96 | + def __gt__(self, other: 'MemorySize') -> bool: |
| 97 | + return self.bytes > other.bytes |
| 98 | + |
| 99 | + def __ge__(self, other: 'MemorySize') -> bool: |
| 100 | + return self.bytes >= other.bytes |
| 101 | + |
| 102 | + @staticmethod |
| 103 | + def parse(text: str) -> 'MemorySize': |
| 104 | + return MemorySize(MemorySize.parse_bytes(text)) |
| 105 | + |
| 106 | + @staticmethod |
| 107 | + def parse_bytes(text: str) -> int: |
| 108 | + if text is None: |
| 109 | + raise ValueError("text cannot be None") |
| 110 | + |
| 111 | + trimmed = text.strip() |
| 112 | + if not trimmed: |
| 113 | + raise ValueError("argument is an empty- or whitespace-only string") |
| 114 | + |
| 115 | + pos = 0 |
| 116 | + while pos < len(trimmed) and trimmed[pos].isdigit(): |
| 117 | + pos += 1 |
| 118 | + |
| 119 | + number_str = trimmed[:pos] |
| 120 | + unit_str = trimmed[pos:].strip().lower() |
| 121 | + |
| 122 | + if not number_str: |
| 123 | + raise ValueError("text does not start with a number") |
| 124 | + |
| 125 | + try: |
| 126 | + value = int(number_str) |
| 127 | + except ValueError: |
| 128 | + raise ValueError( |
| 129 | + f"The value '{number_str}' cannot be represented as 64bit number (numeric overflow).") |
| 130 | + |
| 131 | + unit = MemorySize._parse_unit(unit_str) |
| 132 | + multiplier = unit.multiplier if unit else 1 |
| 133 | + result = value * multiplier |
| 134 | + |
| 135 | + if result // multiplier != value: |
| 136 | + raise ValueError( |
| 137 | + f"The value '{text}' cannot be represented as 64bit number of bytes (numeric overflow).") |
| 138 | + |
| 139 | + return result |
| 140 | + |
| 141 | + @staticmethod |
| 142 | + def _parse_unit(unit_str: str) -> Optional['MemoryUnit']: |
| 143 | + if not unit_str: |
| 144 | + return None |
| 145 | + |
| 146 | + for unit in [MemoryUnit.BYTES, MemoryUnit.KILO_BYTES, MemoryUnit.MEGA_BYTES, |
| 147 | + MemoryUnit.GIGA_BYTES, MemoryUnit.TERA_BYTES]: |
| 148 | + if unit_str in unit.units: |
| 149 | + return unit |
| 150 | + |
| 151 | + raise ValueError( |
| 152 | + f"Memory size unit '{unit_str}' does not match any of the recognized units: " |
| 153 | + f"{MemoryUnit.get_all_units()}") |
| 154 | + |
| 155 | + |
| 156 | +class MemoryUnit: |
| 157 | + """Enum which defines memory unit, mostly used to parse value from configuration file.""" |
| 158 | + |
| 159 | + def __init__(self, units: list, multiplier: int): |
| 160 | + self.units = units |
| 161 | + self.multiplier = multiplier |
| 162 | + |
| 163 | + BYTES = None |
| 164 | + KILO_BYTES = None |
| 165 | + MEGA_BYTES = None |
| 166 | + GIGA_BYTES = None |
| 167 | + TERA_BYTES = None |
| 168 | + |
| 169 | + @staticmethod |
| 170 | + def get_all_units() -> str: |
| 171 | + all_units = [] |
| 172 | + for unit in [MemoryUnit.BYTES, MemoryUnit.KILO_BYTES, MemoryUnit.MEGA_BYTES, |
| 173 | + MemoryUnit.GIGA_BYTES, MemoryUnit.TERA_BYTES]: |
| 174 | + all_units.append("(" + " | ".join(unit.units) + ")") |
| 175 | + return " / ".join(all_units) |
| 176 | + |
| 177 | + @staticmethod |
| 178 | + def has_unit(text: str) -> bool: |
| 179 | + if text is None: |
| 180 | + raise ValueError("text cannot be None") |
| 181 | + |
| 182 | + trimmed = text.strip() |
| 183 | + if not trimmed: |
| 184 | + raise ValueError("argument is an empty- or whitespace-only string") |
| 185 | + |
| 186 | + pos = 0 |
| 187 | + while pos < len(trimmed) and trimmed[pos].isdigit(): |
| 188 | + pos += 1 |
| 189 | + |
| 190 | + unit = trimmed[pos:].strip().lower() |
| 191 | + return len(unit) > 0 |
| 192 | + |
| 193 | + |
| 194 | +MemoryUnit.BYTES = MemoryUnit(["b", "bytes"], 1) |
| 195 | +MemoryUnit.KILO_BYTES = MemoryUnit(["k", "kb", "kibibytes"], 1024) |
| 196 | +MemoryUnit.MEGA_BYTES = MemoryUnit(["m", "mb", "mebibytes"], 1024 * 1024) |
| 197 | +MemoryUnit.GIGA_BYTES = MemoryUnit(["g", "gb", "gibibytes"], 1024 * 1024 * 1024) |
| 198 | +MemoryUnit.TERA_BYTES = MemoryUnit(["t", "tb", "tebibytes"], 1024 * 1024 * 1024 * 1024) |
| 199 | + |
| 200 | +MemorySize.ZERO = MemorySize(0) |
| 201 | +MemorySize.MAX_VALUE = MemorySize(2**63 - 1) |
0 commit comments