rainbowadn/rainbowadn/chain/reduction/reducible.py
2022-07-10 21:14:02 +03:00

59 lines
2.1 KiB
Python

from typing import Generic, Iterable, TypeVar
from rainbowadn.core import *
from .reductionresult import *
__all__ = ('Reducible', 'ReducibleFactory',)
ReductorType = TypeVar('ReductorType')
AccumulatorType = TypeVar('AccumulatorType')
class Reducible(
ReductionResult[ReductorType, AccumulatorType],
RecursiveMentionable,
Generic[ReductorType, AccumulatorType]
):
def __init__(self, reductor: HashPoint[ReductorType], accumulator: HashPoint[AccumulatorType]):
assert isinstance(reductor, HashPoint)
assert isinstance(accumulator, HashPoint)
self.reductor = reductor
self.accumulator = accumulator
def points(self) -> Iterable[HashPoint]:
return [self.reductor, self.accumulator]
def __bytes__(self):
return bytes(self.reductor) + bytes(self.accumulator)
def __factory__(self) -> RainbowFactory['Reducible[ReductorType, AccumulatorType]']:
return ReducibleFactory(self.reductor.factory, self.accumulator.factory)
async def str(self, tab: int) -> str:
assert isinstance(tab, int)
return f'(reduction)' \
f'{tabulate(tab)}{await hash_point_format(self.accumulator, tab)}'
class ReducibleFactory(
RainbowFactory[Reducible[ReductorType, AccumulatorType]],
Generic[ReductorType, AccumulatorType]
):
def __init__(
self,
reductor_factory: RainbowFactory[ReductorType],
accumulator_factory: RainbowFactory[AccumulatorType],
):
assert isinstance(reductor_factory, RainbowFactory)
assert isinstance(accumulator_factory, RainbowFactory)
self.reductor_factory = reductor_factory
self.accumulator_factory = accumulator_factory
def from_bytes(self, source: bytes, resolver: HashResolver) -> Reducible[ReductorType, AccumulatorType]:
assert isinstance(source, bytes)
assert isinstance(resolver, HashResolver)
return Reducible(
ResolverOrigin(self.reductor_factory, source[:HashPoint.HASH_LENGTH], resolver).hash_point(),
ResolverOrigin(self.accumulator_factory, source[HashPoint.HASH_LENGTH:], resolver).hash_point(),
)