-
Notifications
You must be signed in to change notification settings - Fork 2
/
bytes.py
52 lines (38 loc) · 1.05 KB
/
bytes.py
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from __future__ import annotations
from enum import Enum
import math
class UnitSize(Enum):
B = {"name": "byte", "multiplier": 2**0}
KiB = {
"name": "kibibyte",
"multiplier": 2**10,
}
MiB = {
"name": "mebibyte",
"multiplier": 2**20,
}
GiB = {
"name": "gibibyte",
"multiplier": 2**30,
}
TiB = {
"name": "tebibyte",
"multiplier": 2**40,
}
PiB = {
"name": "pebibyte",
"multiplier": 2**50,
}
def to_bytes(self, bytes: int) -> int:
return bytes * self.multiplier()
def from_bytes(self, bytes: int) -> int:
return math.floor(bytes / self.multiplier())
def multiplier(self) -> int:
return self.value["multiplier"] # type: ignore
def traditional_name(self) -> str:
return self.value["name"] # type: ignore
def convert(size: int, from_unit: UnitSize, target_unit: UnitSize):
if size == 0:
return 0
to_bytes = from_unit.to_bytes(size)
return target_unit.from_bytes(to_bytes)