This commit is contained in:
AF 2023-10-02 19:07:57 +00:00
parent 3c13630d8e
commit 8915fc6afa
140 changed files with 1412 additions and 1831 deletions

12
main.py
View File

@ -7,20 +7,20 @@ class Print(Instrumentation):
self.msg = msg
def instrument(self, method, *args, **kwargs):
print(self.msg, end=' ')
print(self.msg, end=" ")
return method(*args, **kwargs)
class C:
@classmethod
def m(cls):
print('m')
print("m")
with Print(Instrumentation, '__exit__', 'exit'):
print1 = Print(C, 'm', '1')
print2 = Print(C, 'm', '2')
print3 = Print(C, 'm', '3')
with Print(Instrumentation, "__exit__", "exit"):
print1 = Print(C, "m", "1")
print2 = Print(C, "m", "2")
print3 = Print(C, "m", "3")
C.m()
print1.__enter__()
C.m()

46
plot.py
View File

@ -5,7 +5,7 @@ from typing import Any
import matplotlib.pyplot as plt
import numpy as np
__all__ = ('plot',)
__all__ = ("plot",)
def plottable(log: list[tuple[float, int]]):
@ -18,7 +18,7 @@ def plottable(log: list[tuple[float, int]]):
def format_params(params) -> str:
match params:
case dict():
return '{' + ' '.join(f'{key}={format_params(value)}' for key, value in params.items()) + '}'
return "{" + " ".join(f"{key}={format_params(value)}" for key, value in params.items()) + "}"
case list():
return f'[{" ".join(format_params(value) for value in params)}]'
case _:
@ -26,42 +26,42 @@ def format_params(params) -> str:
def plot(fn: str):
plt.rcParams['figure.figsize'] = [16, 9]
plt.style.use('dark_background')
plt.rcParams["figure.figsize"] = [16, 9]
plt.style.use("dark_background")
plt.subplots_adjust(left=0.05, right=0.99, top=0.95, bottom=0.05)
plt.xlabel('time (s)')
plt.ylabel('concurrency (1)')
plt.xlabel("time (s)")
plt.ylabel("concurrency (1)")
with open(fn) as file:
jsonified: dict[str, Any] = json.load(file)
title = fn
if (params := jsonified.pop('params', None)) is not None:
title += f' {format_params(params)}'
if (params := jsonified.pop("params", None)) is not None:
title += f" {format_params(params)}"
plt.title(title)
def logplot(plot_function, metric: str, **kwargs):
if (log := jsonified.pop(metric, None)) is not None:
plot_function(*plottable(log), label=f'{metric} ({len(log)})', **kwargs)
plot_function(*plottable(log), label=f"{metric} ({len(log)})", **kwargs)
logplot(plt.plot, 'DelayedResolver:sleep:concurrency')
logplot(plt.plot, 'ActiveBinaryTree:add:concurrency')
logplot(plt.plot, 'ActiveBinaryTree:contains:concurrency')
logplot(plt.plot, 'FlowStandard:verify_subset:concurrency')
logplot(plt.plot, 'Stack:list:concurrency')
logplot(plt.scatter, 'ActiveBinaryTree:add:entry', c='tomato', zorder=100, s=.5)
logplot(plt.scatter, 'ActiveBinaryTree:add:exit', c='gold', zorder=99, s=.5)
logplot(plt.plot, "DelayedResolver:sleep:concurrency")
logplot(plt.plot, "ActiveBinaryTree:add:concurrency")
logplot(plt.plot, "ActiveBinaryTree:contains:concurrency")
logplot(plt.plot, "FlowStandard:verify_subset:concurrency")
logplot(plt.plot, "Stack:list:concurrency")
logplot(plt.scatter, "ActiveBinaryTree:add:entry", c="tomato", zorder=100, s=0.5)
logplot(plt.scatter, "ActiveBinaryTree:add:exit", c="gold", zorder=99, s=0.5)
plt.legend()
plt.savefig(f'{fn}.png')
plt.savefig(f"{fn}.png")
plt.show()
plt.clf()
if __name__ == '__main__':
Path('trace').mkdir(exist_ok=True)
if Path('trace/latest.json').exists():
plot('trace/latest.json')
for fp in list(Path('trace').glob('*.json')):
if fp != Path('trace/latest.json'):
if __name__ == "__main__":
Path("trace").mkdir(exist_ok=True)
if Path("trace/latest.json").exists():
plot("trace/latest.json")
for fp in list(Path("trace").glob("*.json")):
if fp != Path("trace/latest.json"):
plot(str(fp))

View File

@ -1,7 +1,7 @@
__all__ = (
'Atomic',
'Integer',
'Plain',
"Atomic",
"Integer",
"Plain",
)
from .atomic import Atomic

View File

@ -3,14 +3,14 @@ from typing import Type, TypeVar
from rainbowadn.core import *
__all__ = ('Atomic',)
__all__ = ("Atomic",)
AtomicMentioned = TypeVar('AtomicMentioned', bound='Atomic')
AtomicMentioned = TypeVar("AtomicMentioned", bound="Atomic")
class Atomic(StaticMentionable, abc.ABC):
def __topology_hash__(self) -> bytes:
return HashPoint.hash(b'')
return HashPoint.hash(b"")
@classmethod
def from_bytes(cls: Type[AtomicMentioned], source: bytes, resolver: HashResolver) -> AtomicMentioned:

View File

@ -1,6 +1,8 @@
from __future__ import annotations
from .atomic import *
__all__ = ('Integer',)
__all__ = ("Integer",)
class Integer(Atomic):
@ -10,14 +12,14 @@ class Integer(Atomic):
self.integer = integer
@classmethod
def _from_bytes(cls, source: bytes) -> 'Integer':
def _from_bytes(cls, source: bytes) -> Integer:
assert isinstance(source, bytes)
if source:
assert source[-1] > 0
return cls(int.from_bytes(source, 'little'))
return cls(int.from_bytes(source, "little"))
def __bytes__(self):
return self.integer.to_bytes((self.integer.bit_length() + 7) // 8, 'little')
return self.integer.to_bytes((self.integer.bit_length() + 7) // 8, "little")
def __str__(self):
return str(self.integer)

View File

@ -1,6 +1,8 @@
from __future__ import annotations
from .atomic import *
__all__ = ('Plain',)
__all__ = ("Plain",)
class Plain(Atomic):
@ -9,7 +11,7 @@ class Plain(Atomic):
self.source = source
@classmethod
def _from_bytes(cls, source: bytes) -> 'Plain':
def _from_bytes(cls, source: bytes) -> Plain:
assert isinstance(source, bytes)
return cls(source)
@ -17,4 +19,4 @@ class Plain(Atomic):
return self.source
def __str__(self):
return self.source.decode(errors='replace')
return self.source.decode(errors="replace")

View File

@ -3,17 +3,12 @@ from typing import Generic, TypeVar
from rainbowadn.core import *
from rainbowadn.nullability import *
__all__ = ('CollectionInterface',)
__all__ = ("CollectionInterface",)
CollectionType = TypeVar('CollectionType', bound=Mentionable, covariant=True)
CollectionType = TypeVar("CollectionType", bound=Mentionable, covariant=True)
class CollectionInterface(
Generic[CollectionType]
):
def __init__(
self,
reference: NullableReference[CollectionType]
):
class CollectionInterface(Generic[CollectionType]):
def __init__(self, reference: NullableReference[CollectionType]):
assert isinstance(reference, NullableReference)
self.reference = reference

View File

@ -1,13 +1,26 @@
__all__ = (
'Comparison', 'Left', 'Right', 'Equal', 'Replace', 'Fail', 'Duplicate', 'Comparator',
'HashComparator',
'KeyedComparator',
'PlainComparator',
"Comparison",
"Left",
"Right",
"Equal",
"Replace",
"Fail",
"Duplicate",
"Comparator",
"HashComparator",
"KeyedComparator",
"PlainComparator",
)
from .comparator import (
Comparator, Comparison, Duplicate, Equal, Fail, Left,
Replace, Right
Comparator,
Comparison,
Duplicate,
Equal,
Fail,
Left,
Replace,
Right,
)
from .hashcomparator import HashComparator
from .keyedcomparator import KeyedComparator

View File

@ -4,7 +4,14 @@ from typing import Generic, TypeVar
from rainbowadn.core import *
__all__ = (
'Comparison', 'Left', 'Right', 'Equal', 'Replace', 'Fail', 'Duplicate', 'Comparator',
"Comparison",
"Left",
"Right",
"Equal",
"Replace",
"Fail",
"Duplicate",
"Comparator",
)
@ -36,7 +43,7 @@ class Duplicate(Equal):
pass
KeyType = TypeVar('KeyType', bound=Mentionable, contravariant=True)
KeyType = TypeVar("KeyType", bound=Mentionable, contravariant=True)
class Comparator(Generic[KeyType]):

View File

@ -5,9 +5,9 @@ from rainbowadn.core import *
from .comparator import *
from .protocolcomparator import *
__all__ = ('HashComparator',)
__all__ = ("HashComparator",)
KeyType = TypeVar('KeyType', bound=Mentionable, contravariant=True)
KeyType = TypeVar("KeyType", bound=Mentionable, contravariant=True)
class HashComparator(ProtocolComparator[KeyType], Generic[KeyType]):

View File

@ -5,23 +5,19 @@ from rainbowadn.core import *
from .comparator import *
__all__ = ('KeyedComparator',)
__all__ = ("KeyedComparator",)
ComparatorKeyType = TypeVar('ComparatorKeyType', bound=Mentionable, contravariant=True)
ComparatorKeyType = TypeVar("ComparatorKeyType", bound=Mentionable, contravariant=True)
class KeyedComparator(
Comparator[Keyed[ComparatorKeyType]], Generic[ComparatorKeyType]
):
class KeyedComparator(Comparator[Keyed[ComparatorKeyType]], Generic[ComparatorKeyType]):
def __init__(self, comparator: Comparator[ComparatorKeyType]):
assert isinstance(comparator, Comparator)
self.comparator = comparator
super().__init__()
async def compare(
self,
original: HashPoint[Keyed[ComparatorKeyType]],
key: HashPoint[Keyed[ComparatorKeyType]]
self, original: HashPoint[Keyed[ComparatorKeyType]], key: HashPoint[Keyed[ComparatorKeyType]]
) -> Comparison:
assert isinstance(original, HashPoint)
assert isinstance(key, HashPoint)

View File

@ -4,7 +4,7 @@ from rainbowadn.core import *
from .comparator import *
from .protocolcomparator import *
__all__ = ('PlainComparator',)
__all__ = ("PlainComparator",)
class PlainComparator(ProtocolComparator[Plain]):

View File

@ -5,9 +5,9 @@ from rainbowadn.core import *
from .comparator import *
__all__ = ('ProtocolComparator',)
__all__ = ("ProtocolComparator",)
KeyType = TypeVar('KeyType', bound=Mentionable, contravariant=True)
KeyType = TypeVar("KeyType", bound=Mentionable, contravariant=True)
class ProtocolComparator(Comparator[KeyType], abc.ABC, Generic[KeyType]):

View File

@ -3,9 +3,9 @@ from typing import Generic, TypeVar
from rainbowadn.core import *
__all__ = ('Keyed',)
__all__ = ("Keyed",)
KKeyType = TypeVar('KKeyType', bound=Mentionable, covariant=True)
KKeyType = TypeVar("KKeyType", bound=Mentionable, covariant=True)
class Keyed(RecursiveMentionable, Generic[KKeyType], abc.ABC):

View File

@ -1,13 +1,18 @@
from __future__ import annotations
from typing import Generic, Iterable, TypeVar
from rainbowadn.core import *
from .keyed import *
__all__ = ('KeyMetadata', 'KeyMetadataFactory',)
__all__ = (
"KeyMetadata",
"KeyMetadataFactory",
)
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable, covariant=True)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable, covariant=True)
ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable, covariant=True)
MetaDataType = TypeVar("MetaDataType", bound=Mentionable, covariant=True)
class KeyMetadata(Keyed[ActiveKeyType], Generic[ActiveKeyType, MetaDataType]):
@ -23,24 +28,19 @@ class KeyMetadata(Keyed[ActiveKeyType], Generic[ActiveKeyType, MetaDataType]):
def __bytes__(self):
return bytes(self.key) + bytes(self.metadata)
def __factory__(self) -> RainbowFactory['KeyMetadata[ActiveKeyType, MetaDataType]']:
def __factory__(self) -> RainbowFactory[KeyMetadata[ActiveKeyType, MetaDataType]]:
return KeyMetadataFactory(self.key.factory, self.metadata.factory)
async def str(self, tab: int) -> str:
assert isinstance(tab, int)
key_str, metadata_str = await gather(
hash_point_format(self.key, tab),
hash_point_format(self.metadata, tab)
)
key_str, metadata_str = await gather(hash_point_format(self.key, tab), hash_point_format(self.metadata, tab))
assert isinstance(key_str, str)
assert isinstance(metadata_str, str)
return f'{key_str}' \
f'{tabulate(tab)}{metadata_str}'
return f"{key_str}" f"{tabulate(tab)}{metadata_str}"
class KeyMetadataFactory(
RainbowFactory[KeyMetadata[ActiveKeyType, MetaDataType]],
Generic[ActiveKeyType, MetaDataType]
RainbowFactory[KeyMetadata[ActiveKeyType, MetaDataType]], Generic[ActiveKeyType, MetaDataType]
):
def __init__(self, key_factory: RainbowFactory[ActiveKeyType], metadata_factory: RainbowFactory[MetaDataType]):
assert isinstance(key_factory, RainbowFactory)
@ -52,8 +52,8 @@ class KeyMetadataFactory(
assert isinstance(source, bytes)
assert isinstance(resolver, HashResolver)
return KeyMetadata(
ResolverOrigin(self.key_factory, source[:HashPoint.HASH_LENGTH], resolver).hash_point(),
ResolverOrigin(self.metadata_factory, source[HashPoint.HASH_LENGTH:], resolver).hash_point(),
ResolverOrigin(self.key_factory, source[: HashPoint.HASH_LENGTH], resolver).hash_point(),
ResolverOrigin(self.metadata_factory, source[HashPoint.HASH_LENGTH :], resolver).hash_point(),
)
def loose(self) -> RainbowFactory[KeyMetadata[ActiveKeyType, MetaDataType]]:

View File

@ -1,3 +1,5 @@
from __future__ import annotations
from typing import Generic, TypeVar
from rainbowadn.core import *
@ -5,10 +7,10 @@ from rainbowadn.inlining import *
from .keyed import *
__all__ = ('KeyValue',)
__all__ = ("KeyValue",)
KVKeyType = TypeVar('KVKeyType', bound=Mentionable)
KVValueType = TypeVar('KVValueType', bound=Mentionable)
KVKeyType = TypeVar("KVKeyType", bound=Mentionable)
KVValueType = TypeVar("KVValueType", bound=Mentionable)
class KeyValue(Keyed[KVKeyType], IAuto, Generic[KVKeyType, KVValueType]):
@ -20,23 +22,21 @@ class KeyValue(Keyed[KVKeyType], IAuto, Generic[KVKeyType, KVValueType]):
Keyed.__init__(self, key)
@classmethod
async def off(
cls, key: HashPoint[KVKeyType], value: HashPoint[KVValueType]
) -> 'KeyValue[KVKeyType, KVValueType]':
async def off(cls, key: HashPoint[KVKeyType], value: HashPoint[KVValueType]) -> KeyValue[KVKeyType, KVValueType]:
assert isinstance(key, HashPoint)
assert isinstance(value, HashPoint)
return await cls.auto_off(key, value)
@classmethod
def of(cls, vk: KVKeyType, vv: KVValueType) -> 'KeyValue[KVKeyType, KVValueType]':
def of(cls, vk: KVKeyType, vv: KVValueType) -> KeyValue[KVKeyType, KVValueType]:
assert isinstance(vk, Mentionable)
assert isinstance(vv, Mentionable)
return cls.auto_of(vk, vv)
@classmethod
def f(
cls, f0: RainbowFactory[KVKeyType], f1: RainbowFactory[KVValueType]
) -> RainbowFactory['KeyValue[KVKeyType, KVValueType]']:
cls, f0: RainbowFactory[KVKeyType], f1: RainbowFactory[KVValueType]
) -> RainbowFactory[KeyValue[KVKeyType, KVValueType]]:
assert issubclass(cls, KeyValue)
assert isinstance(f0, RainbowFactory)
assert isinstance(f1, RainbowFactory)

View File

@ -1,6 +1,9 @@
__all__ = (
'Array', 'ArrayFactory',
'TLRoot', 'TLRootFactory', 'TLRParametres',
"Array",
"ArrayFactory",
"TLRoot",
"TLRootFactory",
"TLRParametres",
)
from ._array import Array, ArrayFactory

View File

@ -2,17 +2,16 @@ from typing import Generic, Iterable, TypeVar
from rainbowadn.core import *
__all__ = ('Array', 'ArrayFactory',)
__all__ = (
"Array",
"ArrayFactory",
)
ElementType = TypeVar('ElementType', bound=Mentionable, covariant=True)
ElementType = TypeVar("ElementType", bound=Mentionable, covariant=True)
class Array(RecursiveMentionable, Generic[ElementType]):
def __init__(
self,
factory: RainbowFactory[ElementType],
array: tuple[HashPoint[ElementType], ...]
):
def __init__(self, factory: RainbowFactory[ElementType], array: tuple[HashPoint[ElementType], ...]):
assert isinstance(factory, RainbowFactory)
assert isinstance(array, tuple)
self.factory = factory
@ -22,31 +21,23 @@ class Array(RecursiveMentionable, Generic[ElementType]):
return self.array
def __bytes__(self):
return b''.join(map(HashPoint.__bytes__, self.array))
return b"".join(map(HashPoint.__bytes__, self.array))
def __factory__(self) -> RainbowFactory['Array']:
def __factory__(self) -> RainbowFactory["Array"]:
return ArrayFactory(self.factory)
async def str(self, tab: int) -> str:
assert isinstance(tab, int)
formatted = f'('
formatted += ''.join(
f'{tabulate(tab + 1)}{hash_point_str}'
for hash_point_str in await gather(
*(
hash_point_format(hash_point, tab + 1) for hash_point in self.array
)
)
formatted = f"("
formatted += "".join(
f"{tabulate(tab + 1)}{hash_point_str}"
for hash_point_str in await gather(*(hash_point_format(hash_point, tab + 1) for hash_point in self.array))
)
return f'{formatted}' \
f'{tabulate(tab)})'
return f"{formatted}" f"{tabulate(tab)})"
class ArrayFactory(RainbowFactory[Array], Generic[ElementType]):
def __init__(
self,
factory: RainbowFactory[ElementType]
):
def __init__(self, factory: RainbowFactory[ElementType]):
assert isinstance(factory, RainbowFactory)
self.factory = factory
@ -56,10 +47,7 @@ class ArrayFactory(RainbowFactory[Array], Generic[ElementType]):
return Array(
self.factory,
tuple(
ResolverOrigin(self.factory, source[i:i + HashPoint.HASH_LENGTH], resolver).hash_point()
for
i
in
range(0, len(source), HashPoint.HASH_LENGTH)
)
ResolverOrigin(self.factory, source[i : i + HashPoint.HASH_LENGTH], resolver).hash_point()
for i in range(0, len(source), HashPoint.HASH_LENGTH)
),
)

View File

@ -1,6 +1,7 @@
__all__ = (
'TLRoot', 'TLRootFactory',
'TLRParametres',
"TLRoot",
"TLRootFactory",
"TLRParametres",
)
from .tlroot import TLRoot, TLRootFactory

View File

