continued reorganisation

This commit is contained in:
Emile Clark-Boman 2025-06-21 21:29:00 +10:00
parent 6f8a7322f2
commit 0a2d9a5694
22 changed files with 190 additions and 61 deletions

17
bcrypter/lib/format.py Normal file
View file

@ -0,0 +1,17 @@
from typing import Any
from bcrypt.lib.math import clamp_min
'''
Apply left padding to str(x) for parameter x: Any
'''
def lpad(x: Any, n: int, pad: chr = ' ') -> str:
x = str(x)
width = clamp_min(n - len(x), 0)
return width * pad + x
'''
Left pad an integer's binary representation with zeros
'''
def lpadbin(x: int, n: int) -> str:
return lpad(bin(x)[2:], n, pad='0')

16
bcrypter/lib/math.py Normal file
View file

@ -0,0 +1,16 @@
'''
Implements numeric range clamping (idk why its not in the stdlib...)
NOTE: the upper and lower bounds for clamping are inclusive
'''
def clamp(x: int, min: int, max: int) -> int:
if x < min:
return min
elif x > max:
return max
return x
def clamp_min(x: int, min: int) -> int:
return x if x > min else min
def clamp_max(x: int, max: int) -> int:
return x if x < max else max

26
bcrypter/lib/result.py Normal file
View file

@ -0,0 +1,26 @@
from dataclass import dataclass
from enum import Enum
class ResultState(Enum):
WARNING,
SUCCESS,
FAILURE,
@dataclass
class Result[T]:
state: ResultState
value: T | None
message: str
@classmethod
def warn(cls: Result, message: str, value: T | None = NOne) -> Result:
cls(ResultState.WARNING, value, message)
@classmethod
def succeed(cls: Result, value: T, message: str = 'Ok') -> Result:
cls(ResultState.SUCCESS, value, message)
@classmethod
def fail(cls: Result, message: str, value: T | None = None) -> Result:
cls(ResultState.WARNING, value, message)
def is_ok(self) -> bool: return not self.is_err()
def is_err(self) -> bool: return self.state == ResultState.FAILURE