@ -1,21 +1,26 @@
from __future__ import annotations
from typing import Generic, Iterable, TypeVar
from rainbowadn.core import *
from .tlparametres import *
__all__ = ('TLNode', 'TLNodeFactory',)
__all__ = (
"TLNode",
"TLNodeFactory",
)
ElementType = TypeVar('ElementType', bound=Mentionable)
ElementType = TypeVar("ElementType", bound=Mentionable)
class TLNode(RecursiveMentionable, Generic[ElementType]):
def __init__(
self,
source: bytes,
parametres: TLParametres[ElementType],
node_cache: tuple[MetaOrigin['TLNode[ElementType]'], ...],
element_cache: tuple[MetaOrigin[ElementType], ...],
self,
source: bytes,
parametres: TLParametres[ElementType],
node_cache: tuple[MetaOrigin[TLNode[ElementType]], ...],
element_cache: tuple[MetaOrigin[ElementType], ...],
):
assert isinstance(source, bytes)
assert isinstance(parametres, TLParametres)
@ -37,7 +42,7 @@ class TLNode(RecursiveMentionable, Generic[ElementType]):
def bytes_no(self, index: int) -> bytes:
assert isinstance(index, int)
assert index < self.parametres.branching
return self.source[HashPoint.HASH_LENGTH * index:HashPoint.HASH_LENGTH * (index + 1)]
return self.source[HashPoint.HASH_LENGTH * index : HashPoint.HASH_LENGTH * (index + 1)]
def element_no(self, index: int) -> HashPoint[ElementType]:
assert isinstance(index, int)
@ -45,18 +50,13 @@ class TLNode(RecursiveMentionable, Generic[ElementType]):
meta_origin: MetaOrigin[ElementType] = self.element_cache[index]
return meta_origin.hash_point(self.parametres.tlr.factory, self.bytes_no(index))
def node_no(self, index: int) -> HashPoint['TLNode[ElementType]']:
def node_no(self, index: int) -> HashPoint[TLNode[ElementType]]:
assert isinstance(index, int)
assert index < self.nodes
meta_origin: MetaOrigin[TLNode[ElementType]] = self.node_cache[index]
return meta_origin.hash_point(
TLNodeFactory(
self.parametres.params_no(index)
),
self.bytes_no(index)
)
return meta_origin.hash_point(TLNodeFactory(self.parametres.params_no(index)), self.bytes_no(index))
async def node_no_resolved(self, index: int) -> 'TLNode[ElementType]':
async def node_no_resolved(self, index: int) -> TLNode[ElementType]:
assert isinstance(index, int)
assert index < self.nodes
return await self.node_no(index).resolve()
@ -73,19 +73,17 @@ class TLNode(RecursiveMentionable, Generic[ElementType]):
def __bytes__(self):
return self.source
def __factory__(self) -> RainbowFactory['TLNode[ElementType]']:
return TLNodeFactory(
self.parametres
)
def __factory__(self) -> RainbowFactory[TLNode[ElementType]]:
return TLNodeFactory(self.parametres)
async def str(self, tab: int) -> str:
assert isinstance(tab, int)
if self.parametres.size == 0:
return f'-'
return f"-"
else:
return f'{tabulate(tab)}'.join(await gather(*(hash_point_format(point, tab) for point in self.points())))
return f"{tabulate(tab)}".join(await gather(*(hash_point_format(point, tab) for point in self.points())))
def unit(self, element: HashPoint[ElementType]) -> 'TLNode[ElementType]':
def unit(self, element: HashPoint[ElementType]) -> TLNode[ElementType]:
assert isinstance(element, HashPoint)
return TLNode(
bytes(element),
@ -95,13 +93,13 @@ class TLNode(RecursiveMentionable, Generic[ElementType]):
)
def source_without_last(self) -> bytes:
return self.source[:-HashPoint.HASH_LENGTH]
return self.source[: -HashPoint.HASH_LENGTH]
async def last(self) -> 'TLNode[ElementType]':
async def last(self) -> TLNode[ElementType]:
assert not self.parametres.leaf
return await self.node_no_resolved(self.nodes - 1)
async def add(self, element: HashPoint[ElementType]) -> 'TLNode[ElementType]':
async def add(self, element: HashPoint[ElementType]) -> TLNode[ElementType]:
assert isinstance(self, TLNode)
assert isinstance(element, HashPoint)
if self.parametres.full:
@ -114,7 +112,10 @@ class TLNode(RecursiveMentionable, Generic[ElementType]):
return TLNode(
bytes(self_hp) + bytes(unit_hp),
self.parametres.superparams(),
(LocalMetaOrigin(self_hp.origin), LocalMetaOrigin(unit_hp.origin),),
(
LocalMetaOrigin(self_hp.origin),
LocalMetaOrigin(unit_hp.origin),
),
(),
)
elif self.parametres.leaf:
@ -150,8 +151,8 @@ class TLNode(RecursiveMentionable, Generic[ElementType]):
class TLNodeFactory(RainbowFactory[TLNode[ElementType]], Generic[ElementType]):
def __init__(
self,
parametres: TLParametres[ElementType],
self,
parametres: TLParametres[ElementType],
):
assert isinstance(parametres, TLParametres)
self.parametres = parametres

View File

@ -1,21 +1,21 @@
from __future__ import annotations
from typing import Generic, TypeVar
from rainbowadn.core import *
from .tlrparametres import *
__all__ = ('TLParametres',)
__all__ = ("TLParametres",)
ElementType = TypeVar('ElementType', bound=Mentionable)
ElementType = TypeVar("ElementType", bound=Mentionable)
class TLParametres(
Generic[ElementType]
):
class TLParametres(Generic[ElementType]):
def __init__(
self,
tlr: TLRParametres[ElementType],
size: int,
self,
tlr: TLRParametres[ElementType],
size: int,
):
assert isinstance(tlr, TLRParametres)
assert isinstance(size, int)
@ -49,12 +49,12 @@ class TLParametres(
return self.order ** (self.height + 1)
def _subsize(self) -> int:
return self.order ** self.height
return self.order**self.height
def superparams(self) -> 'TLParametres[ElementType]':
def superparams(self) -> TLParametres[ElementType]:
return TLParametres(self.tlr, self.size + 1)
def unit(self) -> 'TLParametres[ElementType]':
def unit(self) -> TLParametres[ElementType]:
return TLParametres(self.tlr, 1)
def _subsize_no(self, index: int) -> int:
@ -65,7 +65,7 @@ class TLParametres(
else:
return self.subsize
def params_no(self, index: int) -> 'TLParametres[ElementType]':
def params_no(self, index: int) -> TLParametres[ElementType]:
assert isinstance(index, int)
assert not self.leaf
assert index < self.branching

View File

@ -1,3 +1,5 @@
from __future__ import annotations
from typing import Generic, Iterable, TypeVar
from rainbowadn.atomic import *
@ -7,17 +9,16 @@ from .tlnode import *
from .tlparametres import *
from .tlrparametres import *
__all__ = ('TLRoot', 'TLRootFactory',)
__all__ = (
"TLRoot",
"TLRootFactory",
)
ElementType = TypeVar('ElementType', bound=Mentionable)
ElementType = TypeVar("ElementType", bound=Mentionable)
class TLRoot(RecursiveMentionable, Generic[ElementType]):
def __init__(
self,
node: HashPoint[TLNode[ElementType]],
parametres: TLParametres
):
def __init__(self, node: HashPoint[TLNode[ElementType]], parametres: TLParametres):
assert isinstance(node, HashPoint)
assert isinstance(parametres, TLParametres)
self.node = node
@ -29,19 +30,16 @@ class TLRoot(RecursiveMentionable, Generic[ElementType]):
def __bytes__(self):
return bytes(self.node) + bytes(Integer(self.parametres.size))
def __factory__(self) -> RainbowFactory['TLRoot[ElementType]']:
def __factory__(self) -> RainbowFactory[TLRoot[ElementType]]:
return TLRootFactory(self.parametres.tlr)
async def node_resolved(self) -> TLNode[ElementType]:
return await self.node.resolve()
async def add(self, element: HashPoint[ElementType]) -> 'TLRoot[ElementType]':
async def add(self, element: HashPoint[ElementType]) -> TLRoot[ElementType]:
assert isinstance(element, HashPoint)
node = await (await self.node_resolved()).add(element)
return TLRoot(
HashPoint.of(node),
node.parametres
)
return TLRoot(HashPoint.of(node), node.parametres)
async def str(self, tab: int) -> str:
assert isinstance(tab, int)
@ -50,8 +48,8 @@ class TLRoot(RecursiveMentionable, Generic[ElementType]):
class TLRootFactory(RainbowFactory[TLRoot[ElementType]]):
def __init__(
self,
tlr: TLRParametres,
self,
tlr: TLRParametres,
):
assert isinstance(tlr, TLRParametres)
self.tlr = tlr
@ -59,19 +57,14 @@ class TLRootFactory(RainbowFactory[TLRoot[ElementType]]):
def from_bytes(self, source: bytes, resolver: HashResolver) -> TLRoot[ElementType]:
assert isinstance(source, bytes)
assert isinstance(resolver, HashResolver)
size: int = Integer.from_bytes(source[HashPoint.HASH_LENGTH:], resolver).integer
size: int = Integer.from_bytes(source[HashPoint.HASH_LENGTH :], resolver).integer
assert isinstance(size, int)
parametres = TLParametres(self.tlr, size)
return TLRoot(
ResolverOrigin(
TLNodeFactory(parametres), source[:HashPoint.HASH_LENGTH], resolver
).hash_point(),
parametres
ResolverOrigin(TLNodeFactory(parametres), source[: HashPoint.HASH_LENGTH], resolver).hash_point(),
parametres,
)
def empty(self) -> TLRoot[ElementType]:
parametres = TLParametres(self.tlr, 0)
return TLRoot(
HashPoint.of(TLNode(b'', parametres, (), ())),
parametres
)
return TLRoot(HashPoint.of(TLNode(b"", parametres, (), ())), parametres)

View File

@ -2,18 +2,16 @@ from typing import Generic, TypeVar
from rainbowadn.core import *
__all__ = ('TLRParametres',)
__all__ = ("TLRParametres",)
ElementType = TypeVar('ElementType', bound=Mentionable)
ElementType = TypeVar("ElementType", bound=Mentionable)
class TLRParametres(
Generic[ElementType]
):
class TLRParametres(Generic[ElementType]):
def __init__(
self,
order: int,
factory: RainbowFactory[ElementType],
self,
order: int,
factory: RainbowFactory[ElementType],
):
assert isinstance(order, int)
assert isinstance(factory, RainbowFactory)

View File

@ -1,7 +1,8 @@
__all__ = (
'ActiveBinaryTree',
'AVL',
'BinaryTree', 'BinaryTreeFactory',
"ActiveBinaryTree",
"AVL",
"BinaryTree",
"BinaryTreeFactory",
)
from .activebinarytree import ActiveBinaryTree

View File

@ -1,14 +1,18 @@
__all__ = (
'BinaryAction',
'CompareAction',
'AddAction', 'RemoveAction', 'ContainsAction', 'SplitAction', 'UnionAction', 'MergeAction',
'Symmetric', 'InnerOuter', 'OuterInner',
"BinaryAction",
"CompareAction",
"AddAction",
"RemoveAction",
"ContainsAction",
"SplitAction",
"UnionAction",
"MergeAction",
"Symmetric",
"InnerOuter",
"OuterInner",
)
from .binaryaction import BinaryAction
from .compareaction import CompareAction
from .stdactions import (
AddAction, ContainsAction, MergeAction, RemoveAction,
SplitAction, UnionAction
)
from .stdactions import AddAction, ContainsAction, MergeAction, RemoveAction, SplitAction, UnionAction
from .symmetric import InnerOuter, OuterInner, Symmetric

View File

@ -3,18 +3,18 @@ from typing import Generic, TypeVar
from rainbowadn.collection.trees.binary.core import *
from rainbowadn.core import *
__all__ = ('BinaryAction',)
__all__ = ("BinaryAction",)
TreeType = TypeVar('TreeType')
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable)
ActionType = TypeVar('ActionType')
TreeType = TypeVar("TreeType")
ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
MetaDataType = TypeVar("MetaDataType", bound=Mentionable)
ActionType = TypeVar("ActionType")
class BinaryAction(Generic[ActiveKeyType, MetaDataType, TreeType, ActionType]):
async def on(
self,
protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType],
self,
protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType],
) -> ActionType:
assert isinstance(protocolized, BinaryProtocolized)
if (split := await ProtocolizedBinarySplit.split_of(protocolized)) is None:
@ -24,13 +24,10 @@ class BinaryAction(Generic[ActiveKeyType, MetaDataType, TreeType, ActionType]):
return await self.on_split(split)
async def on_null(
self,
protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType],
self,
protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType],
) -> ActionType:
raise NotImplementedError
async def on_split(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> ActionType:
async def on_split(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> ActionType:
raise NotImplementedError

View File

@ -7,27 +7,24 @@ from rainbowadn.core import *
from .binaryaction import *
__all__ = ('CompareAction',)
__all__ = ("CompareAction",)
TreeType = TypeVar('TreeType')
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable)
ActionType = TypeVar('ActionType')
TreeType = TypeVar("TreeType")
ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
MetaDataType = TypeVar("MetaDataType", bound=Mentionable)
ActionType = TypeVar("ActionType")
class CompareAction(
BinaryAction[ActiveKeyType, MetaDataType, TreeType, ActionType],
Generic[ActiveKeyType, MetaDataType, TreeType, ActionType],
abc.ABC
abc.ABC,
):
def __init__(self, key: HashPoint[ActiveKeyType]):
assert isinstance(key, HashPoint)
self.key = key
async def on_split(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> ActionType:
async def on_split(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> ActionType:
assert isinstance(case, ProtocolizedBinarySplit)
comparison: Comparison = await case.protocol.comparator.compare(case.split.key, self.key)
assert isinstance(comparison, Comparison)
@ -41,20 +38,12 @@ class CompareAction(
raise TypeError
async def on_equal(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType],
equal: Equal
self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], equal: Equal
) -> ActionType:
raise NotImplementedError
async def on_left(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> ActionType:
async def on_left(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> ActionType:
raise NotImplementedError
async def on_right(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> ActionType:
async def on_right(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> ActionType:
raise NotImplementedError

View File

@ -7,26 +7,25 @@ from rainbowadn.core import *
from .binaryaction import *
from .compareaction import *
__all__ = ('AddAction', 'RemoveAction', 'ContainsAction', 'SplitAction', 'UnionAction', 'MergeAction',)
__all__ = (
"AddAction",
"RemoveAction",
"ContainsAction",
"SplitAction",
"UnionAction",
"MergeAction",
)
TreeType = TypeVar('TreeType')
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable)
TreeType = TypeVar("TreeType")
ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
MetaDataType = TypeVar("MetaDataType", bound=Mentionable)
class AddAction(
CompareAction[
ActiveKeyType,
MetaDataType,
TreeType,
TreeType
],
Generic[ActiveKeyType, MetaDataType, TreeType]
CompareAction[ActiveKeyType, MetaDataType, TreeType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType]
):
async def on_equal(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType],
equal: Equal
self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], equal: Equal
) -> TreeType:
assert isinstance(case, ProtocolizedBinarySplit)
assert isinstance(equal, Equal)
@ -35,123 +34,70 @@ class AddAction(
else:
raise TypeError
async def on_left(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
async def on_left(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
assert isinstance(case, ProtocolizedBinarySplit)
return await case.protocol.tree(
await self.on(case.protocolizedl()),
case.split.treer,
case.split.key
)
return await case.protocol.tree(await self.on(case.protocolizedl()), case.split.treer, case.split.key)
async def on_right(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
async def on_right(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
assert isinstance(case, ProtocolizedBinarySplit)
return await case.protocol.tree(
case.split.treel,
await self.on(case.protocolizedr()),
case.split.key
)
return await case.protocol.tree(case.split.treel, await self.on(case.protocolizedr()), case.split.key)
async def on_null(
self,
protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType],
self,
protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType],
) -> TreeType:
assert isinstance(protocolized, BinaryProtocolized)
return await protocolized.creation.tree(protocolized.tree, protocolized.tree, self.key)
class MergeAction(
BinaryAction[
ActiveKeyType,
MetaDataType,
TreeType,
TreeType
],
Generic[ActiveKeyType, MetaDataType, TreeType]
BinaryAction[ActiveKeyType, MetaDataType, TreeType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType]
):
def __init__(self, treer: TreeType):
self.treer = treer
async def on_null(
self,
protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType],
self,
protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType],
) -> TreeType:
assert isinstance(protocolized, BinaryProtocolized)
return self.treer
async def on_split(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
async def on_split(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
assert isinstance(case, ProtocolizedBinarySplit)
return await case.protocol.tree(
case.split.treel,
await MergeAction(self.treer).on(case.protocolizedr()),
case.split.key
case.split.treel, await MergeAction(self.treer).on(case.protocolizedr()), case.split.key
)
class RemoveAction(
CompareAction[
ActiveKeyType,
MetaDataType,
TreeType,
TreeType
],
Generic[ActiveKeyType, MetaDataType, TreeType]
CompareAction[ActiveKeyType, MetaDataType, TreeType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType]
):
async def on_equal(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType],
equal: Equal
self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], equal: Equal
) -> TreeType:
assert isinstance(case, ProtocolizedBinarySplit)
assert isinstance(equal, Equal)
return await MergeAction(case.split.treer).on(case.protocolizedl())
async def on_left(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
async def on_left(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
assert isinstance(case, ProtocolizedBinarySplit)
return await case.protocol.tree(
await self.on(case.protocolizedl()),
case.split.treer,
case.split.key
)
return await case.protocol.tree(await self.on(case.protocolizedl()), case.split.treer, case.split.key)
async def on_right(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
async def on_right(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
assert isinstance(case, ProtocolizedBinarySplit)
return await case.protocol.tree(
case.split.treel,
await self.on(case.protocolizedr()),
case.split.key
)
return await case.protocol.tree(case.split.treel, await self.on(case.protocolizedr()), case.split.key)
async def on_null(
self,
protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType],
self,
protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType],
) -> TreeType:
assert isinstance(protocolized, BinaryProtocolized)
return protocolized.tree
class ContainsAction(
CompareAction[
ActiveKeyType,
MetaDataType,
TreeType,
bool
],
Generic[ActiveKeyType, MetaDataType, TreeType]
CompareAction[ActiveKeyType, MetaDataType, TreeType, bool], Generic[ActiveKeyType, MetaDataType, TreeType]
):
def __init__(self, key: HashPoint[ActiveKeyType], *, exact: bool):
assert isinstance(exact, bool)
@ -159,9 +105,7 @@ class ContainsAction(
super().__init__(key)
async def on_equal(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType],
equal: Equal
self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], equal: Equal
) -> bool:
assert isinstance(case, ProtocolizedBinarySplit)
assert isinstance(equal, Equal)
@ -170,39 +114,28 @@ class ContainsAction(
else:
return True
async def on_left(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> bool:
async def on_left(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> bool:
assert isinstance(case, ProtocolizedBinarySplit)
return await self.on(case.protocolizedl())
async def on_right(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> bool:
async def on_right(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> bool:
assert isinstance(case, ProtocolizedBinarySplit)
return await self.on(case.protocolizedr())
async def on_null(
self,
protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType],
self,
protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType],
) -> bool:
assert isinstance(protocolized, BinaryProtocolized)
return False
class SplitAction(
CompareAction[
ActiveKeyType,
MetaDataType,
TreeType,
tuple[TreeType, TreeType]
],
Generic[ActiveKeyType, MetaDataType, TreeType]
CompareAction[ActiveKeyType, MetaDataType, TreeType, tuple[TreeType, TreeType]],
Generic[ActiveKeyType, MetaDataType, TreeType],
):
async def on_equal(
self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], equal: Equal
self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], equal: Equal
) -> tuple[TreeType, TreeType]:
if isinstance(equal, Replace):
return case.split.treel, case.split.treer
@ -210,31 +143,25 @@ class SplitAction(
raise TypeError
async def on_left(
self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> tuple[TreeType, TreeType]:
ll, lr = await self.on(case.protocolizedl())
return ll, await case.protocol.tree(lr, case.split.treer, case.split.key)
async def on_right(
self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> tuple[TreeType, TreeType]:
rl, rr = await self.on(case.protocolizedr())
return await case.protocol.tree(case.split.treel, rl, case.split.key), rr
async def on_null(
self, protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType]
self, protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType]
) -> tuple[TreeType, TreeType]:
return protocolized.tree, protocolized.tree
class UnionAction(
BinaryAction[
ActiveKeyType,
MetaDataType,
TreeType,
TreeType
],
Generic[ActiveKeyType, MetaDataType, TreeType]
BinaryAction[ActiveKeyType, MetaDataType, TreeType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType]
):
def __init__(self, protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType]):
assert isinstance(protocolized, BinaryProtocolized)

View File

@ -3,109 +3,70 @@ from typing import Generic, TypeVar
from rainbowadn.collection.trees.binary.core import *
from rainbowadn.core import *
__all__ = ('Symmetric', 'InnerOuter', 'OuterInner',)
__all__ = (
"Symmetric",
"InnerOuter",
"OuterInner",
)
TreeType = TypeVar('TreeType')
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable)
TreeType = TypeVar("TreeType")
ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
MetaDataType = TypeVar("MetaDataType", bound=Mentionable)
class Symmetric(
Generic[ActiveKeyType, MetaDataType, TreeType]
):
class Symmetric(Generic[ActiveKeyType, MetaDataType, TreeType]):
def __init__(
self,
protocol: BinaryCreation[ActiveKeyType, MetaDataType, TreeType],
self,
protocol: BinaryCreation[ActiveKeyType, MetaDataType, TreeType],
):
assert isinstance(protocol, BinaryCreation)
self.protocol = protocol
def inner(
self,
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
def inner(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
raise NotImplementedError
def outer(
self,
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
def outer(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
raise NotImplementedError
async def tree(
self,
inner: TreeType,
outer: TreeType,
key: HashPoint[ActiveKeyType]
) -> TreeType:
async def tree(self, inner: TreeType, outer: TreeType, key: HashPoint[ActiveKeyType]) -> TreeType:
raise NotImplementedError
def protocolizedi(
self,
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType]:
assert isinstance(split, BinarySplit)
return BinaryProtocolized(self.protocol, self.inner(split))
def protocolizedo(
self,
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType]:
assert isinstance(split, BinarySplit)
return BinaryProtocolized(self.protocol, self.outer(split))
class InnerOuter(
Symmetric[ActiveKeyType, MetaDataType, TreeType],
Generic[ActiveKeyType, MetaDataType, TreeType]
):
def inner(
self,
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
class InnerOuter(Symmetric[ActiveKeyType, MetaDataType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType]):
def inner(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
assert isinstance(split, BinarySplit)
return split.treel
def outer(
self,
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
def outer(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
assert isinstance(split, BinarySplit)
return split.treer
async def tree(
self,
inner: TreeType,
outer: TreeType,
key: HashPoint[ActiveKeyType]
) -> TreeType:
async def tree(self, inner: TreeType, outer: TreeType, key: HashPoint[ActiveKeyType]) -> TreeType:
assert isinstance(key, HashPoint)
return await self.protocol.tree(inner, outer, key)
class OuterInner(
Symmetric[ActiveKeyType, MetaDataType, TreeType],
Generic[ActiveKeyType, MetaDataType, TreeType]
):
def inner(
self,
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
class OuterInner(Symmetric[ActiveKeyType, MetaDataType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType]):
def inner(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
assert isinstance(split, BinarySplit)
return split.treer
def outer(
self,
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
def outer(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
assert isinstance(split, BinarySplit)
return split.treel
async def tree(
self,
inner: TreeType,
outer: TreeType,
key: HashPoint[ActiveKeyType]
) -> TreeType:
async def tree(self, inner: TreeType, outer: TreeType, key: HashPoint[ActiveKeyType]) -> TreeType:
assert isinstance(key, HashPoint)
return await self.protocol.tree(outer, inner, key)

View File

@ -1,3 +1,5 @@
from __future__ import annotations
from typing import Generic, Optional, TypeVar
from rainbowadn.collection.collectioninterface import *
@ -9,24 +11,19 @@ from .actions import *
from .binarytree import *
from .core import *
__all__ = ('ActiveBinaryTree',)
__all__ = ("ActiveBinaryTree",)
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable)
ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
MetaDataType = TypeVar("MetaDataType", bound=Mentionable)
class ActiveBinaryTree(
CollectionInterface[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]],
Generic[ActiveKeyType, MetaDataType]
CollectionInterface[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]], Generic[ActiveKeyType, MetaDataType]
):
def __init__(
self,
protocol: BinaryBalancing[
ActiveKeyType,
MetaDataType,
'ActiveBinaryTree[ActiveKeyType, MetaDataType]'
],
reference: NullableReference[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]]
self,
protocol: BinaryBalancing[ActiveKeyType, MetaDataType, ActiveBinaryTree[ActiveKeyType, MetaDataType]],
reference: NullableReference[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]],
):
assert isinstance(protocol, BinaryBalancing)
assert isinstance(reference, NullableReference)
@ -37,45 +34,33 @@ class ActiveBinaryTree(
@classmethod
def empty(
cls,
protocol: BinaryBalancing[ActiveKeyType, MetaDataType, 'ActiveBinaryTree'],
factory: RainbowFactory[ActiveKeyType]
cls,
protocol: BinaryBalancing[ActiveKeyType, MetaDataType, ActiveBinaryTree],
factory: RainbowFactory[ActiveKeyType],
):
assert isinstance(protocol, BinaryBalancing)
assert isinstance(factory, RainbowFactory)
return cls(
protocol,
NullableReference(
Null(),
BinaryTreeFactory(KeyMetadataFactory(factory, protocol.empty_metadata.factory))
)
NullableReference(Null(), BinaryTreeFactory(KeyMetadataFactory(factory, protocol.empty_metadata.factory))),
)
def create(
self,
reference: NullableReference[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]]
) -> 'ActiveBinaryTree[ActiveKeyType, MetaDataType]':
self, reference: NullableReference[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]]
) -> ActiveBinaryTree[ActiveKeyType, MetaDataType]:
assert isinstance(reference, NullableReference)
return ActiveBinaryTree(
self.protocol,
reference
)
return ActiveBinaryTree(self.protocol, reference)
def protocolized(self) -> BinaryProtocolized[
ActiveKeyType,
MetaDataType,
'ActiveBinaryTree[ActiveKeyType, MetaDataType]'
]:
return BinaryProtocolized(
self.creation,
self
)
def protocolized(
self,
) -> BinaryProtocolized[ActiveKeyType, MetaDataType, ActiveBinaryTree[ActiveKeyType, MetaDataType]]:
return BinaryProtocolized(self.creation, self)
async def add(self, key: HashPoint[ActiveKeyType]) -> 'ActiveBinaryTree[ActiveKeyType, MetaDataType]':
async def add(self, key: HashPoint[ActiveKeyType]) -> ActiveBinaryTree[ActiveKeyType, MetaDataType]:
assert isinstance(key, HashPoint)
return await AddAction(key).on(self.protocolized())
async def remove(self, key: HashPoint[ActiveKeyType]) -> 'ActiveBinaryTree[ActiveKeyType, MetaDataType]':
async def remove(self, key: HashPoint[ActiveKeyType]) -> ActiveBinaryTree[ActiveKeyType, MetaDataType]:
assert isinstance(key, HashPoint)
return await RemoveAction(key).on(self.protocolized())
@ -83,20 +68,17 @@ class ActiveBinaryTree(
assert isinstance(key, HashPoint)
return await ContainsAction(key, exact=exact).on(self.protocolized())
async def split(self, key: HashPoint[ActiveKeyType]) -> tuple[
'ActiveBinaryTree[ActiveKeyType, MetaDataType]',
'ActiveBinaryTree[ActiveKeyType, MetaDataType]',
]:
async def split(
self, key: HashPoint[ActiveKeyType]
) -> tuple[ActiveBinaryTree[ActiveKeyType, MetaDataType], ActiveBinaryTree[ActiveKeyType, MetaDataType]]:
return await SplitAction(key).on(self.protocolized())
async def union(
self, other: 'ActiveBinaryTree[ActiveKeyType, MetaDataType]'
) -> 'ActiveBinaryTree[ActiveKeyType, MetaDataType]':
self, other: ActiveBinaryTree[ActiveKeyType, MetaDataType]
) -> ActiveBinaryTree[ActiveKeyType, MetaDataType]:
return await UnionAction(other.protocolized()).on(self.protocolized())
def loose(self) -> CollectionInterface[
BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]
]:
def loose(self) -> CollectionInterface[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]]:
return self
def __eq__(self, other):
@ -106,23 +88,10 @@ class ActiveBinaryTree(
return NotImplemented
class ActiveCreation(
BalancedCreation[
ActiveKeyType,
MetaDataType,
ActiveBinaryTree[ActiveKeyType, MetaDataType]
]
):
class ActiveCreation(BalancedCreation[ActiveKeyType, MetaDataType, ActiveBinaryTree[ActiveKeyType, MetaDataType]]):
async def split(
self,
tree: ActiveBinaryTree[ActiveKeyType, MetaDataType]
) -> Optional[
BinarySplit[
ActiveKeyType,
MetaDataType,
ActiveBinaryTree[ActiveKeyType, MetaDataType]
]
]:
self, tree: ActiveBinaryTree[ActiveKeyType, MetaDataType]
) -> Optional[BinarySplit[ActiveKeyType, MetaDataType, ActiveBinaryTree[ActiveKeyType, MetaDataType]]]:
assert isinstance(tree, ActiveBinaryTree)
if tree.reference.null():
return None
@ -136,10 +105,7 @@ class ActiveCreation(
)
async def _tree(
self,
treel: ActiveBinaryTree,
treer: ActiveBinaryTree,
key: HashPoint[ActiveKeyType]
self, treel: ActiveBinaryTree, treer: ActiveBinaryTree, key: HashPoint[ActiveKeyType]
) -> ActiveBinaryTree:
assert isinstance(treel, ActiveBinaryTree)
assert isinstance(treer, ActiveBinaryTree)
@ -150,7 +116,7 @@ class ActiveCreation(
BinaryTree(
treel.reference,
treer.reference,
KeyMetadata(key, await self.protocol.metadata(treel, treer, key, self))
KeyMetadata(key, await self.protocol.metadata(treel, treer, key, self)),
)
)
),
)

View File

@ -7,10 +7,10 @@ from rainbowadn.core import *
from .actions import *
from .core import *
__all__ = ('AVL',)
__all__ = ("AVL",)
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable)
TreeType = TypeVar('TreeType')
ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
TreeType = TypeVar("TreeType")
class AVL(BinaryBalancing[ActiveKeyType, Integer, TreeType]):
@ -18,11 +18,11 @@ class AVL(BinaryBalancing[ActiveKeyType, Integer, TreeType]):
super().__init__(comparator_, HashPoint.of(Integer(0)))
async def metadata(
self,
treel: TreeType,
treer: TreeType,
key: HashPoint[ActiveKeyType],
creation: BinaryCreation[ActiveKeyType, Integer, TreeType]
self,
treel: TreeType,
treer: TreeType,
key: HashPoint[ActiveKeyType],
creation: BinaryCreation[ActiveKeyType, Integer, TreeType],
) -> HashPoint[Integer]:
assert isinstance(key, HashPoint)
assert isinstance(creation, BinaryCreation)
@ -35,8 +35,7 @@ class AVL(BinaryBalancing[ActiveKeyType, Integer, TreeType]):
return HashPoint.of(
Integer(
1
+
max(
+ max(
height_l,
height_r,
)
@ -45,43 +44,37 @@ class AVL(BinaryBalancing[ActiveKeyType, Integer, TreeType]):
@classmethod
async def height(
cls,
protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType],
cls,
protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType],
) -> int:
assert isinstance(protocolized, BinaryProtocolized)
return await HeightAction().on(protocolized)
@classmethod
async def full_height(
cls,
protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType],
cls,
protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType],
) -> tuple[int, Optional[BinarySplit[ActiveKeyType, Integer, TreeType]]]:
assert isinstance(protocolized, BinaryProtocolized)
return await FullHeightAction().on(protocolized)
async def balance(
self,
protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType],
self,
protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType],
) -> TreeType:
assert isinstance(protocolized, BinaryProtocolized)
return await BalanceAction().on(protocolized)
class HeightAction(
BinaryAction[ActiveKeyType, Integer, TreeType, int],
Generic[ActiveKeyType, TreeType]
):
class HeightAction(BinaryAction[ActiveKeyType, Integer, TreeType, int], Generic[ActiveKeyType, TreeType]):
async def on_null(
self,
protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType],
self,
protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType],
) -> int:
assert isinstance(protocolized, BinaryProtocolized)
return 0
async def on_split(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType]
) -> int:
async def on_split(self, case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType]) -> int:
assert isinstance(case, ProtocolizedBinarySplit)
metadata: Integer = await case.split.metadata.resolve()
assert isinstance(metadata, Integer)
@ -89,24 +82,18 @@ class HeightAction(
class FullHeightAction(
BinaryAction[
ActiveKeyType,
Integer,
TreeType,
tuple[int, Optional[BinarySplit[ActiveKeyType, Integer, TreeType]]]
],
Generic[ActiveKeyType, TreeType]
BinaryAction[ActiveKeyType, Integer, TreeType, tuple[int, Optional[BinarySplit[ActiveKeyType, Integer, TreeType]]]],
Generic[ActiveKeyType, TreeType],
):
async def on_null(
self,
protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType],
self,
protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType],
) -> tuple[int, Optional[BinarySplit[ActiveKeyType, Integer, TreeType]]]:
assert isinstance(protocolized, BinaryProtocolized)
return 0, None
async def on_split(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType]
self, case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType]
) -> tuple[int, Optional[BinarySplit[ActiveKeyType, Integer, TreeType]]]:
assert isinstance(case, ProtocolizedBinarySplit)
metadata: Integer = await case.split.metadata.resolve()
@ -114,21 +101,15 @@ class FullHeightAction(
return metadata.integer, case.split
class BalanceAction(
BinaryAction[ActiveKeyType, Integer, TreeType, TreeType],
Generic[ActiveKeyType, TreeType]
):
class BalanceAction(BinaryAction[ActiveKeyType, Integer, TreeType, TreeType], Generic[ActiveKeyType, TreeType]):
async def on_null(
self,
protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType],
self,
protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType],
) -> TreeType:
assert isinstance(protocolized, BinaryProtocolized)
return protocolized.tree
async def on_split(
self,
case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType]
) -> TreeType:
async def on_split(self, case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType]) -> TreeType:
assert isinstance(case, ProtocolizedBinarySplit)
(height_l, splitl), (height_r, splitr) = await gather(
AVL.full_height(case.protocolizedl()),
@ -151,11 +132,11 @@ class BalanceAction(
@classmethod
async def on_symmetric(
cls,
symmetry: Symmetric[ActiveKeyType, Integer, TreeType],
treei: TreeType,
key: HashPoint[ActiveKeyType],
splito: BinarySplit[ActiveKeyType, Integer, TreeType],
cls,
symmetry: Symmetric[ActiveKeyType, Integer, TreeType],
treei: TreeType,
key: HashPoint[ActiveKeyType],
splito: BinarySplit[ActiveKeyType, Integer, TreeType],
) -> TreeType:
assert isinstance(symmetry, Symmetric)
assert isinstance(key, HashPoint)
@ -173,14 +154,8 @@ class BalanceAction(
symmetry.tree(treei, symmetry.inner(splitoi), key),
symmetry.tree(symmetry.outer(splitoi), symmetry.outer(splito), splito.key),
)
return await symmetry.tree(
inner,
outer,
splitoi.key
)
return await symmetry.tree(inner, outer, splitoi.key)
else:
return await symmetry.tree(
await symmetry.tree(treei, symmetry.inner(splito), key),
symmetry.outer(splito),
splito.key
await symmetry.tree(treei, symmetry.inner(splito), key), symmetry.outer(splito), splito.key
)

View File

@ -1,27 +1,32 @@
from __future__ import annotations
from typing import Generic, Iterable, TypeVar
from rainbowadn.core import *
from rainbowadn.nullability import *
__all__ = ('BinaryTree', 'BinaryTreeFactory',)
__all__ = (
"BinaryTree",
"BinaryTreeFactory",
)
TreeKeyType = TypeVar('TreeKeyType', bound=Mentionable)
TreeKeyType = TypeVar("TreeKeyType", bound=Mentionable)
class BinaryTree(RecursiveMentionable, Generic[TreeKeyType]):
def __factory__(self) -> RainbowFactory['BinaryTree[TreeKeyType]']:
def __factory__(self) -> RainbowFactory[BinaryTree[TreeKeyType]]:
return self.factory(self.key.__factory__())
@classmethod
def factory(cls, factory: RainbowFactory[TreeKeyType]) -> RainbowFactory['BinaryTree[TreeKeyType]']:
def factory(cls, factory: RainbowFactory[TreeKeyType]) -> RainbowFactory[BinaryTree[TreeKeyType]]:
assert isinstance(factory, RainbowFactory)
return BinaryTreeFactory(factory)
def __init__(
self,
treel: NullableReference['BinaryTree[TreeKeyType]'],
treer: NullableReference['BinaryTree[TreeKeyType]'],
key: TreeKeyType
self,
treel: NullableReference[BinaryTree[TreeKeyType]],
treer: NullableReference[BinaryTree[TreeKeyType]],
key: TreeKeyType,
):
assert isinstance(treel, NullableReference)
assert isinstance(treer, NullableReference)
@ -46,9 +51,7 @@ class BinaryTree(RecursiveMentionable, Generic[TreeKeyType]):
assert isinstance(treel_str, str)
assert isinstance(key_str, str)
assert isinstance(treer_str, str)
return f'{treel_str}' \
f'{tabulate(tab)}{key_str}' \
f'{tabulate(tab)}{treer_str}'
return f"{treel_str}" f"{tabulate(tab)}{key_str}" f"{tabulate(tab)}{treer_str}"
class BinaryTreeFactory(RainbowFactory[BinaryTree[TreeKeyType]], Generic[TreeKeyType]):
@ -61,12 +64,9 @@ class BinaryTreeFactory(RainbowFactory[BinaryTree[TreeKeyType]], Generic[TreeKey
assert isinstance(source, bytes)
assert isinstance(resolver, HashResolver)
return BinaryTree(
self.reference_factory.from_bytes(source[:HashPoint.HASH_LENGTH], resolver),
self.reference_factory.from_bytes(
source[HashPoint.HASH_LENGTH:HashPoint.HASH_LENGTH * 2],
resolver
),
self.factory.from_bytes(source[HashPoint.HASH_LENGTH * 2:], resolver),
self.reference_factory.from_bytes(source[: HashPoint.HASH_LENGTH], resolver),
self.reference_factory.from_bytes(source[HashPoint.HASH_LENGTH : HashPoint.HASH_LENGTH * 2], resolver),
self.factory.from_bytes(source[HashPoint.HASH_LENGTH * 2 :], resolver),
)
def loose(self) -> RainbowFactory[BinaryTree[TreeKeyType]]:

View File

@ -1,11 +1,11 @@
__all__ = (
'BalancedCreation',
'BinaryBalancing',
'BinaryCreation',
'BinaryMetadata',
'BinaryProtocolized',
'BinarySplit',
'ProtocolizedBinarySplit',
"BalancedCreation",
"BinaryBalancing",
"BinaryCreation",
"BinaryMetadata",
"BinaryProtocolized",
"BinarySplit",
"ProtocolizedBinarySplit",
)
from .balancedcreation import BalancedCreation

View File

@ -7,22 +7,17 @@ from .binarybalancing import *
from .binarycreation import *
from .binaryprotocolized import *
__all__ = ('BalancedCreation',)
__all__ = ("BalancedCreation",)
TreeType = TypeVar('TreeType')
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable)
TreeType = TypeVar("TreeType")
ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
MetaDataType = TypeVar("MetaDataType", bound=Mentionable)
class BalancedCreation(
BinaryCreation[ActiveKeyType, MetaDataType, TreeType],
Generic[ActiveKeyType, MetaDataType, TreeType],
abc.ABC
BinaryCreation[ActiveKeyType, MetaDataType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType], abc.ABC
):
def __init__(
self,
protocol: BinaryBalancing[ActiveKeyType, MetaDataType, TreeType]
):
def __init__(self, protocol: BinaryBalancing[ActiveKeyType, MetaDataType, TreeType]):
assert isinstance(protocol, BinaryBalancing)
self.protocol = protocol
super().__init__(protocol.comparator)
@ -36,19 +31,10 @@ class BalancedCreation(
self.protocol.balance(BinaryProtocolized(self, treel)),
self.protocol.balance(BinaryProtocolized(self, treer)),
)
return await self.protocol.balance(
BinaryProtocolized(
self,
await self._tree(
balancedl,
balancedr,
key
)
)
)
return await self.protocol.balance(BinaryProtocolized(self, await self._tree(balancedl, balancedr, key)))
async def verify_metadata(
self, treel: TreeType, treer: TreeType, key: HashPoint[ActiveKeyType], metadata: HashPoint[MetaDataType]
self, treel: TreeType, treer: TreeType, key: HashPoint[ActiveKeyType], metadata: HashPoint[MetaDataType]
) -> bool:
assert_true(await self.protocol.verify_metadata(treel, treer, key, metadata, self))
return True

View File

@ -7,17 +7,15 @@ from rainbowadn.core import *
from .binarymetadata import *
from .binaryprotocolized import *
__all__ = ('BinaryBalancing',)
__all__ = ("BinaryBalancing",)
TreeType = TypeVar('TreeType')
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable)
TreeType = TypeVar("TreeType")
ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
MetaDataType = TypeVar("MetaDataType", bound=Mentionable)
class BinaryBalancing(
BinaryMetadata[ActiveKeyType, MetaDataType, TreeType],
Generic[ActiveKeyType, MetaDataType, TreeType],
abc.ABC
BinaryMetadata[ActiveKeyType, MetaDataType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType], abc.ABC
):
def __init__(self, comparator_: Comparator[ActiveKeyType], empty_metadata: HashPoint[MetaDataType]):
assert isinstance(comparator_, Comparator)
@ -26,7 +24,7 @@ class BinaryBalancing(
super().__init__(empty_metadata)
async def balance(
self,
protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType],
self,
protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType],
) -> TreeType:
raise NotImplementedError

View File

@ -5,11 +5,11 @@ from rainbowadn.core import *
from .binarysplit import *
__all__ = ('BinaryCreation',)
__all__ = ("BinaryCreation",)
TreeType = TypeVar('TreeType')
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable)
TreeType = TypeVar("TreeType")
ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
MetaDataType = TypeVar("MetaDataType", bound=Mentionable)
class BinaryCreation(Generic[ActiveKeyType, MetaDataType, TreeType]):
@ -17,9 +17,7 @@ class BinaryCreation(Generic[ActiveKeyType, MetaDataType, TreeType]):
assert isinstance(comparator, Comparator)
self.comparator = comparator
async def split(self, tree: TreeType) -> Optional[
BinarySplit[ActiveKeyType, MetaDataType, TreeType]
]:
async def split(self, tree: TreeType) -> Optional[BinarySplit[ActiveKeyType, MetaDataType, TreeType]]:
"""result of this method is supposed to be used right after the call, therefore all values are resolved"""
raise NotImplementedError
@ -27,6 +25,6 @@ class BinaryCreation(Generic[ActiveKeyType, MetaDataType, TreeType]):
raise NotImplementedError
async def verify_metadata(
self, treel: TreeType, treer: TreeType, key: HashPoint[ActiveKeyType], metadata: HashPoint[MetaDataType]
self, treel: TreeType, treer: TreeType, key: HashPoint[ActiveKeyType], metadata: HashPoint[MetaDataType]
) -> bool:
raise NotImplementedError

View File

@ -4,11 +4,11 @@ from rainbowadn.core import *
from .binarycreation import *
__all__ = ('BinaryMetadata',)
__all__ = ("BinaryMetadata",)
TreeType = TypeVar('TreeType')
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable)
TreeType = TypeVar("TreeType")
ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
MetaDataType = TypeVar("MetaDataType", bound=Mentionable)
class BinaryMetadata(Generic[ActiveKeyType, MetaDataType, TreeType]):
@ -17,21 +17,21 @@ class BinaryMetadata(Generic[ActiveKeyType, MetaDataType, TreeType]):
self.empty_metadata = empty_metadata
async def metadata(
self,
treel: TreeType,
treer: TreeType,
key: HashPoint[ActiveKeyType],
creation: BinaryCreation[ActiveKeyType, MetaDataType, TreeType],
self,
treel: TreeType,
treer: TreeType,
key: HashPoint[ActiveKeyType],
creation: BinaryCreation[ActiveKeyType, MetaDataType, TreeType],
) -> HashPoint[MetaDataType]:
raise NotImplementedError
async def verify_metadata(
self,
treel: TreeType,
treer: TreeType,
key: HashPoint[ActiveKeyType],
metadata: HashPoint[MetaDataType],
creation: BinaryCreation[ActiveKeyType, MetaDataType, TreeType],
self,
treel: TreeType,
treer: TreeType,
key: HashPoint[ActiveKeyType],
metadata: HashPoint[MetaDataType],
creation: BinaryCreation[ActiveKeyType, MetaDataType, TreeType],
) -> bool:
assert_eq(await self.metadata(treel, treer, key, creation), metadata)
return True

View File

@ -5,21 +5,15 @@ from rainbowadn.core import *
from .binarycreation import *
from .binarysplit import *
__all__ = ('BinaryProtocolized',)
__all__ = ("BinaryProtocolized",)
TreeType = TypeVar('TreeType')
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable)
TreeType = TypeVar("TreeType")
ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
MetaDataType = TypeVar("MetaDataType", bound=Mentionable)
class BinaryProtocolized(
Generic[ActiveKeyType, MetaDataType, TreeType]
):
def __init__(
self,
creation: BinaryCreation[ActiveKeyType, MetaDataType, TreeType],
tree: TreeType
):
class BinaryProtocolized(Generic[ActiveKeyType, MetaDataType, TreeType]):
def __init__(self, creation: BinaryCreation[ActiveKeyType, MetaDataType, TreeType], tree: TreeType):
assert isinstance(creation, BinaryCreation)
self.creation = creation
self.tree = tree

View File

@ -2,22 +2,16 @@ from typing import Generic, TypeVar
from rainbowadn.core import *
__all__ = ('BinarySplit',)
__all__ = ("BinarySplit",)
TreeType = TypeVar('TreeType')
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable)
TreeType = TypeVar("TreeType")
ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
MetaDataType = TypeVar("MetaDataType", bound=Mentionable)
class BinarySplit(
Generic[ActiveKeyType, MetaDataType, TreeType]
):
class BinarySplit(Generic[ActiveKeyType, MetaDataType, TreeType]):
def __init__(
self,
treel: TreeType,
key: HashPoint[ActiveKeyType],
metadata: HashPoint[MetaDataType],
treer: TreeType
self, treel: TreeType, key: HashPoint[ActiveKeyType], metadata: HashPoint[MetaDataType], treer: TreeType
):
assert isinstance(key, HashPoint)
assert isinstance(metadata, HashPoint)

View File

@ -1,3 +1,5 @@
from __future__ import annotations
from typing import Generic, Optional, TypeVar
from rainbowadn.core import *
@ -6,21 +8,19 @@ from .binarycreation import *
from .binaryprotocolized import *
from .binarysplit import *
__all__ = ('ProtocolizedBinarySplit',)
__all__ = ("ProtocolizedBinarySplit",)
TreeType = TypeVar('TreeType')
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable)
TreeType = TypeVar("TreeType")
ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
MetaDataType = TypeVar("MetaDataType", bound=Mentionable)
class ProtocolizedBinarySplit(
Generic[ActiveKeyType, MetaDataType, TreeType]
):
class ProtocolizedBinarySplit(Generic[ActiveKeyType, MetaDataType, TreeType]):
def __init__(
self,
protocol: BinaryCreation[ActiveKeyType, MetaDataType, TreeType],
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType],
tree: TreeType
self,
protocol: BinaryCreation[ActiveKeyType, MetaDataType, TreeType],
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType],
tree: TreeType,
):
assert isinstance(protocol, BinaryCreation)
assert isinstance(split, BinarySplit)
@ -42,11 +42,8 @@ class ProtocolizedBinarySplit(
@classmethod
async def split_of(
cls,
protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType]
) -> Optional[
'ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]'
]:
cls, protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType]
) -> Optional[ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]]:
assert isinstance(protocolized, BinaryProtocolized)
if (split := await protocolized.split()) is None:
return None
@ -55,8 +52,6 @@ class ProtocolizedBinarySplit(
async def verify_metadata(self) -> bool:
assert_true(
await self.protocol.verify_metadata(
self.split.treel, self.split.treer, self.split.key, self.split.metadata
)
await self.protocol.verify_metadata(self.split.treel, self.split.treer, self.split.key, self.split.metadata)
)
return True

View File

@ -1,35 +1,59 @@
__all__ = (
'assert_true', 'assert_trues', 'assert_false', 'assert_none', 'assert_none_strict', 'assert_eq',
'ExtendableResolver',
'gather', 'asum', 'alist', 'set_gather_asyncio', 'set_gather_linear', 'aidentity',
'hash_point_format', 'tabulate', 'enable_newline', 'disable_newline',
'HashPoint',
'HashResolver',
'LocalMetaOrigin',
'LocalOrigin',
'Mentionable',
'MetaOrigin',
'Origin',
'RainbowFactory',
'RecursiveMentionable',
'ResolverMetaOrigin',
'ResolverOrigin',
'StaticMentionable', 'StaticFactory',
"assert_true",
"assert_trues",
"assert_false",
"assert_none",
"assert_none_strict",
"assert_eq",
"ExtendableResolver",
"gather",
"asum",
"alist",
"set_gather_asyncio",
"set_gather_linear",
"aidentity",
"hash_point_format",
"tabulate",
"enable_newline",
"disable_newline",
"HashPoint",
"HashResolver",
"LocalMetaOrigin",
"LocalOrigin",
"Mentionable",
"MetaOrigin",
"Origin",
"RainbowFactory",
"RecursiveMentionable",
"ResolverMetaOrigin",
"ResolverOrigin",
"StaticMentionable",
"StaticFactory",
)
from .asserts import (
assert_eq, assert_false, assert_none, assert_none_strict,
assert_true, assert_trues
assert_eq,
assert_false,
assert_none,
assert_none_strict,
assert_true,
assert_trues,
)
from .extendableresolver import ExtendableResolver
from .gather import (
aidentity, alist, asum, gather, set_gather_asyncio,
set_gather_linear
aidentity,
alist,
asum,
gather,
set_gather_asyncio,
set_gather_linear,
)
from .hashpoint import HashPoint
from .hashpointformat import (
disable_newline, enable_newline,
hash_point_format, tabulate
disable_newline,
enable_newline,
hash_point_format,
tabulate,
)
from .hashresolver import HashResolver
from .localmetaorigin import LocalMetaOrigin

View File

@ -1,6 +1,13 @@
from typing import Any, Iterable, Optional, TypeVar
__all__ = ('assert_true', 'assert_trues', 'assert_false', 'assert_none', 'assert_none_strict', 'assert_eq',)
__all__ = (
"assert_true",
"assert_trues",
"assert_false",
"assert_none",
"assert_none_strict",
"assert_eq",
)
def assert_true(value: bool) -> bool:
@ -19,7 +26,7 @@ def assert_false(value: bool) -> bool:
return True
T = TypeVar('T')
T = TypeVar("T")
def assert_none(value: Optional[Any]) -> bool:

View File

@ -1,3 +1,5 @@
from __future__ import annotations
import abc
from typing import TypeVar
@ -6,13 +8,13 @@ from .hashresolver import *
from .mentionable import *
from .resolvermetaorigin import *
__all__ = ('ExtendableResolver',)
__all__ = ("ExtendableResolver",)
Mentioned = TypeVar('Mentioned', bound=Mentionable)
Mentioned = TypeVar("Mentioned", bound=Mentionable)
class ExtendableResolver(HashResolver, abc.ABC):
async def extend(self, hash_point: HashPoint[Mentionable]) -> 'ExtendableResolver':
async def extend(self, hash_point: HashPoint[Mentionable]) -> ExtendableResolver:
raise NotImplementedError
async def migrate(self, hash_point: HashPoint[Mentioned]) -> HashPoint[Mentioned]:

View File

@ -1,7 +1,14 @@
import asyncio
from typing import Any, AsyncIterable, Awaitable, Coroutine, TypeVar, overload
__all__ = ('gather', 'asum', 'alist', 'set_gather_asyncio', 'set_gather_linear', 'aidentity',)
__all__ = (
"gather",
"asum",
"alist",
"set_gather_asyncio",
"set_gather_linear",
"aidentity",
)
_gather: Any = asyncio.gather
@ -20,28 +27,23 @@ def set_gather_linear():
_gather = _local_gather
T0 = TypeVar('T0')
T1 = TypeVar('T1')
T2 = TypeVar('T2')
T3 = TypeVar('T3')
T4 = TypeVar('T4')
T0 = TypeVar("T0")
T1 = TypeVar("T1")
T2 = TypeVar("T2")
T3 = TypeVar("T3")
T4 = TypeVar("T4")
@overload
def gather(a0: Coroutine[Any, Any, T0], a1: Coroutine[Any, Any, T1], /) -> Awaitable[tuple[T0, T1]]:
...
@overload
def gather(
a0: Coroutine[Any, Any, T0],
a1: Coroutine[Any, Any, T1],
/
) -> Awaitable[tuple[T0, T1]]: ...
@overload
def gather(
a0: Coroutine[Any, Any, T0],
a1: Coroutine[Any, Any, T1],
a2: Coroutine[Any, Any, T2],
/
) -> Awaitable[tuple[T0, T1, T2]]: ...
a0: Coroutine[Any, Any, T0], a1: Coroutine[Any, Any, T1], a2: Coroutine[Any, Any, T2], /
) -> Awaitable[tuple[T0, T1, T2]]:
...
@overload
@ -50,8 +52,9 @@ def gather(
a1: Coroutine[Any, Any, T1],
a2: Coroutine[Any, Any, T2],
a3: Coroutine[Any, Any, T3],
/
) -> Awaitable[tuple[T0, T1, T2, T3]]: ...
/,
) -> Awaitable[tuple[T0, T1, T2, T3]]:
...
@overload
@ -61,8 +64,9 @@ def gather(
a2: Coroutine[Any, Any, T2],
a3: Coroutine[Any, Any, T3],
a4: Coroutine[Any, Any, T4],
/
) -> Awaitable[tuple[T0, T1, T2, T3, T4]]: ...
/,
) -> Awaitable[tuple[T0, T1, T2, T3, T4]]:
...
# @overload
@ -77,7 +81,7 @@ async def asum(iterable):
return sum(await gather(*iterable))
T = TypeVar('T')
T = TypeVar("T")
async def alist(aiterable: AsyncIterable[T]) -> list[T]:

View File

@ -1,5 +1,7 @@
from __future__ import annotations
import hashlib
from typing import Generic, TypeVar
from typing import Generic, Type, TypeVar
from .asserts import *
from .localorigin import *
@ -7,10 +9,10 @@ from .mentionable import *
from .origin import *
from .rainbow_factory import *
__all__ = ('HashPoint',)
__all__ = ("HashPoint",)
Mentioned = TypeVar('Mentioned', bound=Mentionable, covariant=True)
MentionedI = TypeVar('MentionedI', bound=Mentionable)
Mentioned = TypeVar("Mentioned", bound=Mentionable, covariant=True)
MentionedI = TypeVar("MentionedI", bound=Mentionable)
def _hash(source: bytes) -> bytes:
@ -19,11 +21,7 @@ def _hash(source: bytes) -> bytes:
class HashPoint(Generic[Mentioned]):
def __init__(
self,
point: bytes,
origin: Origin[Mentioned]
):
def __init__(self, point: bytes, origin: Origin[Mentioned]):
assert isinstance(point, bytes)
assert isinstance(origin, Origin)
assert_eq(len(point), self.HASH_LENGTH)
@ -35,8 +33,8 @@ class HashPoint(Generic[Mentioned]):
def __bytes__(self):
return self.point
HASH_LENGTH = len(_hash(b''))
NULL_HASH = b'\0' * HASH_LENGTH
HASH_LENGTH = len(_hash(b""))
NULL_HASH = b"\0" * HASH_LENGTH
@classmethod
def hash(cls, source: bytes) -> bytes:
@ -55,12 +53,10 @@ class HashPoint(Generic[Mentioned]):
return topology_hash + bytes(mentioned)
@classmethod
def of(cls, mentioned: MentionedI) -> 'HashPoint[MentionedI]':
def of(cls: Type[HashPoint[MentionedI]], mentioned: MentionedI) -> HashPoint[MentionedI]:
assert issubclass(cls, HashPoint)
assert isinstance(mentioned, Mentionable)
return cls(
cls.hash(cls.bytes_of_mentioned(mentioned)), LocalOrigin(mentioned)
)
return cls(cls.hash(cls.bytes_of_mentioned(mentioned)), LocalOrigin(mentioned))
async def resolve(self) -> Mentioned:
resolved: Mentioned = await self.origin.resolve()

View File

@ -2,7 +2,12 @@ from .hashpoint import *
from .mentionable import *
from .recursivementionable import *
__all__ = ('hash_point_format', 'tabulate', 'enable_newline', 'disable_newline',)
__all__ = (
"hash_point_format",
"tabulate",
"enable_newline",
"disable_newline",
)
async def hash_point_format(hash_point: HashPoint, tab: int) -> str:
@ -32,6 +37,6 @@ def disable_newline():
def tabulate(tab: int) -> str:
assert isinstance(tab, int)
if newline:
return '\n' + ' ' * tab
return "\n" + " " * tab
else:
return ' '
return " "

View File

@ -1,6 +1,8 @@
__all__ = ('HashResolver',)
from __future__ import annotations
__all__ = ("HashResolver",)
class HashResolver:
async def resolve(self, point: bytes) -> tuple[bytes, 'HashResolver']:
async def resolve(self, point: bytes) -> tuple[bytes, HashResolver]:
raise NotImplementedError

View File

@ -7,9 +7,9 @@ from .metaorigin import *
from .origin import *
from .rainbow_factory import *
__all__ = ('LocalMetaOrigin',)
__all__ = ("LocalMetaOrigin",)
Mentioned = TypeVar('Mentioned', bound=Mentionable)
Mentioned = TypeVar("Mentioned", bound=Mentionable)
class LocalMetaOrigin(MetaOrigin[Mentioned], Generic[Mentioned]):

View File

@ -3,9 +3,9 @@ from typing import Generic, TypeVar
from .mentionable import *
from .origin import *
__all__ = ('LocalOrigin',)
__all__ = ("LocalOrigin",)
Mentioned = TypeVar('Mentioned')
Mentioned = TypeVar("Mentioned")
class LocalOrigin(Origin[Mentioned], Generic[Mentioned]):

View File

@ -2,9 +2,9 @@ from typing import TypeVar
from .rainbow_factory import *
__all__ = ('Mentionable',)
__all__ = ("Mentionable",)
Mentioned = TypeVar('Mentioned')
Mentioned = TypeVar("Mentioned")
class Mentionable:

View File

@ -6,9 +6,9 @@ from .mentionable import *
from .origin import *
from .rainbow_factory import *
__all__ = ('MetaOrigin',)
__all__ = ("MetaOrigin",)
Mentioned = TypeVar('Mentioned', bound=Mentionable, covariant=True)
Mentioned = TypeVar("Mentioned", bound=Mentionable, covariant=True)
class MetaOrigin(Generic[Mentioned]):

View File

@ -2,9 +2,9 @@ from typing import Generic, TypeVar
from .rainbow_factory import *
__all__ = ('Origin',)
__all__ = ("Origin",)
Mentioned = TypeVar('Mentioned', covariant=True)
Mentioned = TypeVar("Mentioned", covariant=True)
class Origin(Generic[Mentioned]):

View File

@ -2,9 +2,9 @@ from typing import Generic, TypeVar
from .hashresolver import *
__all__ = ('RainbowFactory',)
__all__ = ("RainbowFactory",)
Mentioned = TypeVar('Mentioned', covariant=True)
Mentioned = TypeVar("Mentioned", covariant=True)
class RainbowFactory(Generic[Mentioned]):

View File

@ -4,7 +4,7 @@ from typing import Iterable
from .hashpoint import *
from .mentionable import *
__all__ = ('RecursiveMentionable',)
__all__ = ("RecursiveMentionable",)
class RecursiveMentionable(Mentionable, abc.ABC):
@ -20,7 +20,7 @@ class RecursiveMentionable(Mentionable, abc.ABC):
async def str(self, tab: int) -> str:
assert isinstance(tab, int)
return f'(recursive {self.__class__.__name__})'
return f"(recursive {self.__class__.__name__})"
def __topology_hash__(self) -> bytes:
return HashPoint.hash(b''.join(hash_point.point for hash_point in self.points()))
return HashPoint.hash(b"".join(hash_point.point for hash_point in self.points()))

View File

@ -9,9 +9,9 @@ from .origin import *
from .rainbow_factory import *
from .resolverorigin import *
__all__ = ('ResolverMetaOrigin',)
__all__ = ("ResolverMetaOrigin",)
Mentioned = TypeVar('Mentioned', bound=Mentionable, covariant=True)
Mentioned = TypeVar("Mentioned", bound=Mentionable, covariant=True)
class ResolverMetaOrigin(MetaOrigin[Mentioned], Generic[Mentioned]):

View File

@ -7,18 +7,13 @@ from .mentionable import *
from .origin import *
from .rainbow_factory import *
__all__ = ('ResolverOrigin',)
__all__ = ("ResolverOrigin",)
Mentioned = TypeVar('Mentioned', bound=Mentionable, covariant=True)
Mentioned = TypeVar("Mentioned", bound=Mentionable, covariant=True)
class ResolverOrigin(Origin[Mentioned], Generic[Mentioned]):
def __init__(
self,
factory: RainbowFactory[Mentioned],
point: bytes,
resolver: HashResolver
):
def __init__(self, factory: RainbowFactory[Mentioned], point: bytes, resolver: HashResolver):
assert isinstance(factory, RainbowFactory)
assert isinstance(point, bytes)
assert isinstance(resolver, HashResolver)
@ -31,9 +26,9 @@ class ResolverOrigin(Origin[Mentioned], Generic[Mentioned]):
resolved, resolver = await self.resolver.resolve(self.point)
assert isinstance(resolved, bytes)
assert isinstance(resolver, HashResolver)
mentioned: Mentioned = self.factory.from_bytes(resolved[HashPoint.HASH_LENGTH:], resolver)
mentioned: Mentioned = self.factory.from_bytes(resolved[HashPoint.HASH_LENGTH :], resolver)
assert isinstance(mentioned, Mentionable)
assert_eq(mentioned.__topology_hash__(), resolved[:HashPoint.HASH_LENGTH])
assert_eq(mentioned.__topology_hash__(), resolved[: HashPoint.HASH_LENGTH])
assert_eq(self.point, HashPoint.hash(HashPoint.bytes_of_mentioned(mentioned)))
return mentioned

View File

@ -5,9 +5,12 @@ from .hashresolver import *
from .mentionable import *
from .rainbow_factory import *
__all__ = ('StaticMentionable', 'StaticFactory',)
__all__ = (
"StaticMentionable",
"StaticFactory",
)
StaticMentioned = TypeVar('StaticMentioned', bound='StaticMentionable')
StaticMentioned = TypeVar("StaticMentioned", bound="StaticMentionable")
class StaticMentionable(Mentionable, abc.ABC):

View File

@ -1,5 +1,6 @@
__all__ = (
'Encrypted', 'EncryptedFactory',
"Encrypted",
"EncryptedFactory",
)
from .encrypted import Encrypted, EncryptedFactory

View File

@ -1,3 +1,5 @@
from __future__ import annotations
from typing import Generic, Iterable, TypeVar
from nacl.bindings import crypto_hash_sha256
@ -5,20 +7,23 @@ from nacl.secret import SecretBox
from rainbowadn.core import *
__all__ = ('Encrypted', 'EncryptedFactory',)
__all__ = (
"Encrypted",
"EncryptedFactory",
)
EncryptedType = TypeVar('EncryptedType', bound=Mentionable)
EncryptedType = TypeVar("EncryptedType", bound=Mentionable)
class Encrypted(RecursiveMentionable, Generic[EncryptedType]):
"""unstable"""
def __init__(
self,
key: bytes,
resolution: tuple[HashPoint['Encrypted'], ...],
mapping: dict[bytes, HashPoint['Encrypted']],
decrypted: EncryptedType
self,
key: bytes,
resolution: tuple[HashPoint[Encrypted], ...],
mapping: dict[bytes, HashPoint[Encrypted]],
decrypted: EncryptedType,
):
assert isinstance(key, bytes)
assert isinstance(resolution, tuple)
@ -38,49 +43,34 @@ class Encrypted(RecursiveMentionable, Generic[EncryptedType]):
return self.resolution
@classmethod
async def encrypt(cls, decrypted: EncryptedType, key: bytes) -> 'Encrypted[EncryptedType]':
async def encrypt(cls, decrypted: EncryptedType, key: bytes) -> Encrypted[EncryptedType]:
assert isinstance(decrypted, Mentionable)
assert isinstance(key, bytes)
hashpoints = tuple(decrypted.points()) if isinstance(decrypted, RecursiveMentionable) else ()
resolution = tuple(
await gather(
*(
cls.encrypt_hashpoint(hash_point, key) for hash_point in hashpoints
)
)
)
return cls.construct(
key,
resolution,
hashpoints,
decrypted
)
resolution = tuple(await gather(*(cls.encrypt_hashpoint(hash_point, key) for hash_point in hashpoints)))
return cls.construct(key, resolution, hashpoints, decrypted)
@classmethod
async def encrypt_hashpoint(
cls, hash_point: HashPoint[EncryptedType], key: bytes
) -> HashPoint['Encrypted[EncryptedType]']:
cls, hash_point: HashPoint[EncryptedType], key: bytes
) -> HashPoint[Encrypted[EncryptedType]]:
assert isinstance(hash_point, HashPoint)
assert isinstance(key, bytes)
if isinstance(hash_point.origin, ResolverOrigin):
resolver: HashResolver = hash_point.origin.resolver
assert isinstance(resolver, HashResolver)
if isinstance(resolver, EncryptedResolver) and resolver.key == key:
return ShortcutOrigin(
hash_point.factory,
resolver.mapping[hash_point.point],
key
).hash_point()
return ShortcutOrigin(hash_point.factory, resolver.mapping[hash_point.point], key).hash_point()
return HashPoint.of(await cls.encrypt(await hash_point.resolve(), key))
@classmethod
def construct(
cls,
key: bytes,
resolution: tuple[HashPoint['Encrypted'], ...],
hashpoints: tuple[HashPoint, ...],
decrypted: EncryptedType
) -> 'Encrypted[EncryptedType]':
cls,
key: bytes,
resolution: tuple[HashPoint[Encrypted], ...],
hashpoints: tuple[HashPoint, ...],
decrypted: EncryptedType,
) -> Encrypted[EncryptedType]:
assert isinstance(key, bytes)
assert isinstance(resolution, tuple)
assert isinstance(hashpoints, tuple)
@ -92,23 +82,19 @@ class Encrypted(RecursiveMentionable, Generic[EncryptedType]):
key,
resolution,
mapping,
decrypted.__factory__().from_bytes(
bytes(decrypted),
EncryptedResolver(mapping, key)
)
decrypted.__factory__().from_bytes(bytes(decrypted), EncryptedResolver(mapping, key)),
)
def __bytes__(self):
source: bytes = len(self.resolution).to_bytes(8, 'little') + b''.join(
encrypted.point
for
encrypted
in self.resolution
) + bytes(self.decrypted)
source: bytes = (
len(self.resolution).to_bytes(8, "little")
+ b"".join(encrypted.point for encrypted in self.resolution)
+ bytes(self.decrypted)
)
nonce: bytes = crypto_hash_sha256(self.key + source)[:24]
return SecretBox(self.key).encrypt(source, nonce=nonce)
def __factory__(self) -> RainbowFactory['Encrypted[EncryptedType]']:
def __factory__(self) -> RainbowFactory[Encrypted[EncryptedType]]:
return EncryptedFactory(self.factory, self.key)
@ -123,9 +109,9 @@ class EncryptedFactory(RainbowFactory[Encrypted[EncryptedType]], Generic[Encrypt
assert isinstance(source, bytes)
assert isinstance(resolver, HashResolver)
plain: bytes = SecretBox(self.key).decrypt(source)
resolution_size: int = int.from_bytes(plain[:8], 'little')
resolution_size: int = int.from_bytes(plain[:8], "little")
decrypted: EncryptedType = self.factory.from_bytes(
plain[8 + resolution_size * HashPoint.HASH_LENGTH:],
plain[8 + resolution_size * HashPoint.HASH_LENGTH :],
resolver,
)
assert isinstance(decrypted, Mentionable)
@ -133,20 +119,13 @@ class EncryptedFactory(RainbowFactory[Encrypted[EncryptedType]], Generic[Encrypt
assert_eq(len(hashpoints), resolution_size)
resolution: tuple[HashPoint[Encrypted], ...] = tuple(
ResolverOrigin(
EncryptedFactory(
hash_point.factory,
self.key
),
plain[8 + i * HashPoint.HASH_LENGTH: 8 + (i + 1) * HashPoint.HASH_LENGTH],
resolver
).hash_point() for i, hash_point in enumerate(hashpoints)
)
return Encrypted.construct(
self.key,
resolution,
hashpoints,
decrypted
EncryptedFactory(hash_point.factory, self.key),
plain[8 + i * HashPoint.HASH_LENGTH : 8 + (i + 1) * HashPoint.HASH_LENGTH],
resolver,
).hash_point()
for i, hash_point in enumerate(hashpoints)
)
return Encrypted.construct(self.key, resolution, hashpoints, decrypted)
class EncryptedResolver(HashResolver):
@ -156,7 +135,7 @@ class EncryptedResolver(HashResolver):
self.mapping = mapping
self.key = key
async def resolve(self, point: bytes) -> tuple[bytes, 'HashResolver']:
async def resolve(self, point: bytes) -> tuple[bytes, HashResolver]:
assert isinstance(point, bytes)
encrypted: Encrypted = await self.mapping[point].resolve()
assert isinstance(encrypted, Encrypted)
@ -182,10 +161,7 @@ class ShortcutOrigin(Origin[Encrypted[EncryptedType]], Generic[EncryptedType]):
return encrypted
def hash_point(self) -> HashPoint[Encrypted[EncryptedType]]:
return HashPoint(
self.hashpoint.point,
self
)
return HashPoint(self.hashpoint.point, self)
class ShortcutResolver(HashResolver):
@ -195,11 +171,8 @@ class ShortcutResolver(HashResolver):
hash_point.point: hash_point for hash_point in encrypted.resolution
}
async def resolve(self, point: bytes) -> tuple[bytes, 'HashResolver']:
async def resolve(self, point: bytes) -> tuple[bytes, HashResolver]:
assert isinstance(point, bytes)
resolved: Encrypted = await self.mapping[point].resolve()
assert isinstance(resolved, Encrypted)
return (
HashPoint.bytes_of_mentioned(resolved),
ShortcutResolver(resolved)
)
return (HashPoint.bytes_of_mentioned(resolved), ShortcutResolver(resolved))

View File

@ -2,8 +2,6 @@
todo: deprecate
"""
__all__ = (
'ListBridge',
)
__all__ = ("ListBridge",)
from ._listbridge import ListBridge

View File

@ -3,16 +3,13 @@ from typing import Generic, TypeVar
from rainbowadn.core import *
from rainbowadn.flow.core import *
__all__ = ('ListBridge',)
__all__ = ("ListBridge",)
Element = TypeVar('Element')
Out = TypeVar('Out')
Element = TypeVar("Element")
Out = TypeVar("Out")
class ListBridge(
Reducer[Element, Out],
Generic[Element, Out]
):
class ListBridge(Reducer[Element, Out], Generic[Element, Out]):
def __init__(self, target: list[Element]):
assert isinstance(target, list)
self.target = target

View File

@ -1,12 +1,12 @@
__all__ = (
'CallableMapper',
'Composition',
'Mapper',
'MapReduce',
'MapReducer',
'PureReduce',
'Reduce',
'Reducer',
"CallableMapper",
"Composition",
"Mapper",
"MapReduce",
"MapReducer",
"PureReduce",
"Reduce",
"Reducer",
)
from ._callablemapper import CallableMapper

View File

@ -2,16 +2,13 @@ from typing import Callable, Generic, TypeVar
from ._mapper import Mapper
__all__ = ('CallableMapper',)
__all__ = ("CallableMapper",)
Element = TypeVar('Element', contravariant=True)
Mapped = TypeVar('Mapped', covariant=True)
Element = TypeVar("Element", contravariant=True)
Mapped = TypeVar("Mapped", covariant=True)
class CallableMapper(
Mapper[Element, Mapped],
Generic[Element, Mapped]
):
class CallableMapper(Mapper[Element, Mapped], Generic[Element, Mapped]):
def __init__(self, target: Callable[[Element], Mapped]):
assert callable(target)
self.target = target

View File

@ -2,17 +2,14 @@ from typing import Generic, TypeVar
from ._mapper import *
__all__ = ('Composition',)
__all__ = ("Composition",)
Element = TypeVar('Element', contravariant=True)
Middle = TypeVar('Middle')
Mapped = TypeVar('Mapped', covariant=True)
Element = TypeVar("Element", contravariant=True)
Middle = TypeVar("Middle")
Mapped = TypeVar("Mapped", covariant=True)
class Composition(
Mapper[Element, Mapped],
Generic[Element, Mapped, Middle]
):
class Composition(Mapper[Element, Mapped], Generic[Element, Mapped, Middle]):
def __init__(self, domain: Mapper[Element, Middle], codomain: Mapper[Middle, Mapped]):
assert isinstance(domain, Mapper)
assert isinstance(codomain, Mapper)

View File

@ -1,9 +1,9 @@
from typing import Any, Callable, Coroutine, Generic, TypeVar
__all__ = ('Mapper',)
__all__ = ("Mapper",)
Element = TypeVar('Element', contravariant=True)
Mapped = TypeVar('Mapped', covariant=True)
Element = TypeVar("Element", contravariant=True)
Mapped = TypeVar("Mapped", covariant=True)
class Mapper(Generic[Element, Mapped]):

View File

@ -5,11 +5,11 @@ from rainbowadn.core import *
from ._mapper import *
from ._reduce import *
__all__ = ('MapReduce',)
__all__ = ("MapReduce",)
Element = TypeVar('Element', contravariant=True)
Mapped = TypeVar('Mapped')
Out = TypeVar('Out')
Element = TypeVar("Element", contravariant=True)
Mapped = TypeVar("Mapped")
Out = TypeVar("Out")
class MapReduce(Reduce[Element, Out], Generic[Element, Out, Mapped]):
@ -24,9 +24,9 @@ class MapReduce(Reduce[Element, Out], Generic[Element, Out, Mapped]):
return await self.reduce_mapped.reducec(lambda: aidentity(out), lambda: self.mapper.map(element))
async def reducec(
self,
outc: Callable[[], Coroutine[Any, Any, Out]],
elementc: Callable[[], Coroutine[Any, Any, Element]],
self,
outc: Callable[[], Coroutine[Any, Any, Out]],
elementc: Callable[[], Coroutine[Any, Any, Element]],
) -> Out:
return await self.reduce_mapped.reducec(outc, self.mapper.bind(elementc))
@ -34,9 +34,9 @@ class MapReduce(Reduce[Element, Out], Generic[Element, Out, Mapped]):
return await self.reduce_mapped.merge(left, right)
async def mergec(
self,
leftc: Callable[[], Coroutine[Any, Any, Out]],
rightc: Callable[[], Coroutine[Any, Any, Out]],
self,
leftc: Callable[[], Coroutine[Any, Any, Out]],
rightc: Callable[[], Coroutine[Any, Any, Out]],
) -> Out:
return await self.reduce_mapped.mergec(leftc, rightc)

View File

@ -5,11 +5,11 @@ from ._mapreduce import *
from ._reduce import *
from ._reducer import *
__all__ = ('MapReducer',)
__all__ = ("MapReducer",)
Element = TypeVar('Element', contravariant=True)
Mapped = TypeVar('Mapped')
Out = TypeVar('Out')
Element = TypeVar("Element", contravariant=True)
Mapped = TypeVar("Mapped")
Out = TypeVar("Out")
class MapReducer(Reducer[Mapped, Out], Generic[Mapped, Out, Element]):

View File

@ -2,9 +2,9 @@ from typing import Generic, TypeVar
from ._reduce import *
__all__ = ('PureReduce',)
__all__ = ("PureReduce",)
Pure = TypeVar('Pure')
Pure = TypeVar("Pure")
class PureReduce(Reduce[Pure, Pure], Generic[Pure]):

View File

@ -2,10 +2,10 @@ from typing import Any, Callable, Coroutine, Generic, TypeVar
from rainbowadn.core import *
__all__ = ('Reduce',)
__all__ = ("Reduce",)
Element = TypeVar('Element', contravariant=True)
Out = TypeVar('Out')
Element = TypeVar("Element", contravariant=True)
Out = TypeVar("Out")
class Reduce(Generic[Element, Out]):
@ -16,9 +16,9 @@ class Reduce(Generic[Element, Out]):
raise NotImplementedError
async def reducec(
self,
out2: Callable[[], Coroutine[Any, Any, Out]],
element2: Callable[[], Coroutine[Any, Any, Element]],
self,
out2: Callable[[], Coroutine[Any, Any, Out]],
element2: Callable[[], Coroutine[Any, Any, Element]],
) -> Out:
out, element = await gather(out2(), element2())
return await self.reduce(out, element)
@ -27,9 +27,9 @@ class Reduce(Generic[Element, Out]):
raise NotImplementedError
async def mergec(
self,
leftc: Callable[[], Coroutine[Any, Any, Out]],
rightc: Callable[[], Coroutine[Any, Any, Out]],
self,
leftc: Callable[[], Coroutine[Any, Any, Out]],
rightc: Callable[[], Coroutine[Any, Any, Out]],
) -> Out:
left, right = await gather(leftc(), rightc())
return await self.merge(left, right)

View File

@ -2,10 +2,10 @@ from typing import Generic, TypeVar
from ._reduce import *
__all__ = ('Reducer',)
__all__ = ("Reducer",)
Element = TypeVar('Element', contravariant=True)
Out = TypeVar('Out')
Element = TypeVar("Element", contravariant=True)
Out = TypeVar("Out")
class Reducer(Generic[Element, Out]):

View File

@ -1,6 +1,6 @@
__all__ = (
'ConstMapper',
'UnitReducer',
"ConstMapper",
"UnitReducer",
)
from ._constmapper import ConstMapper

View File

@ -2,10 +2,10 @@ from typing import Generic, TypeVar
from rainbowadn.flow.core import *
__all__ = ('ConstMapper',)
__all__ = ("ConstMapper",)
Element = TypeVar('Element', contravariant=True)
Mapped = TypeVar('Mapped', covariant=True)
Element = TypeVar("Element", contravariant=True)
Mapped = TypeVar("Mapped", covariant=True)
class ConstMapper(Mapper[Element, Mapped], Generic[Element, Mapped]):

View File

@ -2,16 +2,13 @@ from typing import Generic, TypeVar
from rainbowadn.flow.core import *
__all__ = ('UnitReducer',)
__all__ = ("UnitReducer",)
Element = TypeVar('Element', contravariant=True)
Out = TypeVar('Out')
Element = TypeVar("Element", contravariant=True)
Out = TypeVar("Out")
class UnitReducer(
Reducer[Element, Out],
Generic[Element, Out]
):
class UnitReducer(Reducer[Element, Out], Generic[Element, Out]):
def __init__(self, element: Element):
self.element = element

View File

@ -1,9 +1,9 @@
__all__ = (
'CompositionVerification',
'MapperVerification',
'ReduceVerification',
'Verification',
'VerifyReduce',
"CompositionVerification",
"MapperVerification",
"ReduceVerification",
"Verification",
"VerifyReduce",
)
from ._compositionverification import CompositionVerification

View File

@ -5,16 +5,13 @@ from rainbowadn.flow.core import *
from ._verification import *
__all__ = ('CompositionVerification',)
__all__ = ("CompositionVerification",)
Verified = TypeVar('Verified', contravariant=True)
Middle = TypeVar('Middle')
Verified = TypeVar("Verified", contravariant=True)
Middle = TypeVar("Middle")
class CompositionVerification(
Verification[Verified],
Generic[Verified, Middle]
):
class CompositionVerification(Verification[Verified], Generic[Verified, Middle]):
def __init__(self, domain: Mapper[Verified, Middle], codomain: Verification[Middle]):
assert isinstance(domain, Mapper)
assert isinstance(codomain, Verification)

View File

@ -4,9 +4,9 @@ from rainbowadn.flow.core import *
from ._verification import *
__all__ = ('MapperVerification',)
__all__ = ("MapperVerification",)
Verified = TypeVar('Verified', contravariant=True)
Verified = TypeVar("Verified", contravariant=True)
class MapperVerification(Verification[Verified], Generic[Verified]):

View File

@ -6,19 +6,16 @@ from rainbowadn.flow.core import *
from ._verification import *
from ._verifyreduce import *
__all__ = ('ReduceVerification',)
__all__ = ("ReduceVerification",)
Verified = TypeVar('Verified', contravariant=True)
Verified = TypeVar("Verified", covariant=True)
class ReduceVerification(
Verification[Reducer[Verified, bool]],
Generic[Verified],
):
def __init__(
self,
verification: Verification[Verified]
):
def __init__(self, verification: Verification[Verified]):
assert isinstance(verification, Mapper)
self.verification = verification

View File

@ -3,15 +3,12 @@ from typing import Generic, TypeVar
from rainbowadn.core import *
from rainbowadn.flow.core import *
__all__ = ('Verification',)
__all__ = ("Verification",)
Verified = TypeVar('Verified', contravariant=True)
Verified = TypeVar("Verified", contravariant=True)
class Verification(
Mapper[Verified, bool],
Generic[Verified]
):
class Verification(Mapper[Verified, bool], Generic[Verified]):
async def map(self, element: Verified) -> bool:
assert_true(await self.verify(element))
return True

View File

@ -1,7 +1,7 @@
from rainbowadn.core import *
from rainbowadn.flow.core import *
__all__ = ('VerifyReduce',)
__all__ = ("VerifyReduce",)
class VerifyReduce(PureReduce[bool]):

View File

@ -5,21 +5,21 @@ from rainbowadn.flow.core import *
from rainbowadn.flow.verification.core import *
from rainbowadn.nullability import *
__all__ = ('StateVerification', 'SVF',)
__all__ = (
"StateVerification",
"SVF",
)
Header = TypeVar('Header')
State = TypeVar('State')
Link = TypeVar('Link')
Header = TypeVar("Header")
State = TypeVar("State")
Link = TypeVar("Link")
class StateVerification(
Verification[tuple[Nullable[Link], Link]],
Generic[Header, State, Link]
):
class StateVerification(Verification[tuple[Nullable[Link], Link]], Generic[Header, State, Link]):
def __init__(
self,
mapper: Mapper[Link, tuple[Header, State]],
verification: Verification[tuple[Nullable[State], Header, State]],
self,
mapper: Mapper[Link, tuple[Header, State]],
verification: Verification[tuple[Nullable[State], Header, State]],
):
assert isinstance(mapper, Mapper)
assert isinstance(verification, Mapper)

View File

@ -1,10 +1,15 @@
__all__ = (
'BankBlock',
'FlowBlock', 'FlowBlockFactory', 'FlowBlockVerification',
'FlowCheque',
'FlowIterate',
'FlowStandard',
'FlowCoinData', 'FlowCoin', 'FlowTransactionData', 'FlowTransaction',
"BankBlock",
"FlowBlock",
"FlowBlockFactory",
"FlowBlockVerification",
"FlowCheque",
"FlowIterate",
"FlowStandard",
"FlowCoinData",
"FlowCoin",
"FlowTransactionData",
"FlowTransaction",
)
from ._bankblock import BankBlock
@ -12,7 +17,4 @@ from ._flowblock import FlowBlock, FlowBlockFactory, FlowBlockVerification
from ._flowcheque import FlowCheque
from ._flowiterate import FlowIterate
from ._flowstandard import FlowStandard
from ._flowtransaction import (
FlowCoin, FlowCoinData, FlowTransaction,
FlowTransactionData
)
from ._flowtransaction import FlowCoin, FlowCoinData, FlowTransaction, FlowTransactionData

View File

@ -12,7 +12,7 @@ from ._flowblock import *
from ._flowcheque import *
from ._flowstandard import *
__all__ = ('BankBlock',)
__all__ = ("BankBlock",)
Link: TypeAlias = IPair[FlowCheque, FlowBank]
Block: TypeAlias = FlowBlock[Link]
@ -25,7 +25,7 @@ class BankBlock:
self.reference = reference
@classmethod
def flow(cls) -> 'BankFlow':
def flow(cls) -> "BankFlow":
return BankFlow(FlowBank.empty())
@classmethod
@ -33,13 +33,8 @@ class BankBlock:
return IPair.f(FlowCheque.factory(), FlowBank.factory())
@classmethod
def empty(cls) -> 'BankBlock':
return cls(
NullableReference(
Null(),
FlowBlockFactory(cls.link_factory()).loose()
)
)
def empty(cls) -> "BankBlock":
return cls(NullableReference(Null(), FlowBlockFactory(cls.link_factory()).loose()))
@classmethod
def verification(cls) -> Verification[Index]:
@ -50,14 +45,12 @@ class BankBlock:
assert_true(await self.verification().verify(await FlowBlock.outer_of(self.link_factory(), self.reference)))
return True
async def add(self, cheque: FlowCheque) -> 'BankBlock':
async def add(self, cheque: FlowCheque) -> "BankBlock":
assert isinstance(cheque, FlowCheque)
return await AddCheque(cheque).map(self)
class AddCheque(
Mapper[BankBlock, BankBlock]
):
class AddCheque(Mapper[BankBlock, BankBlock]):
def __init__(self, cheque: FlowCheque):
assert isinstance(cheque, FlowCheque)
self.cheque = cheque
@ -65,7 +58,7 @@ class AddCheque(
@classmethod
async def _bank_for_link(cls, link: Nullable[Link]) -> Nullable[FlowBank]:
assert isinstance(link, Nullable)
return Null() if link.null() else NotNull(await (link.resolve()).e1.resolve())
return Null() if link.null() else NotNull(await link.resolve().e1.resolve())
async def _next_bank_for_bank(self, bank: Nullable[FlowBank]) -> FlowBank:
return await BankBlock.flow().add(bank, self.cheque)
@ -74,38 +67,32 @@ class AddCheque(
assert isinstance(bank, FlowBank)
return HashPoint.of(IPair.of(self.cheque, bank))
async def _next_link_for_link(
self, link: Nullable[Link]
) -> HashPoint[Link]:
async def _next_link_for_link(self, link: Nullable[Link]) -> HashPoint[Link]:
assert isinstance(link, Nullable)
return await self._link_for_bank(
await self._next_bank_for_bank(
await self._bank_for_link(link)
)
)
return await self._link_for_bank(await self._next_bank_for_bank(await self._bank_for_link(link)))
@classmethod
async def _add_link_to_reference(
cls,
link: HashPoint[Link],
reference: NullableReference[Block],
cls,
link: HashPoint[Link],
reference: NullableReference[Block],
) -> BankBlock:
assert isinstance(link, HashPoint)
assert isinstance(reference, NullableReference)
return BankBlock(NullableReference.off(await FlowBlock.add_to(reference, link)))
async def _add_to_link(
self,
previous: Nullable[Link],
reference: NullableReference[Block],
self,
previous: Nullable[Link],
reference: NullableReference[Block],
) -> BankBlock:
assert isinstance(previous, Nullable)
assert isinstance(reference, NullableReference)
return await self._add_link_to_reference(await self._next_link_for_link(previous), reference)
async def _add_to_reference(
self,
reference: NullableReference[Block],
self,
reference: NullableReference[Block],
) -> BankBlock:
assert isinstance(reference, NullableReference)
return await self._add_to_link(await FlowBlock.link_of(reference), reference)

View File

@ -15,15 +15,13 @@ from ._flowstandard import *
from ._flowtransaction import *
from ._flowunion import *
__all__ = ('BankFlow',)
__all__ = ("BankFlow",)
Link: TypeAlias = IPair[FlowCheque, FlowBank]
class BankFlow(
Verification[
tuple[Nullable[FlowBank], FlowCheque, FlowBank]
],
Verification[tuple[Nullable[FlowBank], FlowCheque, FlowBank]],
):
def __init__(self, initial: FlowBank):
assert isinstance(initial, FlowBank)
@ -31,10 +29,10 @@ class BankFlow(
@classmethod
async def _verify_disjoint_union(
cls,
per_previous: FlowStandard[FlowCoin],
per_cheque: FlowStandard[FlowCoin],
per_bank: FlowStandard[FlowCoin],
cls,
per_previous: FlowStandard[FlowCoin],
per_cheque: FlowStandard[FlowCoin],
per_bank: FlowStandard[FlowCoin],
) -> bool:
assert isinstance(per_previous, FlowStandard)
assert isinstance(per_cheque, FlowStandard)
@ -57,10 +55,10 @@ class BankFlow(
@classmethod
async def _verify(
cls,
previous: FlowBank,
cheque: FlowCheque,
bank: FlowBank,
cls,
previous: FlowBank,
cheque: FlowCheque,
bank: FlowBank,
) -> bool:
assert isinstance(previous, FlowBank)
assert isinstance(cheque, FlowCheque)
@ -87,9 +85,7 @@ class BankFlow(
return True
async def verify_used_were_minted():
assert_true(
await cheque.used.verify_subset(UnitReducer(bank.minted))
)
assert_true(await cheque.used.verify_subset(UnitReducer(bank.minted)))
return True
assert_trues(
@ -102,10 +98,7 @@ class BankFlow(
)
return True
async def verify(
self,
element: tuple[Nullable[FlowBank], FlowCheque, FlowBank]
) -> bool:
async def verify(self, element: tuple[Nullable[FlowBank], FlowCheque, FlowBank]) -> bool:
assert isinstance(element, tuple)
previous: Nullable[FlowBank]
cheque: FlowCheque
@ -140,9 +133,7 @@ class BankFlow(
)
return FlowBank(minted, used)
def link_verification(self) -> Verification[
tuple[Nullable[HashPoint[Link]], HashPoint[Link]]
]:
def link_verification(self) -> Verification[tuple[Nullable[HashPoint[Link]], HashPoint[Link]]]:
class Decomposition(Mapper[HashPoint[Link], tuple[FlowCheque, FlowBank]]):
async def map(self, element: HashPoint[Link]) -> tuple[FlowCheque, FlowBank]:
assert isinstance(element, HashPoint)
@ -159,12 +150,7 @@ class BankFlow(
return cheque, bank
svf: SVF[FlowCheque, FlowBank, HashPoint[Link]] = SVF()
return svf.make(
Decomposition(),
self.loose()
)
return svf.make(Decomposition(), self.loose())
def loose(self) -> Verification[
tuple[Nullable[FlowBank], FlowCheque, FlowBank]
]:
def loose(self) -> Verification[tuple[Nullable[FlowBank], FlowCheque, FlowBank]]:
return self

View File

@ -7,21 +7,22 @@ from rainbowadn.collection.trees.binary.core import BinaryProtocolized
from rainbowadn.core import *
from rainbowadn.flow.core import *
__all__ = ('BinaryReducer', 'VerifySubsetAction', 'CheckResult',)
__all__ = (
"BinaryReducer",
"VerifySubsetAction",
"CheckResult",
)
KeyT = TypeVar('KeyT', bound=Mentionable)
MetadataT = TypeVar('MetadataT', bound=Mentionable)
TreeT = TypeVar('TreeT')
Out = TypeVar('Out')
KeyT = TypeVar("KeyT", bound=Mentionable)
MetadataT = TypeVar("MetadataT", bound=Mentionable)
TreeT = TypeVar("TreeT")
Out = TypeVar("Out")
BP: TypeAlias = BinaryProtocolized[KeyT, MetadataT, TreeT]
PBS: TypeAlias = ProtocolizedBinarySplit[KeyT, MetadataT, TreeT]
class BinaryReducer(
Reducer[HashPoint[KeyT], Out],
Generic[Out, KeyT, MetadataT, TreeT]
):
class BinaryReducer(Reducer[HashPoint[KeyT], Out], Generic[Out, KeyT, MetadataT, TreeT]):
def __init__(self, protocolized: BP):
assert isinstance(protocolized, BinaryProtocolized)
self.protocolized = protocolized
@ -182,14 +183,12 @@ class VerifySubsetAction(
)
return True
case NotFound():
raise ValueError('subset check failed')
raise ValueError("subset check failed")
case _:
raise TypeError
class VerifySubsetReduce(
PureReduce[CheckResult]
):
class VerifySubsetReduce(PureReduce[CheckResult]):
def pure(self, left: CheckResult, right: CheckResult) -> CheckResult:
return max(left, right)

View File

@ -1,3 +1,5 @@
from __future__ import annotations
from typing import Iterable
from rainbowadn.collection.comparison import *
@ -6,18 +8,18 @@ from rainbowadn.core import *
from ._flowstandard import *
from ._flowtransaction import *
__all__ = ('FlowBank',)
__all__ = ("FlowBank",)
class FlowBank(StaticMentionable, RecursiveMentionable):
@classmethod
def from_bytes(cls, source: bytes, resolver: HashResolver) -> 'FlowBank':
def from_bytes(cls, source: bytes, resolver: HashResolver) -> FlowBank:
return FlowBank(
FlowStandardFactory.of(FlowCoin.factory(), HashComparator(Fail())).from_bytes(
source[:HashPoint.HASH_LENGTH], resolver
source[: HashPoint.HASH_LENGTH], resolver
),
FlowStandardFactory.of(FlowCoin.factory(), HashComparator(Fail())).from_bytes(
source[HashPoint.HASH_LENGTH:], resolver
source[HashPoint.HASH_LENGTH :], resolver
),
)
@ -28,9 +30,9 @@ class FlowBank(StaticMentionable, RecursiveMentionable):
return bytes(self.minted) + bytes(self.used)
def __init__(
self,
minted: FlowStandard[FlowCoin],
used: FlowStandard[FlowCoin],
self,
minted: FlowStandard[FlowCoin],
used: FlowStandard[FlowCoin],
):
assert isinstance(minted, FlowStandard)
assert isinstance(used, FlowStandard)
@ -38,7 +40,7 @@ class FlowBank(StaticMentionable, RecursiveMentionable):
self.used = used
@classmethod
def empty(cls) -> 'FlowBank':
def empty(cls) -> FlowBank:
return FlowBank(
FlowStandardFactory.empty(FlowCoin.factory(), HashComparator(Fail())),
FlowStandardFactory.empty(FlowCoin.factory(), HashComparator(Fail())),
@ -46,8 +48,10 @@ class FlowBank(StaticMentionable, RecursiveMentionable):
async def str(self, tab: int) -> str:
assert isinstance(tab, int)
return f'(' \
f'{tabulate(tab + 1)}bank' \
f'{tabulate(tab + 1)}(minted)' \
f'{tabulate(tab + 1)}(used)' \
f'{tabulate(tab)})'
return (
f"("
f"{tabulate(tab + 1)}bank"
f"{tabulate(tab + 1)}(minted)"
f"{tabulate(tab + 1)}(used)"
f"{tabulate(tab)})"
)

View File

@ -1,4 +1,6 @@
from typing import Callable, Generic, Iterable, TypeAlias, TypeVar
from __future__ import annotations
from typing import Generic, Iterable, TypeAlias, TypeVar
from rainbowadn.collection.comparison import *
from rainbowadn.core import *
@ -7,9 +9,14 @@ from rainbowadn.nullability import *
from ._flowstandard import *
__all__ = ('FlowBlock', 'FlowBlockFactory', 'FlowBlockVerification', 'FBVF',)
__all__ = (
"FlowBlock",
"FlowBlockFactory",
"FlowBlockVerification",
"FBVF",
)
LinkT = TypeVar('LinkT', bound=Mentionable)
LinkT = TypeVar("LinkT", bound=Mentionable)
class FlowBlock(Generic[LinkT], RecursiveMentionable):
@ -19,14 +26,14 @@ class FlowBlock(Generic[LinkT], RecursiveMentionable):
def __bytes__(self):
return bytes(self.previous) + bytes(self.index) + bytes(self.link)
def __factory__(self) -> RainbowFactory['FBL']:
def __factory__(self) -> RainbowFactory[FBL]:
return FlowBlockFactory(self.link.factory)
def __init__(
self,
previous: NullableReference['FBL'],
index: 'Index',
link: HashPoint[LinkT],
self,
previous: NullableReference[FBL],
index: Index,
link: HashPoint[LinkT],
):
assert isinstance(previous, NullableReference)
assert isinstance(index, FlowStandard)
@ -34,95 +41,73 @@ class FlowBlock(Generic[LinkT], RecursiveMentionable):
self.index = index
self.link = link
async def outer(self) -> 'Index':
return FlowStandard(
(
await self.index.protocolized.tree.add(
HashPoint.of(self)
)
).protocolized()
)
async def outer(self) -> Index:
return FlowStandard((await self.index.protocolized.tree.add(HashPoint.of(self))).protocolized())
async def verify_outer_matches(self, index: 'Index') -> bool:
async def verify_outer_matches(self, index: Index) -> bool:
assert_eq(await self.outer(), index)
return True
@classmethod
async def outer_of(cls, factory: RainbowFactory[LinkT], reference: NullableReference['FBL']) -> 'Index':
async def outer_of(cls, factory: RainbowFactory[LinkT], reference: NullableReference[FBL]) -> Index:
if reference.null():
return FlowStandardFactory.empty(FlowBlockFactory(factory), HashComparator(Fail()))
else:
return await (await reference.resolve()).outer()
@classmethod
async def link_of(cls, reference: NullableReference['FBL']) -> Nullable[LinkT]:
async def link_of(cls, reference: NullableReference[FBL]) -> Nullable[LinkT]:
if reference.null():
return Null()
else:
return NotNull(await (await reference.resolve()).link.resolve())
async def add(self, link: HashPoint[LinkT]) -> 'FBL':
return FlowBlock(
NullableReference.off(self),
await self.outer(),
link
)
async def add(self, link: HashPoint[LinkT]) -> FBL:
return FlowBlock(NullableReference.off(self), await self.outer(), link)
@classmethod
async def add_to(cls, reference: NullableReference['FBL'], link: HashPoint[LinkT]) -> 'FBL':
return FlowBlock(
reference,
await cls.outer_of(link.factory, reference),
link
)
async def add_to(cls, reference: NullableReference[FBL], link: HashPoint[LinkT]) -> FBL:
return FlowBlock(reference, await cls.outer_of(link.factory, reference), link)
async def str(self, tab: int) -> str:
assert isinstance(tab, int)
previous_str: str
link_str: str
previous_str, link_str = await gather(
self.previous.str(tab),
hash_point_format(self.link, tab)
)
previous_str, link_str = await gather(self.previous.str(tab), hash_point_format(self.link, tab))
assert isinstance(previous_str, str)
assert isinstance(link_str, str)
return f'{previous_str}' \
f'{tabulate(tab)}(index)' \
f'{tabulate(tab)}{link_str}'
return f"{previous_str}" f"{tabulate(tab)}(index)" f"{tabulate(tab)}{link_str}"
class FlowBlockFactory(RainbowFactory['FBL'], Generic[LinkT]):
class FlowBlockFactory(RainbowFactory["FBL"], Generic[LinkT]):
def __init__(self, factory: RainbowFactory[LinkT]):
assert isinstance(factory, RainbowFactory)
self.factory = factory
def from_bytes(self, source: bytes, resolver: HashResolver) -> 'FBL':
def from_bytes(self, source: bytes, resolver: HashResolver) -> FBL:
assert isinstance(source, bytes)
assert isinstance(resolver, HashResolver)
return FlowBlock(
NullableReference.f(self).from_bytes(source[:HashPoint.HASH_LENGTH], resolver),
NullableReference.f(self).from_bytes(source[: HashPoint.HASH_LENGTH], resolver),
FlowStandardFactory.of(self, HashComparator(Fail())).from_bytes(
source[HashPoint.HASH_LENGTH:2 * HashPoint.HASH_LENGTH], resolver
source[HashPoint.HASH_LENGTH : 2 * HashPoint.HASH_LENGTH], resolver
),
ResolverOrigin(self.factory, source[2 * HashPoint.HASH_LENGTH:], resolver).hash_point(),
ResolverOrigin(self.factory, source[2 * HashPoint.HASH_LENGTH :], resolver).hash_point(),
)
def loose(self) -> RainbowFactory['FBL']:
def loose(self) -> RainbowFactory[FBL]:
return self
FBL: TypeAlias = 'FlowBlock[LinkT]'
FBL: TypeAlias = FlowBlock[LinkT]
Index: TypeAlias = FlowStandard[FBL]
class FlowBlockIndexedVerification(
Verification[HashPoint[FBL]],
Generic[LinkT]
):
class FlowBlockIndexedVerification(Verification[HashPoint[FBL]], Generic[LinkT]):
def __init__(
self,
index: Index,
verification: Verification[tuple[Nullable[HashPoint[LinkT]], HashPoint[LinkT]]],
self,
index: Index,
verification: Verification[tuple[Nullable[HashPoint[LinkT]], HashPoint[LinkT]]],
):
assert isinstance(index, FlowStandard)
assert isinstance(verification, Verification)
@ -133,9 +118,7 @@ class FlowBlockIndexedVerification(
assert isinstance(block, FlowBlock)
assert_trues(
await gather(
self.verification.verify(
(Null(), block.link)
),
self.verification.verify((Null(), block.link)),
block.index.verify_empty(),
)
)
@ -146,9 +129,7 @@ class FlowBlockIndexedVerification(
assert isinstance(block, FlowBlock)
assert_trues(
await gather(
self.verification.verify(
(NotNull(previous.link), block.link)
),
self.verification.verify((NotNull(previous.link), block.link)),
previous.verify_outer_matches(block.index),
)
)
@ -175,22 +156,17 @@ class FlowBlockIndexedVerification(
return self
class FlowBlockVerification(
Verification[Index],
Generic[LinkT]
):
class FlowBlockVerification(Verification[Index], Generic[LinkT]):
def __init__(
self,
verification: Verification[tuple[Nullable[HashPoint[LinkT]], HashPoint[LinkT]]],
self,
verification: Verification[tuple[Nullable[HashPoint[LinkT]], HashPoint[LinkT]]],
):
assert isinstance(verification, Verification)
self.verification = verification
async def verify(self, element: Index) -> bool:
assert_true(
await ReduceVerification(
FlowBlockIndexedVerification(element, self.verification).loose()
).verify(
await ReduceVerification(FlowBlockIndexedVerification(element, self.verification).loose()).verify(
await element.reducer()
)
)
@ -202,7 +178,6 @@ class FlowBlockVerification(
class FBVF(Generic[LinkT]):
def make(
self,
verification: Verification[tuple[Nullable[HashPoint[LinkT]], HashPoint[LinkT]]]
self, verification: Verification[tuple[Nullable[HashPoint[LinkT]], HashPoint[LinkT]]]
) -> Verification[Index]:
return FlowBlockVerification(verification)

View File

@ -1,3 +1,5 @@
from __future__ import annotations
import itertools
from typing import Iterable
@ -13,7 +15,7 @@ from ._flowstandard import *
from ._flowtransaction import *
from ._resolvemapper import *
__all__ = ('FlowCheque',)
__all__ = ("FlowCheque",)
class SumReduce(PureReduce[int]):
@ -29,23 +31,20 @@ class ValueMapper(Mapper[HashPoint[FlowCoin], int]):
class FlowCheque(StaticMentionable, RecursiveMentionable):
@classmethod
def from_bytes(cls, source: bytes, resolver: HashResolver) -> 'FlowCheque':
def from_bytes(cls, source: bytes, resolver: HashResolver) -> FlowCheque:
return FlowCheque(
FlowStandardFactory.of(FlowTransaction.factory(), HashComparator(Fail())).from_bytes(
source[:HashPoint.HASH_LENGTH], resolver
source[: HashPoint.HASH_LENGTH], resolver
),
FlowStandardFactory.of(FlowCoin.factory(), HashComparator(Fail())).from_bytes(
source[HashPoint.HASH_LENGTH:2 * HashPoint.HASH_LENGTH], resolver
source[HashPoint.HASH_LENGTH : 2 * HashPoint.HASH_LENGTH], resolver
),
FlowStandardFactory.of(FlowCoin.factory(), HashComparator(Fail())).from_bytes(
source[2 * HashPoint.HASH_LENGTH:3 * HashPoint.HASH_LENGTH], resolver
source[2 * HashPoint.HASH_LENGTH : 3 * HashPoint.HASH_LENGTH], resolver
),
FlowStandardFactory.of(
KeyValue.f(FlowCoin.factory(), FlowTransaction.factory()),
KeyedComparator(HashComparator(Fail()))
).from_bytes(
source[3 * HashPoint.HASH_LENGTH:], resolver
),
KeyValue.f(FlowCoin.factory(), FlowTransaction.factory()), KeyedComparator(HashComparator(Fail()))
).from_bytes(source[3 * HashPoint.HASH_LENGTH :], resolver),
)
def points(self) -> Iterable[HashPoint]:
@ -55,11 +54,11 @@ class FlowCheque(StaticMentionable, RecursiveMentionable):
return bytes(self.transactions) + bytes(self.minted) + bytes(self.used) + bytes(self.usedx)
def __init__(
self,
transactions: FlowStandard[FlowTransaction],
minted: FlowStandard[FlowCoin],
used: FlowStandard[FlowCoin],
usedx: FlowStandard[KeyValue[FlowCoin, FlowTransaction]],
self,
transactions: FlowStandard[FlowTransaction],
minted: FlowStandard[FlowCoin],
used: FlowStandard[FlowCoin],
usedx: FlowStandard[KeyValue[FlowCoin, FlowTransaction]],
):
assert isinstance(transactions, FlowStandard)
assert isinstance(minted, FlowStandard)
@ -108,27 +107,19 @@ class FlowCheque(StaticMentionable, RecursiveMentionable):
return True
async def _verify_transactions(self) -> bool:
assert_true(
await self.transactions.verify(TransactionVerification(self).loose())
)
assert_true(await self.transactions.verify(TransactionVerification(self).loose()))
return True
async def _verify_minted(self) -> bool:
assert_true(
await self.minted.verify(MintedVerification(self).loose())
)
assert_true(await self.minted.verify(MintedVerification(self).loose()))
return True
async def _verify_used(self) -> bool:
assert_true(
await self.used.verify(UsedVerification(self).loose())
)
assert_true(await self.used.verify(UsedVerification(self).loose()))
return True
async def _verify_usedx(self) -> bool:
assert_true(
await self.usedx.verify(UsedXVerification(self).loose())
)
assert_true(await self.usedx.verify(UsedXVerification(self).loose()))
return True
async def verify(self) -> bool:
@ -156,22 +147,14 @@ class FlowCheque(StaticMentionable, RecursiveMentionable):
@classmethod
async def _transaction_usedx(cls, transaction: FlowTransaction) -> Iterable[KeyValue[FlowCoin, FlowTransaction]]:
assert isinstance(transaction, FlowTransaction)
return (
KeyValue.of(coin, transaction)
for
coin
in
await cls._transaction_used(transaction)
)
return (KeyValue.of(coin, transaction) for coin in await cls._transaction_used(transaction))
@classmethod
async def _make_minted(cls, transactions: Iterable[FlowTransaction]) -> FlowStandard[FlowCoin]:
return await FlowStandardFactory.off(
FlowCoin.factory(),
HashComparator(Fail()),
itertools.chain(
*(await gather(*(cls._transaction_minted(transaction) for transaction in transactions)))
)
itertools.chain(*(await gather(*(cls._transaction_minted(transaction) for transaction in transactions)))),
)
@classmethod
@ -179,26 +162,21 @@ class FlowCheque(StaticMentionable, RecursiveMentionable):
return await FlowStandardFactory.off(
FlowCoin.factory(),
HashComparator(Fail()),
itertools.chain(
*(await gather(*(cls._transaction_used(transaction) for transaction in transactions)))
),
itertools.chain(*(await gather(*(cls._transaction_used(transaction) for transaction in transactions)))),
)
@classmethod
async def _make_usedx(
cls,
transactions: Iterable[FlowTransaction]
cls, transactions: Iterable[FlowTransaction]
) -> FlowStandard[KeyValue[FlowCoin, FlowTransaction]]:
return await FlowStandardFactory.off(
KeyValue.f(FlowCoin.factory(), FlowTransaction.factory()),
KeyedComparator(HashComparator(Fail())),
itertools.chain(
*(await gather(*(cls._transaction_usedx(transaction) for transaction in transactions)))
)
itertools.chain(*(await gather(*(cls._transaction_usedx(transaction) for transaction in transactions)))),
)
@classmethod
async def make(cls, transactions: Iterable[FlowTransaction]) -> 'FlowCheque':
async def make(cls, transactions: Iterable[FlowTransaction]) -> FlowCheque:
transactions_standard: FlowStandard[FlowTransaction]
minted: FlowStandard[FlowCoin]
used: FlowStandard[FlowCoin]
@ -222,13 +200,15 @@ class FlowCheque(StaticMentionable, RecursiveMentionable):
async def str(self, tab: int) -> str:
assert isinstance(tab, int)
return f'(' \
f'{tabulate(tab + 1)}cheque' \
f'{tabulate(tab + 1)}{await self.transactions.str(tab + 1)}' \
f'{tabulate(tab + 1)}(minted)' \
f'{tabulate(tab + 1)}(used)' \
f'{tabulate(tab + 1)}(usedx)' \
f'{tabulate(tab)})'
return (
f"("
f"{tabulate(tab + 1)}cheque"
f"{tabulate(tab + 1)}{await self.transactions.str(tab + 1)}"
f"{tabulate(tab + 1)}(minted)"
f"{tabulate(tab + 1)}(used)"
f"{tabulate(tab + 1)}(usedx)"
f"{tabulate(tab)})"
)
class UsedxMapper(Mapper[HashPoint[FlowCoin], HashPoint[KeyValue[FlowCoin, FlowTransaction]]]):
@ -237,53 +217,35 @@ class UsedxMapper(Mapper[HashPoint[FlowCoin], HashPoint[KeyValue[FlowCoin, FlowT
self.transaction = transaction
async def map(self, element: HashPoint[FlowCoin]) -> HashPoint[KeyValue[FlowCoin, FlowTransaction]]:
return HashPoint.of(
await KeyValue.off(
element,
self.transaction
)
)
return HashPoint.of(await KeyValue.off(element, self.transaction))
class TransactionVerification(
Verification[HashPoint[FlowTransaction]]
):
class TransactionVerification(Verification[HashPoint[FlowTransaction]]):
def __init__(self, cheque: FlowCheque):
assert isinstance(cheque, FlowCheque)
self.cheque = cheque
@classmethod
def _usedx_reducer(
cls,
reducer: Reducer[HashPoint[FlowCoin], bool],
transaction: HashPoint[FlowTransaction]
cls, reducer: Reducer[HashPoint[FlowCoin], bool], transaction: HashPoint[FlowTransaction]
) -> Reducer[HashPoint[KeyValue[FlowCoin, FlowTransaction]], bool]:
assert isinstance(reducer, Reducer)
assert isinstance(transaction, HashPoint)
usedx_reducer: Reducer[HashPoint[KeyValue[FlowCoin, FlowTransaction]], bool] = MapReducer(
UsedxMapper(transaction),
reducer
UsedxMapper(transaction), reducer
)
assert isinstance(usedx_reducer, Reducer)
return usedx_reducer
async def _verify_transaction_minted(self, transaction: FlowTransaction) -> bool:
assert isinstance(transaction, FlowTransaction)
assert_true(
await self.cheque.minted.verify_contains_all(
await transaction.minted_reducer()
)
)
assert_true(await self.cheque.minted.verify_contains_all(await transaction.minted_reducer()))
return True
async def _verify_transaction_used(self, transaction: FlowTransaction) -> bool:
assert isinstance(transaction, FlowTransaction)
assert_true(
await self.cheque.used.verify_contains_all(
await transaction.used_reducer()
)
)
assert_true(await self.cheque.used.verify_contains_all(await transaction.used_reducer()))
return True
async def _verify_transaction_usedx(self, transaction: FlowTransaction) -> bool:
@ -313,30 +275,21 @@ class TransactionVerification(
return self
class MintedVerification(
Verification[HashPoint[FlowCoin]]
):
class MintedVerification(Verification[HashPoint[FlowCoin]]):
def __init__(self, cheque: FlowCheque):
assert isinstance(cheque, FlowCheque)
self.cheque = cheque
async def verify(self, element: HashPoint[FlowCoin]) -> bool:
assert isinstance(element, HashPoint)
assert_true(
await self.cheque.transactions.contains(
(await element.resolve()).transaction,
exact=True
)
)
assert_true(await self.cheque.transactions.contains((await element.resolve()).transaction, exact=True))
return True
def loose(self) -> Verification[HashPoint[FlowCoin]]:
return self
class UsedVerification(
Verification[HashPoint[FlowCoin]]
):
class UsedVerification(Verification[HashPoint[FlowCoin]]):
def __init__(self, cheque: FlowCheque):
assert isinstance(cheque, FlowCheque)
self.cheque = cheque
@ -345,8 +298,7 @@ class UsedVerification(
assert isinstance(element, HashPoint)
assert_true(
await self.cheque.usedx.contains(
HashPoint.of(await KeyValue.off(element, HashPoint.of(FlowTransaction.empty()))),
exact=False
HashPoint.of(await KeyValue.off(element, HashPoint.of(FlowTransaction.empty()))), exact=False
)
)
return True
@ -355,45 +307,28 @@ class UsedVerification(
return self
class UsedXVerification(
Verification[HashPoint[KeyValue[FlowCoin, FlowTransaction]]]
):
class UsedXVerification(Verification[HashPoint[KeyValue[FlowCoin, FlowTransaction]]]):
def __init__(self, cheque: FlowCheque):
assert isinstance(cheque, FlowCheque)
self.cheque = cheque
async def _verify_transaction_registred(self, transaction: HashPoint[FlowTransaction]) -> bool:
assert isinstance(transaction, HashPoint)
assert_true(
await self.cheque.transactions.contains(
transaction,
exact=True
)
)
assert_true(await self.cheque.transactions.contains(transaction, exact=True))
return True
@classmethod
async def _verify_coin_contained_in_transaction(
cls, transaction: HashPoint[FlowTransaction], coin: HashPoint[FlowCoin]
cls, transaction: HashPoint[FlowTransaction], coin: HashPoint[FlowCoin]
) -> bool:
assert isinstance(transaction, HashPoint)
assert isinstance(coin, HashPoint)
assert_true(
await (await transaction.resolve()).data.in_coins.contains(
coin,
exact=True
)
)
assert_true(await (await transaction.resolve()).data.in_coins.contains(coin, exact=True))
return True
async def _verify_coin_registred_as_used(self, coin: HashPoint[FlowCoin]) -> bool:
assert isinstance(coin, HashPoint)
assert_true(
await self.cheque.used.contains(
coin,
exact=True
)
)
assert_true(await self.cheque.used.contains(coin, exact=True))
return True
async def _verify(self, pair: KeyValue[FlowCoin, FlowTransaction]):

View File

@ -2,15 +2,12 @@ from typing import Generic, Iterable, TypeVar
from rainbowadn.flow.core import *
__all__ = ('FlowIterate',)
__all__ = ("FlowIterate",)
Element = TypeVar('Element')
Element = TypeVar("Element")
class FlowIterate(
Reduce[Element, Iterable[Element]],
Generic[Element]
):
class FlowIterate(Reduce[Element, Iterable[Element]], Generic[Element]):
def __init__(self):
super().__init__(())
@ -32,8 +29,5 @@ class FlowIterate(
return self
@classmethod
async def iterate(
cls,
reducer: Reducer[Element, Iterable[Element]]
) -> Iterable[Element]:
async def iterate(cls, reducer: Reducer[Element, Iterable[Element]]) -> Iterable[Element]:
return await reducer.reduce(cls())

View File

@ -1,3 +1,5 @@
from __future__ import annotations
from typing import Any, Generic, Iterable, Optional, TypeAlias, TypeVar
from rainbowadn.atomic import *
@ -15,29 +17,25 @@ from rainbowadn.nullability import *
from ._binaryflow import *
from ._flowtree import *
__all__ = ('FlowStandard', 'FlowStandardFactory',)
__all__ = (
"FlowStandard",
"FlowStandardFactory",
)
KeyT = TypeVar('KeyT', bound=Mentionable)
ABT: TypeAlias = 'ActiveBinaryTree[KeyT, Integer]'
BP: TypeAlias = 'BinaryProtocolized[KeyT, Integer, ABT]'
KeyT = TypeVar("KeyT", bound=Mentionable)
ABT: TypeAlias = "ActiveBinaryTree[KeyT, Integer]"
BP: TypeAlias = "BinaryProtocolized[KeyT, Integer, ABT]"
class FlowStandard(
RecursiveMentionable,
FlowTree[HashPoint[KeyT], 'FS'],
Generic[KeyT]
):
class FlowStandard(RecursiveMentionable, FlowTree[HashPoint[KeyT], "FS"], Generic[KeyT]):
def points(self) -> Iterable[HashPoint]:
return self.protocolized.tree.reference.points()
def __bytes__(self):
return bytes(self.protocolized.tree.reference)
def __factory__(self) -> RainbowFactory['FlowStandard[KeyT]']:
return FlowStandardFactory(
self.protocolized.tree.reference.factory,
self.protocolized.creation.comparator
)
def __factory__(self) -> RainbowFactory[FlowStandard[KeyT]]:
return FlowStandardFactory(self.protocolized.tree.reference.factory, self.protocolized.creation.comparator)
def __init__(self, protocolized: BP):
assert isinstance(protocolized, BinaryProtocolized)
@ -46,27 +44,21 @@ class FlowStandard(
async def contains(self, key: HashPoint[KeyT], *, exact: bool) -> bool:
return await self.protocolized.tree.contains(key, exact=exact)
def _protocolized(self: 'FS') -> BP:
def _protocolized(self: FS) -> BP:
return self.protocolized
@classmethod
def _protocolized_mapper(cls) -> Mapper['FS', BP]:
def _protocolized_mapper(cls) -> Mapper[FS, BP]:
return CallableMapper(FlowStandard._protocolized)
async def verify_subset(self, trees: Reducer['FS', CheckResult]) -> bool:
async def verify_subset(self, trees: Reducer[FS, CheckResult]) -> bool:
assert isinstance(trees, Reducer)
reducer: Reducer[BP, CheckResult] = MapReducer(self._protocolized_mapper(), trees)
assert_true(await VerifySubsetAction(reducer).on(self.protocolized))
return True
async def verify_empty(self) -> bool:
assert_true(
await ReduceVerification(
MapperVerification(ConstMapper(False))
).verify(
await self.reducer()
)
)
assert_true(await ReduceVerification(MapperVerification(ConstMapper(False))).verify(await self.reducer()))
return True
async def reducer(self) -> Reducer[HashPoint[KeyT], Any]:
@ -83,37 +75,30 @@ class FlowStandard(
return await self.protocolized.tree.reference.str(tab)
FS: TypeAlias = 'FlowStandard[KeyT]'
FS: TypeAlias = "FlowStandard[KeyT]"
class FlowStandardFactory(Inlining[FlowStandard[KeyT]], Generic[KeyT]):
def __init__(
self,
factory: RainbowFactory[BinaryTree[KeyMetadata[KeyT, Integer]]],
comparator: Comparator[KeyT]
):
def __init__(self, factory: RainbowFactory[BinaryTree[KeyMetadata[KeyT, Integer]]], comparator: Comparator[KeyT]):
assert isinstance(factory, RainbowFactory)
assert isinstance(comparator, Comparator)
self.factory: RainbowFactory[
NullableReference[BinaryTree[KeyMetadata[KeyT, Integer]]]
] = NullableReference.f(factory)
self.factory: RainbowFactory[NullableReference[BinaryTree[KeyMetadata[KeyT, Integer]]]] = NullableReference.f(
factory
)
self.comparator = comparator
def size(self) -> Optional[int]:
return Inlining.factory_size(self.factory)
@classmethod
def of(cls, factory: RainbowFactory[KeyT], comparator: Comparator[KeyT]) -> 'FlowStandardFactory[KeyT]':
def of(cls, factory: RainbowFactory[KeyT], comparator: Comparator[KeyT]) -> FlowStandardFactory[KeyT]:
assert isinstance(factory, RainbowFactory)
return FlowStandardFactory(
BinaryTreeFactory(KeyMetadataFactory(factory, Integer.factory())),
comparator
)
return FlowStandardFactory(BinaryTreeFactory(KeyMetadataFactory(factory, Integer.factory())), comparator)
@classmethod
async def off(
cls, factory: RainbowFactory[KeyT], comparator: Comparator[KeyT], keys: Iterable[KeyT]
) -> 'FlowStandard[KeyT]':
cls, factory: RainbowFactory[KeyT], comparator: Comparator[KeyT], keys: Iterable[KeyT]
) -> FlowStandard[KeyT]:
assert isinstance(factory, RainbowFactory)
abt: ActiveBinaryTree[KeyT, Integer] = cls.empty(factory, comparator).protocolized.tree
for key in keys:
@ -125,18 +110,13 @@ class FlowStandardFactory(Inlining[FlowStandard[KeyT]], Generic[KeyT]):
return AVL(comparator)
@classmethod
def empty(cls, factory: RainbowFactory[KeyT], comparator: Comparator[KeyT]) -> 'FlowStandard[KeyT]':
def empty(cls, factory: RainbowFactory[KeyT], comparator: Comparator[KeyT]) -> FlowStandard[KeyT]:
assert isinstance(factory, RainbowFactory)
return FlowStandard(
ActiveBinaryTree.empty(cls.protocol(comparator), factory).protocolized()
)
return FlowStandard(ActiveBinaryTree.empty(cls.protocol(comparator), factory).protocolized())
def from_bytes(self, source: bytes, resolver: HashResolver) -> FlowStandard[KeyT]:
assert isinstance(source, bytes)
assert isinstance(resolver, HashResolver)
return FlowStandard(
ActiveBinaryTree(
self.protocol(self.comparator),
self.factory.from_bytes(source, resolver)
).protocolized()
ActiveBinaryTree(self.protocol(self.comparator), self.factory.from_bytes(source, resolver)).protocolized()
)

View File

@ -1,3 +1,5 @@
from __future__ import annotations
from typing import Any, Iterable
from nacl.signing import SigningKey
@ -13,15 +15,16 @@ from rainbowadn.v13 import *
from ._flowstandard import *
from ._resolvemapper import *
__all__ = ('FlowCoinData', 'FlowCoin', 'FlowTransactionData', 'FlowTransaction',)
__all__ = (
"FlowCoinData",
"FlowCoin",
"FlowTransactionData",
"FlowTransaction",
)
class FlowCoinData(RecursiveMentionable, StaticMentionable):
def __init__(
self,
owner: Subject,
value: HashPoint[Integer]
):
def __init__(self, owner: Subject, value: HashPoint[Integer]):
assert isinstance(owner, Subject)
assert isinstance(value, HashPoint)
self.owner = owner
@ -35,7 +38,7 @@ class FlowCoinData(RecursiveMentionable, StaticMentionable):
return (await self.value.resolve()).integer
@classmethod
def of(cls, owner: Subject, value: int) -> 'FlowCoinData':
def of(cls, owner: Subject, value: int) -> FlowCoinData:
assert isinstance(owner, Subject)
assert isinstance(value, int)
return cls(owner, HashPoint.of(Integer(value)))
@ -47,7 +50,7 @@ class FlowCoinData(RecursiveMentionable, StaticMentionable):
return bytes(self.owner) + bytes(self.value)
@classmethod
def from_bytes(cls, source: bytes, resolver: HashResolver) -> 'FlowCoinData':
def from_bytes(cls, source: bytes, resolver: HashResolver) -> FlowCoinData:
assert isinstance(source, bytes)
assert isinstance(resolver, HashResolver)
separation = Subject.size()
@ -58,16 +61,11 @@ class FlowCoinData(RecursiveMentionable, StaticMentionable):
async def str(self, tab: int) -> str:
assert isinstance(tab, int)
return f'{self.owner}' \
f'{tabulate(tab)}{await hash_point_format(self.value, tab)}'
return f"{self.owner}" f"{tabulate(tab)}{await hash_point_format(self.value, tab)}"
class FlowCoin(RecursiveMentionable, StaticMentionable):
def __init__(
self,
data: HashPoint[FlowCoinData],
transaction: HashPoint['FlowTransaction']
):
def __init__(self, data: HashPoint[FlowCoinData], transaction: HashPoint[FlowTransaction]):
assert isinstance(data, HashPoint)
assert isinstance(transaction, HashPoint)
self.data = data
@ -87,23 +85,25 @@ class FlowCoin(RecursiveMentionable, StaticMentionable):
return bytes(self.data) + bytes(self.transaction)
@classmethod
def from_bytes(cls, source: bytes, resolver: HashResolver) -> 'FlowCoin':
def from_bytes(cls, source: bytes, resolver: HashResolver) -> FlowCoin:
assert isinstance(source, bytes)
assert isinstance(resolver, HashResolver)
return cls(
ResolverOrigin(FlowCoinData.factory(), source[:HashPoint.HASH_LENGTH], resolver).hash_point(),
ResolverOrigin(FlowCoinData.factory(), source[: HashPoint.HASH_LENGTH], resolver).hash_point(),
ResolverOrigin(
FlowTransaction.factory(), source[HashPoint.HASH_LENGTH:2 * HashPoint.HASH_LENGTH], resolver
FlowTransaction.factory(), source[HashPoint.HASH_LENGTH : 2 * HashPoint.HASH_LENGTH], resolver
).hash_point(),
)
async def str(self, tab: int) -> str:
assert isinstance(tab, int)
return f'(' \
f'{tabulate(tab + 1)}coin' \
f'{tabulate(tab + 1)}{await hash_point_format(self.data, tab + 1)}' \
f'{tabulate(tab + 1)}(origin)' \
f'{tabulate(tab)})'
return (
f"("
f"{tabulate(tab + 1)}coin"
f"{tabulate(tab + 1)}{await hash_point_format(self.data, tab + 1)}"
f"{tabulate(tab + 1)}(origin)"
f"{tabulate(tab)})"
)
async def int_value(self) -> int:
return await (await self.data_resolved()).int_value()
@ -114,9 +114,9 @@ class FlowCoin(RecursiveMentionable, StaticMentionable):
class FlowTransactionData(RecursiveMentionable, StaticMentionable):
def __init__(
self,
in_coins: FlowStandard[FlowCoin],
out_coins: FlowStandard[FlowCoinData],
self,
in_coins: FlowStandard[FlowCoin],
out_coins: FlowStandard[FlowCoinData],
):
assert isinstance(in_coins, FlowStandard)
assert isinstance(out_coins, FlowStandard)
@ -132,78 +132,63 @@ class FlowTransactionData(RecursiveMentionable, StaticMentionable):
return bytes(self.in_coins) + bytes(self.out_coins)
@classmethod
def from_bytes(cls, source: bytes, resolver: HashResolver) -> 'FlowTransactionData':
def from_bytes(cls, source: bytes, resolver: HashResolver) -> FlowTransactionData:
assert isinstance(source, bytes)
assert isinstance(resolver, HashResolver)
return cls(
FlowStandardFactory.of(
FlowCoin.factory(), HashComparator(Fail())
).from_bytes(source[:HashPoint.HASH_LENGTH], resolver),
FlowStandardFactory.of(
FlowCoinData.factory(), HashComparator(Fail())
).from_bytes(source[HashPoint.HASH_LENGTH:], resolver),
FlowStandardFactory.of(FlowCoin.factory(), HashComparator(Fail())).from_bytes(
source[: HashPoint.HASH_LENGTH], resolver
),
FlowStandardFactory.of(FlowCoinData.factory(), HashComparator(Fail())).from_bytes(
source[HashPoint.HASH_LENGTH :], resolver
),
)
async def _signature_verify(self, coin: FlowCoin, signature: Signature) -> bool:
assert isinstance(coin, FlowCoin)
assert isinstance(signature, Signature)
assert_true(
signature.verify(
await coin.owner(),
self.hash_point
)
)
assert_true(signature.verify(await coin.owner(), self.hash_point))
return True
@classmethod
def _coin_verification_mapper(
cls,
signatures: FlowStandard[KeyValue[Subject, Signature]],
) -> Mapper[
HashPoint[FlowCoin],
bool
]:
cls,
signatures: FlowStandard[KeyValue[Subject, Signature]],
) -> Mapper[HashPoint[FlowCoin], bool]:
assert isinstance(signatures, FlowStandard)
return ResolveMapper.wrap_mapper(CVMapper(signatures).loose())
def _signature_pair_verification_mapper(self) -> Mapper[
HashPoint[KeyValue[Subject, Signature]],
bool
]:
def _signature_pair_verification_mapper(self) -> Mapper[HashPoint[KeyValue[Subject, Signature]], bool]:
return ResolveMapper.wrap_mapper(SPVMapper(self.hash_point).loose())
async def _verify_coin_signatures(
self,
signatures: FlowStandard[KeyValue[Subject, Signature]],
self,
signatures: FlowStandard[KeyValue[Subject, Signature]],
) -> bool:
assert isinstance(signatures, FlowStandard)
assert_true(
await ReduceVerification(
MapperVerification(self._coin_verification_mapper(signatures))
).loose().verify(
await self.in_coins.reducer()
)
await ReduceVerification(MapperVerification(self._coin_verification_mapper(signatures)))
.loose()
.verify(await self.in_coins.reducer())
)
return True
async def _verify_signature_pairs(
self,
signatures: FlowStandard[KeyValue[Subject, Signature]],
self,
signatures: FlowStandard[KeyValue[Subject, Signature]],
):
assert isinstance(signatures, FlowStandard)
assert_true(
await ReduceVerification(
MapperVerification(self._signature_pair_verification_mapper())
).loose().verify(
await signatures.reducer()
)
await ReduceVerification(MapperVerification(self._signature_pair_verification_mapper()))
.loose()
.verify(await signatures.reducer())
)
return True
async def _verify_signatures(
self,
signatures: FlowStandard[KeyValue[Subject, Signature]],
self,
signatures: FlowStandard[KeyValue[Subject, Signature]],
) -> bool:
assert isinstance(signatures, FlowStandard)
assert_trues(
@ -214,10 +199,7 @@ class FlowTransactionData(RecursiveMentionable, StaticMentionable):
)
return True
async def verify(
self,
signatures: FlowStandard[KeyValue[Subject, Signature]]
) -> bool:
async def verify(self, signatures: FlowStandard[KeyValue[Subject, Signature]]) -> bool:
assert isinstance(signatures, FlowStandard)
assert_true(await self._verify_signatures(signatures))
return True
@ -230,13 +212,10 @@ class FlowTransactionData(RecursiveMentionable, StaticMentionable):
)
assert isinstance(in_str, str)
assert isinstance(out_str, str)
return f'(in)' \
f'{tabulate(tab)}{in_str}' \
f'{tabulate(tab)}(out)' \
f'{tabulate(tab)}{out_str}'
return f"(in)" f"{tabulate(tab)}{in_str}" f"{tabulate(tab)}(out)" f"{tabulate(tab)}{out_str}"
@classmethod
def empty(cls) -> 'FlowTransactionData':
def empty(cls) -> FlowTransactionData:
return cls(
FlowStandardFactory.empty(FlowCoin.factory(), HashComparator(Fail())),
FlowStandardFactory.empty(FlowCoinData.factory(), HashComparator(Fail())),
@ -252,8 +231,7 @@ class CVMapper(Mapper[FlowCoin, bool]):
assert isinstance(element, FlowCoin)
assert_true(
await self.signatures.contains(
HashPoint.of(KeyValue.of(await element.owner(), Signature.empty())),
exact=False
HashPoint.of(KeyValue.of(await element.owner(), Signature.empty())), exact=False
)
)
return True
@ -285,11 +263,7 @@ class SPVMapper(Mapper[KeyValue[Subject, Signature], bool]):
class FlowTransaction(RecursiveMentionable, StaticMentionable):
def __init__(
self,
data: FlowTransactionData,
signatures: FlowStandard[KeyValue[Subject, Signature]]
):
def __init__(self, data: FlowTransactionData, signatures: FlowStandard[KeyValue[Subject, Signature]]):
assert isinstance(data, FlowTransactionData)
assert isinstance(signatures, FlowStandard)
self.data = data
@ -308,17 +282,14 @@ class FlowTransaction(RecursiveMentionable, StaticMentionable):
return bytes(self.data) + bytes(self.signatures)
@classmethod
def from_bytes(cls, source: bytes, resolver: HashResolver) -> 'FlowTransaction':
def from_bytes(cls, source: bytes, resolver: HashResolver) -> FlowTransaction:
assert isinstance(source, bytes)
assert isinstance(resolver, HashResolver)
return cls(
FlowTransactionData.from_bytes(source[:-HashPoint.HASH_LENGTH], resolver),
FlowTransactionData.from_bytes(source[: -HashPoint.HASH_LENGTH], resolver),
FlowStandardFactory.of(
KeyValue.f(Subject.factory(), Signature.factory()),
KeyedComparator(HashComparator(Fail()))
).from_bytes(
source[-HashPoint.HASH_LENGTH:], resolver
),
KeyValue.f(Subject.factory(), Signature.factory()), KeyedComparator(HashComparator(Fail()))
).from_bytes(source[-HashPoint.HASH_LENGTH :], resolver),
)
def _coin(self, data: HashPoint[FlowCoinData]) -> HashPoint[FlowCoin]:
@ -337,11 +308,13 @@ class FlowTransaction(RecursiveMentionable, StaticMentionable):
async def str(self, tab: int) -> str:
assert isinstance(tab, int)
return f'(' \
f'{tabulate(tab + 1)}transaction' \
f'{tabulate(tab + 1)}{await self.data.str(tab + 1)}' \
f'{tabulate(tab + 1)}(signatures)' \
f'{tabulate(tab)})'
return (
f"("
f"{tabulate(tab + 1)}transaction"
f"{tabulate(tab + 1)}{await self.data.str(tab + 1)}"
f"{tabulate(tab + 1)}(signatures)"
f"{tabulate(tab)})"
)
@classmethod
def empty(cls):
@ -354,11 +327,11 @@ class FlowTransaction(RecursiveMentionable, StaticMentionable):
@classmethod
async def make(
cls,
used: Iterable[FlowCoin],
minted: Iterable[FlowCoinData],
keys: Iterable[SigningKey],
) -> 'FlowTransaction':
cls,
used: Iterable[FlowCoin],
minted: Iterable[FlowCoinData],
keys: Iterable[SigningKey],
) -> FlowTransaction:
used_std: FlowStandard[FlowCoin]
minted_std: FlowStandard[FlowCoinData]
used_std, minted_std = await gather(
@ -376,14 +349,11 @@ class FlowTransaction(RecursiveMentionable, StaticMentionable):
Subject(signing_key.verify_key),
Signature.sign(signing_key, transaction_data.hash_point),
)
for
signing_key
in
keys
for signing_key in keys
]
return cls(
transaction_data,
await FlowStandardFactory.off(
KeyValue.f(Subject.factory(), Signature.factory()), KeyedComparator(HashComparator(Fail())), signatures
)
),
)

View File

@ -1,13 +1,15 @@
from __future__ import annotations
from typing import Any, Generic, TypeVar
from rainbowadn.core import *
from rainbowadn.flow.core import *
from rainbowadn.flow.verification.core import *
__all__ = ('FlowTree',)
__all__ = ("FlowTree",)
Key = TypeVar('Key')
Tree = TypeVar('Tree')
Key = TypeVar("Key")
Tree = TypeVar("Tree")
class FlowTree(Generic[Key, Tree]):
@ -28,7 +30,7 @@ class FlowTree(Generic[Key, Tree]):
assert_true(await ReduceVerification(key_verification).loose().verify(keys))
return True
async def verify_subset(self: Tree, trees: Reducer['FlowTree[Key, Tree]', Any]) -> bool:
async def verify_subset(self: Tree, trees: Reducer[FlowTree[Key, Tree], Any]) -> bool:
raise NotImplementedError
async def reducer(self) -> Reducer[Key, Any]:
@ -36,13 +38,7 @@ class FlowTree(Generic[Key, Tree]):
async def verify(self, verification: Verification[Key]) -> bool:
assert isinstance(verification, Verification)
assert_true(
await ReduceVerification(
verification
).loose().verify(
await self.reducer()
)
)
assert_true(await ReduceVerification(verification).loose().verify(await self.reducer()))
return True

View File

@ -4,9 +4,9 @@ from rainbowadn.core import *
from ._flowstandard import *
__all__ = ('flow_union',)
__all__ = ("flow_union",)
KeyT = TypeVar('KeyT', bound=Mentionable)
KeyT = TypeVar("KeyT", bound=Mentionable)
async def flow_union(left: FlowStandard[KeyT], right: FlowStandard[KeyT]) -> FlowStandard[KeyT]:

View File

@ -3,10 +3,10 @@ from typing import Generic, TypeVar
from rainbowadn.core import *
from rainbowadn.flow.core import *
__all__ = ('ResolveMapper',)
__all__ = ("ResolveMapper",)
MentionedT = TypeVar('MentionedT', bound=Mentionable)
Out = TypeVar('Out')
MentionedT = TypeVar("MentionedT", bound=Mentionable)
Out = TypeVar("Out")
class ResolveMapper(Mapper[HashPoint[MentionedT], MentionedT], Generic[MentionedT]):

View File

@ -1,12 +1,15 @@
__all__ = (
'IAtomic',
'IAuto', 'Auto', 'IAutoFactory',
'IByte',
'Inlining',
'IPair',
'IRef',
'IStatic', 'IStaticFactory',
'IUnit',
"IAtomic",
"IAuto",
"Auto",
"IAutoFactory",
"IByte",
"Inlining",
"IPair",
"IRef",
"IStatic",
"IStaticFactory",
"IUnit",
)
from .iatomic import IAtomic

View File

@ -5,14 +5,14 @@ from rainbowadn.core import *
from .istatic import *
__all__ = ('IAtomic',)
__all__ = ("IAtomic",)
InlinedAtomic = TypeVar('InlinedAtomic')
InlinedAtomic = TypeVar("InlinedAtomic")
class IAtomic(IStatic, abc.ABC):
def __topology_hash__(self) -> bytes:
return HashPoint.hash(b'')
return HashPoint.hash(b"")
@classmethod
def from_bytes(cls: Type[InlinedAtomic], source: bytes, resolver: HashResolver) -> InlinedAtomic:

View File

@ -1,30 +1,38 @@
from __future__ import annotations
import heapq
from typing import (
Callable, Generic, Iterable, Optional, Type, TypeAlias,
TypeVar, overload
Callable,
Generic,
Iterable,
Optional,
Type,
TypeAlias,
TypeVar,
overload,
)
from rainbowadn.core import *
from .inlining import *
__all__ = ('IAuto', 'Auto', 'IAutoFactory',)
__all__ = (
"IAuto",
"Auto",
"IAutoFactory",
)
_IList: TypeAlias = list[tuple[int, Mentionable]]
_UList: TypeAlias = list[tuple[int, HashPoint]]
_SList: TypeAlias = list[tuple[int, RainbowFactory, int]]
_VList: TypeAlias = list[tuple[int, RainbowFactory]]
_MCall: TypeAlias = Callable[['Auto', _IList, _UList], None]
_MCall: TypeAlias = Callable[["Auto", _IList, _UList], None]
_MTuple: TypeAlias = tuple[int, _MCall, int]
_IAuto = TypeVar('_IAuto', bound='IAuto')
_IAuto = TypeVar("_IAuto", bound="IAuto")
class IAuto(RecursiveMentionable):
def __init__(
self,
inlined: _IList,
uninlined: _UList
):
def __init__(self, inlined: _IList, uninlined: _UList):
assert isinstance(inlined, list)
assert isinstance(uninlined, list)
for index, mentionable in inlined:
@ -59,7 +67,7 @@ class IAuto(RecursiveMentionable):
for index, uninlined in self.uninlined:
uninlined_bytes.append((index, bytes(uninlined)))
merged_bytes: Iterable[tuple[int, bytes]] = heapq.merge(inlined_bytes, uninlined_bytes)
return b''.join(source for _, source in merged_bytes)
return b"".join(source for _, source in merged_bytes)
def __factory__(self: _IAuto) -> RainbowFactory[_IAuto]:
sized: _SList = []
@ -76,11 +84,7 @@ class IAuto(RecursiveMentionable):
for index, uninlined in self.uninlined:
uninlined_unsized.append((index, uninlined.factory))
merged_unsized: Iterable[tuple[int, RainbowFactory]] = heapq.merge(inlined_unsized, uninlined_unsized)
return IAutoFactory(
type(self),
sized,
list(merged_unsized)
)
return IAutoFactory(type(self), sized, list(merged_unsized))
def hashpoints(self) -> Iterable[HashPoint]:
inlined_hashpoints: list[tuple[int, HashPoint]] = []
@ -156,15 +160,15 @@ class IAuto(RecursiveMentionable):
async def str(self, tab: int) -> str:
assert isinstance(tab, int)
formatted = await gather(*(hash_point_format(hashpoint, tab) for hashpoint in self.hashpoints()))
return f'{tabulate(tab)}'.join(formatted)
return f"{tabulate(tab)}".join(formatted)
T = TypeVar('T', bound=Mentionable)
T0 = TypeVar('T0', bound=Mentionable)
T1 = TypeVar('T1', bound=Mentionable)
T2 = TypeVar('T2', bound=Mentionable)
T3 = TypeVar('T3', bound=Mentionable)
T4 = TypeVar('T4', bound=Mentionable)
T = TypeVar("T", bound=Mentionable)
T0 = TypeVar("T0", bound=Mentionable)
T1 = TypeVar("T1", bound=Mentionable)
T2 = TypeVar("T2", bound=Mentionable)
T3 = TypeVar("T3", bound=Mentionable)
T4 = TypeVar("T4", bound=Mentionable)
class Auto:
@ -185,7 +189,7 @@ class Auto:
def as_mentionable(self, factory: RainbowFactory) -> Mentionable:
return self.as_value(factory)
def sub(self, start: Optional[int], stop: Optional[int]) -> 'Auto':
def sub(self, start: Optional[int], stop: Optional[int]) -> Auto:
return Auto(self.source[start:stop], self.resolver)
def __enter__(self):
@ -194,7 +198,7 @@ class Auto:
def __exit__(self, exc_type, exc_val, exc_tb):
assert_eq(len(self.source), self.__index)
def next(self, size: int) -> 'Auto':
def next(self, size: int) -> Auto:
assert isinstance(size, int)
index = self.__index
self.__index += size
@ -220,7 +224,7 @@ class Auto:
def _static_separate(self, infix_position: int, *factories: RainbowFactory) -> Iterable[Mentionable]:
prefix = factories[:infix_position]
postfix = factories[infix_position + 1:]
postfix = factories[infix_position + 1 :]
prefix_size = self._static_size(*prefix)
postfix_size = self._static_size(*postfix)
postfix_start = len(self.source) - postfix_size
@ -236,40 +240,39 @@ class Auto:
if infix_position is None:
infix_position = index
else:
raise ValueError('static auto parse does not allow uninlineable values (two or more unsized)')
raise ValueError("static auto parse does not allow uninlineable values (two or more unsized)")
if infix_position is None:
yield from self._static_simple(*factories)
else:
yield from self._static_separate(infix_position, *factories)
@overload
def static(
self, t0: RainbowFactory[T0], /
) -> tuple[T0]:
def static(self, t0: RainbowFactory[T0], /) -> tuple[T0]:
...
@overload
def static(self, t0: RainbowFactory[T0], t1: RainbowFactory[T1], /) -> tuple[T0, T1]:
...
@overload
def static(self, t0: RainbowFactory[T0], t1: RainbowFactory[T1], t2: RainbowFactory[T2], /) -> tuple[T0, T1, T2]:
...
@overload
def static(
self, t0: RainbowFactory[T0], t1: RainbowFactory[T1], /
) -> tuple[T0, T1]:
...
@overload
def static(
self, t0: RainbowFactory[T0], t1: RainbowFactory[T1], t2: RainbowFactory[T2], /
) -> tuple[T0, T1, T2]:
...
@overload
def static(
self, t0: RainbowFactory[T0], t1: RainbowFactory[T1], t2: RainbowFactory[T2], t3: RainbowFactory[T3], /
self, t0: RainbowFactory[T0], t1: RainbowFactory[T1], t2: RainbowFactory[T2], t3: RainbowFactory[T3], /
) -> tuple[T0, T1, T2, T3]:
...
@overload
def static(
self, t0: RainbowFactory[T0], t1: RainbowFactory[T1], t2: RainbowFactory[T2], t3: RainbowFactory[T3],
t4: RainbowFactory[T4], /
self,
t0: RainbowFactory[T0],
t1: RainbowFactory[T1],
t2: RainbowFactory[T2],
t3: RainbowFactory[T3],
t4: RainbowFactory[T4],
/,
) -> tuple[T0, T1, T2, T3, T4]:
...
@ -278,12 +281,7 @@ class Auto:
class IAutoFactory(Inlining[_IAuto], Generic[_IAuto]):
def __init__(
self,
typed: Type[_IAuto],
sized: _SList,
unsized: _VList
):
def __init__(self, typed: Type[_IAuto], sized: _SList, unsized: _VList):
assert issubclass(typed, IAuto)
assert isinstance(sized, list)
assert isinstance(unsized, list)
@ -369,13 +367,9 @@ class IAutoFactory(Inlining[_IAuto], Generic[_IAuto]):
unsized_mergeable: list[_MTuple] = []
sized_mergeable: list[_MTuple] = []
for index, factory in self.unsized:
unsized_mergeable.append(
self._unsized_mtuple(index, factory)
)
unsized_mergeable.append(self._unsized_mtuple(index, factory))
for index, factory, size in self.sized:
sized_mergeable.append(
self._sized_mtuple(index, factory, size)
)
sized_mergeable.append(self._sized_mtuple(index, factory, size))
merged: Iterable[_MTuple] = heapq.merge(unsized_mergeable, sized_mergeable)
return [(method, size) for _, method, size in merged]
@ -386,9 +380,7 @@ class IAutoFactory(Inlining[_IAuto], Generic[_IAuto]):
return sum(size for _, size in self.merged)
@classmethod
def _parse_affix(
cls, auto: Auto, affix: _SList
) -> Iterable[tuple[int, Mentionable]]:
def _parse_affix(cls, auto: Auto, affix: _SList) -> Iterable[tuple[int, Mentionable]]:
assert isinstance(auto, Auto)
assert isinstance(affix, list)
with auto:

View File

@ -1,6 +1,8 @@
from __future__ import annotations
from .iatomic import *
__all__ = ('IByte',)
__all__ = ("IByte",)
class IByte(IAtomic):
@ -14,7 +16,7 @@ class IByte(IAtomic):
return 1
@classmethod
def _from_bytes(cls, source: bytes) -> 'IByte':
def _from_bytes(cls, source: bytes) -> IByte:
assert isinstance(source, bytes)
[value] = source
return IByte(value)
@ -23,4 +25,4 @@ class IByte(IAtomic):
return bytes([self.value])
def __str__(self):
return f'{self.value:02x}'
return f"{self.value:02x}"

View File

@ -3,9 +3,9 @@ from typing import Any, Callable, Coroutine, Optional, TypeAlias, TypeVar
from rainbowadn.core import *
__all__ = ('Inlining',)
__all__ = ("Inlining",)
Inlined = TypeVar('Inlined', bound=Mentionable, covariant=True)
Inlined = TypeVar("Inlined", bound=Mentionable, covariant=True)
_FTuple: TypeAlias = tuple[int, Callable[[bytes, HashResolver], HashPoint], int]
_HTuple: TypeAlias = tuple[int, Callable[[], Coroutine[Any, Any, bytes]]]

View File

@ -1,13 +1,15 @@
from __future__ import annotations
from typing import Generic, TypeVar
from rainbowadn.core import *
from .iauto import *
__all__ = ('IPair',)
__all__ = ("IPair",)
E0 = TypeVar('E0', bound=Mentionable)
E1 = TypeVar('E1', bound=Mentionable)
E0 = TypeVar("E0", bound=Mentionable)
E1 = TypeVar("E1", bound=Mentionable)
class IPair(IAuto, Generic[E0, E1]):
@ -19,19 +21,19 @@ class IPair(IAuto, Generic[E0, E1]):
self.e0, self.e1 = self.hashpoints()
@classmethod
async def off(cls, e0: HashPoint[E0], e1: HashPoint[E1]) -> 'IPair[E0, E1]':
async def off(cls, e0: HashPoint[E0], e1: HashPoint[E1]) -> IPair[E0, E1]:
assert isinstance(e0, HashPoint)
assert isinstance(e1, HashPoint)
return await cls.auto_off(e0, e1)
@classmethod
def of(cls, v0: E0, v1: E1) -> 'IPair[E0, E1]':
def of(cls, v0: E0, v1: E1) -> IPair[E0, E1]:
assert isinstance(v0, Mentionable)
assert isinstance(v1, Mentionable)
return cls.auto_of(v0, v1)
@classmethod
def f(cls, f0: RainbowFactory[E0], f1: RainbowFactory[E1]) -> RainbowFactory['IPair[E0, E1]']:
def f(cls, f0: RainbowFactory[E0], f1: RainbowFactory[E1]) -> RainbowFactory[IPair[E0, E1]]:
assert isinstance(f0, RainbowFactory)
assert isinstance(f1, RainbowFactory)
return cls.auto_f(f0, f1)

View File

@ -1,12 +1,14 @@
from __future__ import annotations
from typing import Generic, Iterable, Optional, TypeVar
from rainbowadn.core import *
from .inlining import *
__all__ = ('IRef',)
__all__ = ("IRef",)
TRef = TypeVar('TRef', bound=Mentionable)
TRef = TypeVar("TRef", bound=Mentionable)
class IRef(RecursiveMentionable, Generic[TRef]):
@ -16,7 +18,7 @@ class IRef(RecursiveMentionable, Generic[TRef]):
def __bytes__(self):
return bytes(self.hashpoint)
def __factory__(self) -> RainbowFactory['IRef[TRef]']:
def __factory__(self) -> RainbowFactory[IRef[TRef]]:
return IReff(self.hashpoint.factory)
def __init__(self, hashpoint: HashPoint[TRef]):
@ -34,6 +36,4 @@ class IReff(Inlining[IRef[TRef]], Generic[TRef]):
def from_bytes(self, source: bytes, resolver: HashResolver) -> IRef[TRef]:
assert_eq(len(source), HashPoint.HASH_LENGTH)
return IRef(
ResolverMetaOrigin(resolver).hash_point(self.factory, source)
)
return IRef(ResolverMetaOrigin(resolver).hash_point(self.factory, source))

Some files were not shown because too many files have changed in this diff Show More