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

46
plot.py
View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,8 @@
from __future__ import annotations
from .atomic import * from .atomic import *
__all__ = ('Plain',) __all__ = ("Plain",)
class Plain(Atomic): class Plain(Atomic):
@ -9,7 +11,7 @@ class Plain(Atomic):
self.source = source self.source = source
@classmethod @classmethod
def _from_bytes(cls, source: bytes) -> 'Plain': def _from_bytes(cls, source: bytes) -> Plain:
assert isinstance(source, bytes) assert isinstance(source, bytes)
return cls(source) return cls(source)
@ -17,4 +19,4 @@ class Plain(Atomic):
return self.source return self.source
def __str__(self): 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.core import *
from rainbowadn.nullability 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( class CollectionInterface(Generic[CollectionType]):
Generic[CollectionType] def __init__(self, reference: NullableReference[CollectionType]):
):
def __init__(
self,
reference: NullableReference[CollectionType]
):
assert isinstance(reference, NullableReference) assert isinstance(reference, NullableReference)
self.reference = reference self.reference = reference

View File

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

View File

@ -4,7 +4,14 @@ from typing import Generic, TypeVar
from rainbowadn.core import * from rainbowadn.core import *
__all__ = ( __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 pass
KeyType = TypeVar('KeyType', bound=Mentionable, contravariant=True) KeyType = TypeVar("KeyType", bound=Mentionable, contravariant=True)
class Comparator(Generic[KeyType]): class Comparator(Generic[KeyType]):

View File

@ -5,9 +5,9 @@ from rainbowadn.core import *
from .comparator import * from .comparator import *
from .protocolcomparator 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]): class HashComparator(ProtocolComparator[KeyType], Generic[KeyType]):

View File

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

View File

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

View File

@ -5,9 +5,9 @@ from rainbowadn.core import *
from .comparator 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]): class ProtocolComparator(Comparator[KeyType], abc.ABC, Generic[KeyType]):

View File

@ -3,9 +3,9 @@ from typing import Generic, TypeVar
from rainbowadn.core import * 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): class Keyed(RecursiveMentionable, Generic[KKeyType], abc.ABC):

View File

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

View File

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

View File

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

View File

@ -2,17 +2,16 @@ from typing import Generic, Iterable, TypeVar
from rainbowadn.core import * 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]): class Array(RecursiveMentionable, Generic[ElementType]):
def __init__( def __init__(self, factory: RainbowFactory[ElementType], array: tuple[HashPoint[ElementType], ...]):
self,
factory: RainbowFactory[ElementType],
array: tuple[HashPoint[ElementType], ...]
):
assert isinstance(factory, RainbowFactory) assert isinstance(factory, RainbowFactory)
assert isinstance(array, tuple) assert isinstance(array, tuple)
self.factory = factory self.factory = factory
@ -22,31 +21,23 @@ class Array(RecursiveMentionable, Generic[ElementType]):
return self.array return self.array
def __bytes__(self): 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) return ArrayFactory(self.factory)
async def str(self, tab: int) -> str: async def str(self, tab: int) -> str:
assert isinstance(tab, int) assert isinstance(tab, int)
formatted = f'(' formatted = f"("
formatted += ''.join( formatted += "".join(
f'{tabulate(tab + 1)}{hash_point_str}' f"{tabulate(tab + 1)}{hash_point_str}"
for hash_point_str in await gather( for hash_point_str in await gather(*(hash_point_format(hash_point, tab + 1) for hash_point in self.array))
*(
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]): class ArrayFactory(RainbowFactory[Array], Generic[ElementType]):
def __init__( def __init__(self, factory: RainbowFactory[ElementType]):
self,
factory: RainbowFactory[ElementType]
):
assert isinstance(factory, RainbowFactory) assert isinstance(factory, RainbowFactory)
self.factory = factory self.factory = factory
@ -57,9 +48,6 @@ class ArrayFactory(RainbowFactory[Array], Generic[ElementType]):
self.factory, self.factory,
tuple( tuple(
ResolverOrigin(self.factory, source[i : i + HashPoint.HASH_LENGTH], resolver).hash_point() ResolverOrigin(self.factory, source[i : i + HashPoint.HASH_LENGTH], resolver).hash_point()
for for i in range(0, len(source), HashPoint.HASH_LENGTH)
i ),
in
range(0, len(source), HashPoint.HASH_LENGTH)
)
) )

View File

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

View File

@ -1,12 +1,17 @@
from __future__ import annotations
from typing import Generic, Iterable, TypeVar from typing import Generic, Iterable, TypeVar
from rainbowadn.core import * from rainbowadn.core import *
from .tlparametres 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]): class TLNode(RecursiveMentionable, Generic[ElementType]):
@ -14,7 +19,7 @@ class TLNode(RecursiveMentionable, Generic[ElementType]):
self, self,
source: bytes, source: bytes,
parametres: TLParametres[ElementType], parametres: TLParametres[ElementType],
node_cache: tuple[MetaOrigin['TLNode[ElementType]'], ...], node_cache: tuple[MetaOrigin[TLNode[ElementType]], ...],
element_cache: tuple[MetaOrigin[ElementType], ...], element_cache: tuple[MetaOrigin[ElementType], ...],
): ):
assert isinstance(source, bytes) assert isinstance(source, bytes)
@ -45,18 +50,13 @@ class TLNode(RecursiveMentionable, Generic[ElementType]):
meta_origin: MetaOrigin[ElementType] = self.element_cache[index] meta_origin: MetaOrigin[ElementType] = self.element_cache[index]
return meta_origin.hash_point(self.parametres.tlr.factory, self.bytes_no(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 isinstance(index, int)
assert index < self.nodes assert index < self.nodes
meta_origin: MetaOrigin[TLNode[ElementType]] = self.node_cache[index] meta_origin: MetaOrigin[TLNode[ElementType]] = self.node_cache[index]
return meta_origin.hash_point( return meta_origin.hash_point(TLNodeFactory(self.parametres.params_no(index)), self.bytes_no(index))
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 isinstance(index, int)
assert index < self.nodes assert index < self.nodes
return await self.node_no(index).resolve() return await self.node_no(index).resolve()
@ -73,19 +73,17 @@ class TLNode(RecursiveMentionable, Generic[ElementType]):
def __bytes__(self): def __bytes__(self):
return self.source return self.source
def __factory__(self) -> RainbowFactory['TLNode[ElementType]']: def __factory__(self) -> RainbowFactory[TLNode[ElementType]]:
return TLNodeFactory( return TLNodeFactory(self.parametres)
self.parametres
)
async def str(self, tab: int) -> str: async def str(self, tab: int) -> str:
assert isinstance(tab, int) assert isinstance(tab, int)
if self.parametres.size == 0: if self.parametres.size == 0:
return f'-' return f"-"
else: 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) assert isinstance(element, HashPoint)
return TLNode( return TLNode(
bytes(element), bytes(element),
@ -97,11 +95,11 @@ class TLNode(RecursiveMentionable, Generic[ElementType]):
def source_without_last(self) -> bytes: 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 assert not self.parametres.leaf
return await self.node_no_resolved(self.nodes - 1) 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(self, TLNode)
assert isinstance(element, HashPoint) assert isinstance(element, HashPoint)
if self.parametres.full: if self.parametres.full:
@ -114,7 +112,10 @@ class TLNode(RecursiveMentionable, Generic[ElementType]):
return TLNode( return TLNode(
bytes(self_hp) + bytes(unit_hp), bytes(self_hp) + bytes(unit_hp),
self.parametres.superparams(), self.parametres.superparams(),
(LocalMetaOrigin(self_hp.origin), LocalMetaOrigin(unit_hp.origin),), (
LocalMetaOrigin(self_hp.origin),
LocalMetaOrigin(unit_hp.origin),
),
(), (),
) )
elif self.parametres.leaf: elif self.parametres.leaf:

View File

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

View File

@ -1,3 +1,5 @@
from __future__ import annotations
from typing import Generic, Iterable, TypeVar from typing import Generic, Iterable, TypeVar
from rainbowadn.atomic import * from rainbowadn.atomic import *
@ -7,17 +9,16 @@ from .tlnode import *
from .tlparametres import * from .tlparametres import *
from .tlrparametres 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]): class TLRoot(RecursiveMentionable, Generic[ElementType]):
def __init__( def __init__(self, node: HashPoint[TLNode[ElementType]], parametres: TLParametres):
self,
node: HashPoint[TLNode[ElementType]],
parametres: TLParametres
):
assert isinstance(node, HashPoint) assert isinstance(node, HashPoint)
assert isinstance(parametres, TLParametres) assert isinstance(parametres, TLParametres)
self.node = node self.node = node
@ -29,19 +30,16 @@ class TLRoot(RecursiveMentionable, Generic[ElementType]):
def __bytes__(self): def __bytes__(self):
return bytes(self.node) + bytes(Integer(self.parametres.size)) 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) return TLRootFactory(self.parametres.tlr)
async def node_resolved(self) -> TLNode[ElementType]: async def node_resolved(self) -> TLNode[ElementType]:
return await self.node.resolve() 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) assert isinstance(element, HashPoint)
node = await (await self.node_resolved()).add(element) node = await (await self.node_resolved()).add(element)
return TLRoot( return TLRoot(HashPoint.of(node), node.parametres)
HashPoint.of(node),
node.parametres
)
async def str(self, tab: int) -> str: async def str(self, tab: int) -> str:
assert isinstance(tab, int) assert isinstance(tab, int)
@ -63,15 +61,10 @@ class TLRootFactory(RainbowFactory[TLRoot[ElementType]]):
assert isinstance(size, int) assert isinstance(size, int)
parametres = TLParametres(self.tlr, size) parametres = TLParametres(self.tlr, size)
return TLRoot( return TLRoot(
ResolverOrigin( ResolverOrigin(TLNodeFactory(parametres), source[: HashPoint.HASH_LENGTH], resolver).hash_point(),
TLNodeFactory(parametres), source[:HashPoint.HASH_LENGTH], resolver parametres,
).hash_point(),
parametres
) )
def empty(self) -> TLRoot[ElementType]: def empty(self) -> TLRoot[ElementType]:
parametres = TLParametres(self.tlr, 0) parametres = TLParametres(self.tlr, 0)
return TLRoot( return TLRoot(HashPoint.of(TLNode(b"", parametres, (), ())), parametres)
HashPoint.of(TLNode(b'', parametres, (), ())),
parametres
)

View File

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

View File

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

View File

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

View File

@ -3,12 +3,12 @@ from typing import Generic, TypeVar
from rainbowadn.collection.trees.binary.core import * from rainbowadn.collection.trees.binary.core import *
from rainbowadn.core import * from rainbowadn.core import *
__all__ = ('BinaryAction',) __all__ = ("BinaryAction",)
TreeType = TypeVar('TreeType') TreeType = TypeVar("TreeType")
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable) MetaDataType = TypeVar("MetaDataType", bound=Mentionable)
ActionType = TypeVar('ActionType') ActionType = TypeVar("ActionType")
class BinaryAction(Generic[ActiveKeyType, MetaDataType, TreeType, ActionType]): class BinaryAction(Generic[ActiveKeyType, MetaDataType, TreeType, ActionType]):
@ -29,8 +29,5 @@ class BinaryAction(Generic[ActiveKeyType, MetaDataType, TreeType, ActionType]):
) -> ActionType: ) -> ActionType:
raise NotImplementedError raise NotImplementedError
async def on_split( async def on_split(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> ActionType:
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> ActionType:
raise NotImplementedError raise NotImplementedError

View File

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

View File

@ -7,26 +7,25 @@ from rainbowadn.core import *
from .binaryaction import * from .binaryaction import *
from .compareaction import * from .compareaction import *
__all__ = ('AddAction', 'RemoveAction', 'ContainsAction', 'SplitAction', 'UnionAction', 'MergeAction',) __all__ = (
"AddAction",
"RemoveAction",
"ContainsAction",
"SplitAction",
"UnionAction",
"MergeAction",
)
TreeType = TypeVar('TreeType') TreeType = TypeVar("TreeType")
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable) MetaDataType = TypeVar("MetaDataType", bound=Mentionable)
class AddAction( class AddAction(
CompareAction[ CompareAction[ActiveKeyType, MetaDataType, TreeType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType]
ActiveKeyType,
MetaDataType,
TreeType,
TreeType
],
Generic[ActiveKeyType, MetaDataType, TreeType]
): ):
async def on_equal( async def on_equal(
self, self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], equal: Equal
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType],
equal: Equal
) -> TreeType: ) -> TreeType:
assert isinstance(case, ProtocolizedBinarySplit) assert isinstance(case, ProtocolizedBinarySplit)
assert isinstance(equal, Equal) assert isinstance(equal, Equal)
@ -35,27 +34,13 @@ class AddAction(
else: else:
raise TypeError raise TypeError
async def on_left( async def on_left(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
assert isinstance(case, ProtocolizedBinarySplit) assert isinstance(case, ProtocolizedBinarySplit)
return await case.protocol.tree( return await case.protocol.tree(await self.on(case.protocolizedl()), case.split.treer, case.split.key)
await self.on(case.protocolizedl()),
case.split.treer,
case.split.key
)
async def on_right( async def on_right(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
assert isinstance(case, ProtocolizedBinarySplit) assert isinstance(case, ProtocolizedBinarySplit)
return await case.protocol.tree( return await case.protocol.tree(case.split.treel, await self.on(case.protocolizedr()), case.split.key)
case.split.treel,
await self.on(case.protocolizedr()),
case.split.key
)
async def on_null( async def on_null(
self, self,
@ -66,13 +51,7 @@ class AddAction(
class MergeAction( class MergeAction(
BinaryAction[ BinaryAction[ActiveKeyType, MetaDataType, TreeType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType]
ActiveKeyType,
MetaDataType,
TreeType,
TreeType
],
Generic[ActiveKeyType, MetaDataType, TreeType]
): ):
def __init__(self, treer: TreeType): def __init__(self, treer: TreeType):
self.treer = treer self.treer = treer
@ -84,57 +63,30 @@ class MergeAction(
assert isinstance(protocolized, BinaryProtocolized) assert isinstance(protocolized, BinaryProtocolized)
return self.treer return self.treer
async def on_split( async def on_split(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
assert isinstance(case, ProtocolizedBinarySplit) assert isinstance(case, ProtocolizedBinarySplit)
return await case.protocol.tree( return await case.protocol.tree(
case.split.treel, case.split.treel, await MergeAction(self.treer).on(case.protocolizedr()), case.split.key
await MergeAction(self.treer).on(case.protocolizedr()),
case.split.key
) )
class RemoveAction( class RemoveAction(
CompareAction[ CompareAction[ActiveKeyType, MetaDataType, TreeType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType]
ActiveKeyType,
MetaDataType,
TreeType,
TreeType
],
Generic[ActiveKeyType, MetaDataType, TreeType]
): ):
async def on_equal( async def on_equal(
self, self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], equal: Equal
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType],
equal: Equal
) -> TreeType: ) -> TreeType:
assert isinstance(case, ProtocolizedBinarySplit) assert isinstance(case, ProtocolizedBinarySplit)
assert isinstance(equal, Equal) assert isinstance(equal, Equal)
return await MergeAction(case.split.treer).on(case.protocolizedl()) return await MergeAction(case.split.treer).on(case.protocolizedl())
async def on_left( async def on_left(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
assert isinstance(case, ProtocolizedBinarySplit) assert isinstance(case, ProtocolizedBinarySplit)
return await case.protocol.tree( return await case.protocol.tree(await self.on(case.protocolizedl()), case.split.treer, case.split.key)
await self.on(case.protocolizedl()),
case.split.treer,
case.split.key
)
async def on_right( async def on_right(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
assert isinstance(case, ProtocolizedBinarySplit) assert isinstance(case, ProtocolizedBinarySplit)
return await case.protocol.tree( return await case.protocol.tree(case.split.treel, await self.on(case.protocolizedr()), case.split.key)
case.split.treel,
await self.on(case.protocolizedr()),
case.split.key
)
async def on_null( async def on_null(
self, self,
@ -145,13 +97,7 @@ class RemoveAction(
class ContainsAction( class ContainsAction(
CompareAction[ CompareAction[ActiveKeyType, MetaDataType, TreeType, bool], Generic[ActiveKeyType, MetaDataType, TreeType]
ActiveKeyType,
MetaDataType,
TreeType,
bool
],
Generic[ActiveKeyType, MetaDataType, TreeType]
): ):
def __init__(self, key: HashPoint[ActiveKeyType], *, exact: bool): def __init__(self, key: HashPoint[ActiveKeyType], *, exact: bool):
assert isinstance(exact, bool) assert isinstance(exact, bool)
@ -159,9 +105,7 @@ class ContainsAction(
super().__init__(key) super().__init__(key)
async def on_equal( async def on_equal(
self, self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], equal: Equal
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType],
equal: Equal
) -> bool: ) -> bool:
assert isinstance(case, ProtocolizedBinarySplit) assert isinstance(case, ProtocolizedBinarySplit)
assert isinstance(equal, Equal) assert isinstance(equal, Equal)
@ -170,17 +114,11 @@ class ContainsAction(
else: else:
return True return True
async def on_left( async def on_left(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> bool:
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> bool:
assert isinstance(case, ProtocolizedBinarySplit) assert isinstance(case, ProtocolizedBinarySplit)
return await self.on(case.protocolizedl()) return await self.on(case.protocolizedl())
async def on_right( async def on_right(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> bool:
self,
case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> bool:
assert isinstance(case, ProtocolizedBinarySplit) assert isinstance(case, ProtocolizedBinarySplit)
return await self.on(case.protocolizedr()) return await self.on(case.protocolizedr())
@ -193,13 +131,8 @@ class ContainsAction(
class SplitAction( class SplitAction(
CompareAction[ CompareAction[ActiveKeyType, MetaDataType, TreeType, tuple[TreeType, TreeType]],
ActiveKeyType, Generic[ActiveKeyType, MetaDataType, TreeType],
MetaDataType,
TreeType,
tuple[TreeType, TreeType]
],
Generic[ActiveKeyType, MetaDataType, TreeType]
): ):
async def on_equal( async def on_equal(
self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], equal: Equal self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], equal: Equal
@ -228,13 +161,7 @@ class SplitAction(
class UnionAction( class UnionAction(
BinaryAction[ BinaryAction[ActiveKeyType, MetaDataType, TreeType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType]
ActiveKeyType,
MetaDataType,
TreeType,
TreeType
],
Generic[ActiveKeyType, MetaDataType, TreeType]
): ):
def __init__(self, protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType]): def __init__(self, protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType]):
assert isinstance(protocolized, BinaryProtocolized) assert isinstance(protocolized, BinaryProtocolized)

View File

@ -3,16 +3,18 @@ from typing import Generic, TypeVar
from rainbowadn.collection.trees.binary.core import * from rainbowadn.collection.trees.binary.core import *
from rainbowadn.core import * from rainbowadn.core import *
__all__ = ('Symmetric', 'InnerOuter', 'OuterInner',) __all__ = (
"Symmetric",
"InnerOuter",
"OuterInner",
)
TreeType = TypeVar('TreeType') TreeType = TypeVar("TreeType")
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable) MetaDataType = TypeVar("MetaDataType", bound=Mentionable)
class Symmetric( class Symmetric(Generic[ActiveKeyType, MetaDataType, TreeType]):
Generic[ActiveKeyType, MetaDataType, TreeType]
):
def __init__( def __init__(
self, self,
protocol: BinaryCreation[ActiveKeyType, MetaDataType, TreeType], protocol: BinaryCreation[ActiveKeyType, MetaDataType, TreeType],
@ -20,92 +22,51 @@ class Symmetric(
assert isinstance(protocol, BinaryCreation) assert isinstance(protocol, BinaryCreation)
self.protocol = protocol self.protocol = protocol
def inner( def inner(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
self,
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
raise NotImplementedError raise NotImplementedError
def outer( def outer(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
self,
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
raise NotImplementedError raise NotImplementedError
async def tree( async def tree(self, inner: TreeType, outer: TreeType, key: HashPoint[ActiveKeyType]) -> TreeType:
self,
inner: TreeType,
outer: TreeType,
key: HashPoint[ActiveKeyType]
) -> TreeType:
raise NotImplementedError raise NotImplementedError
def protocolizedi( def protocolizedi(
self, self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType]: ) -> BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType]:
assert isinstance(split, BinarySplit) assert isinstance(split, BinarySplit)
return BinaryProtocolized(self.protocol, self.inner(split)) return BinaryProtocolized(self.protocol, self.inner(split))
def protocolizedo( def protocolizedo(
self, self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType]: ) -> BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType]:
assert isinstance(split, BinarySplit) assert isinstance(split, BinarySplit)
return BinaryProtocolized(self.protocol, self.outer(split)) return BinaryProtocolized(self.protocol, self.outer(split))
class InnerOuter( class InnerOuter(Symmetric[ActiveKeyType, MetaDataType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType]):
Symmetric[ActiveKeyType, MetaDataType, TreeType], def inner(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
Generic[ActiveKeyType, MetaDataType, TreeType]
):
def inner(
self,
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
assert isinstance(split, BinarySplit) assert isinstance(split, BinarySplit)
return split.treel return split.treel
def outer( def outer(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
self,
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
assert isinstance(split, BinarySplit) assert isinstance(split, BinarySplit)
return split.treer return split.treer
async def tree( async def tree(self, inner: TreeType, outer: TreeType, key: HashPoint[ActiveKeyType]) -> TreeType:
self,
inner: TreeType,
outer: TreeType,
key: HashPoint[ActiveKeyType]
) -> TreeType:
assert isinstance(key, HashPoint) assert isinstance(key, HashPoint)
return await self.protocol.tree(inner, outer, key) return await self.protocol.tree(inner, outer, key)
class OuterInner( class OuterInner(Symmetric[ActiveKeyType, MetaDataType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType]):
Symmetric[ActiveKeyType, MetaDataType, TreeType], def inner(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
Generic[ActiveKeyType, MetaDataType, TreeType]
):
def inner(
self,
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
assert isinstance(split, BinarySplit) assert isinstance(split, BinarySplit)
return split.treer return split.treer
def outer( def outer(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType:
self,
split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]
) -> TreeType:
assert isinstance(split, BinarySplit) assert isinstance(split, BinarySplit)
return split.treel return split.treel
async def tree( async def tree(self, inner: TreeType, outer: TreeType, key: HashPoint[ActiveKeyType]) -> TreeType:
self,
inner: TreeType,
outer: TreeType,
key: HashPoint[ActiveKeyType]
) -> TreeType:
assert isinstance(key, HashPoint) assert isinstance(key, HashPoint)
return await self.protocol.tree(outer, inner, key) 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 typing import Generic, Optional, TypeVar
from rainbowadn.collection.collectioninterface import * from rainbowadn.collection.collectioninterface import *
@ -9,24 +11,19 @@ from .actions import *
from .binarytree import * from .binarytree import *
from .core import * from .core import *
__all__ = ('ActiveBinaryTree',) __all__ = ("ActiveBinaryTree",)
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable) MetaDataType = TypeVar("MetaDataType", bound=Mentionable)
class ActiveBinaryTree( class ActiveBinaryTree(
CollectionInterface[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]], CollectionInterface[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]], Generic[ActiveKeyType, MetaDataType]
Generic[ActiveKeyType, MetaDataType]
): ):
def __init__( def __init__(
self, self,
protocol: BinaryBalancing[ protocol: BinaryBalancing[ActiveKeyType, MetaDataType, ActiveBinaryTree[ActiveKeyType, MetaDataType]],
ActiveKeyType, reference: NullableReference[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]],
MetaDataType,
'ActiveBinaryTree[ActiveKeyType, MetaDataType]'
],
reference: NullableReference[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]]
): ):
assert isinstance(protocol, BinaryBalancing) assert isinstance(protocol, BinaryBalancing)
assert isinstance(reference, NullableReference) assert isinstance(reference, NullableReference)
@ -38,44 +35,32 @@ class ActiveBinaryTree(
@classmethod @classmethod
def empty( def empty(
cls, cls,
protocol: BinaryBalancing[ActiveKeyType, MetaDataType, 'ActiveBinaryTree'], protocol: BinaryBalancing[ActiveKeyType, MetaDataType, ActiveBinaryTree],
factory: RainbowFactory[ActiveKeyType] factory: RainbowFactory[ActiveKeyType],
): ):
assert isinstance(protocol, BinaryBalancing) assert isinstance(protocol, BinaryBalancing)
assert isinstance(factory, RainbowFactory) assert isinstance(factory, RainbowFactory)
return cls( return cls(
protocol, protocol,
NullableReference( NullableReference(Null(), BinaryTreeFactory(KeyMetadataFactory(factory, protocol.empty_metadata.factory))),
Null(),
BinaryTreeFactory(KeyMetadataFactory(factory, protocol.empty_metadata.factory))
)
) )
def create( def create(
self, self, reference: NullableReference[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]]
reference: NullableReference[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]] ) -> ActiveBinaryTree[ActiveKeyType, MetaDataType]:
) -> 'ActiveBinaryTree[ActiveKeyType, MetaDataType]':
assert isinstance(reference, NullableReference) assert isinstance(reference, NullableReference)
return ActiveBinaryTree( return ActiveBinaryTree(self.protocol, reference)
self.protocol,
reference
)
def protocolized(self) -> BinaryProtocolized[ def protocolized(
ActiveKeyType, self,
MetaDataType, ) -> BinaryProtocolized[ActiveKeyType, MetaDataType, ActiveBinaryTree[ActiveKeyType, MetaDataType]]:
'ActiveBinaryTree[ActiveKeyType, MetaDataType]' return BinaryProtocolized(self.creation, self)
]:
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) assert isinstance(key, HashPoint)
return await AddAction(key).on(self.protocolized()) 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) assert isinstance(key, HashPoint)
return await RemoveAction(key).on(self.protocolized()) return await RemoveAction(key).on(self.protocolized())
@ -83,20 +68,17 @@ class ActiveBinaryTree(
assert isinstance(key, HashPoint) assert isinstance(key, HashPoint)
return await ContainsAction(key, exact=exact).on(self.protocolized()) return await ContainsAction(key, exact=exact).on(self.protocolized())
async def split(self, key: HashPoint[ActiveKeyType]) -> tuple[ async def split(
'ActiveBinaryTree[ActiveKeyType, MetaDataType]', self, key: HashPoint[ActiveKeyType]
'ActiveBinaryTree[ActiveKeyType, MetaDataType]', ) -> tuple[ActiveBinaryTree[ActiveKeyType, MetaDataType], ActiveBinaryTree[ActiveKeyType, MetaDataType]]:
]:
return await SplitAction(key).on(self.protocolized()) return await SplitAction(key).on(self.protocolized())
async def union( async def union(
self, other: 'ActiveBinaryTree[ActiveKeyType, MetaDataType]' self, other: ActiveBinaryTree[ActiveKeyType, MetaDataType]
) -> 'ActiveBinaryTree[ActiveKeyType, MetaDataType]': ) -> ActiveBinaryTree[ActiveKeyType, MetaDataType]:
return await UnionAction(other.protocolized()).on(self.protocolized()) return await UnionAction(other.protocolized()).on(self.protocolized())
def loose(self) -> CollectionInterface[ def loose(self) -> CollectionInterface[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]]:
BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]
]:
return self return self
def __eq__(self, other): def __eq__(self, other):
@ -106,23 +88,10 @@ class ActiveBinaryTree(
return NotImplemented return NotImplemented
class ActiveCreation( class ActiveCreation(BalancedCreation[ActiveKeyType, MetaDataType, ActiveBinaryTree[ActiveKeyType, MetaDataType]]):
BalancedCreation[
ActiveKeyType,
MetaDataType,
ActiveBinaryTree[ActiveKeyType, MetaDataType]
]
):
async def split( async def split(
self, self, tree: ActiveBinaryTree[ActiveKeyType, MetaDataType]
tree: ActiveBinaryTree[ActiveKeyType, MetaDataType] ) -> Optional[BinarySplit[ActiveKeyType, MetaDataType, ActiveBinaryTree[ActiveKeyType, MetaDataType]]]:
) -> Optional[
BinarySplit[
ActiveKeyType,
MetaDataType,
ActiveBinaryTree[ActiveKeyType, MetaDataType]
]
]:
assert isinstance(tree, ActiveBinaryTree) assert isinstance(tree, ActiveBinaryTree)
if tree.reference.null(): if tree.reference.null():
return None return None
@ -136,10 +105,7 @@ class ActiveCreation(
) )
async def _tree( async def _tree(
self, self, treel: ActiveBinaryTree, treer: ActiveBinaryTree, key: HashPoint[ActiveKeyType]
treel: ActiveBinaryTree,
treer: ActiveBinaryTree,
key: HashPoint[ActiveKeyType]
) -> ActiveBinaryTree: ) -> ActiveBinaryTree:
assert isinstance(treel, ActiveBinaryTree) assert isinstance(treel, ActiveBinaryTree)
assert isinstance(treer, ActiveBinaryTree) assert isinstance(treer, ActiveBinaryTree)
@ -150,7 +116,7 @@ class ActiveCreation(
BinaryTree( BinaryTree(
treel.reference, treel.reference,
treer.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 .actions import *
from .core import * from .core import *
__all__ = ('AVL',) __all__ = ("AVL",)
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
TreeType = TypeVar('TreeType') TreeType = TypeVar("TreeType")
class AVL(BinaryBalancing[ActiveKeyType, Integer, TreeType]): class AVL(BinaryBalancing[ActiveKeyType, Integer, TreeType]):
@ -22,7 +22,7 @@ class AVL(BinaryBalancing[ActiveKeyType, Integer, TreeType]):
treel: TreeType, treel: TreeType,
treer: TreeType, treer: TreeType,
key: HashPoint[ActiveKeyType], key: HashPoint[ActiveKeyType],
creation: BinaryCreation[ActiveKeyType, Integer, TreeType] creation: BinaryCreation[ActiveKeyType, Integer, TreeType],
) -> HashPoint[Integer]: ) -> HashPoint[Integer]:
assert isinstance(key, HashPoint) assert isinstance(key, HashPoint)
assert isinstance(creation, BinaryCreation) assert isinstance(creation, BinaryCreation)
@ -35,8 +35,7 @@ class AVL(BinaryBalancing[ActiveKeyType, Integer, TreeType]):
return HashPoint.of( return HashPoint.of(
Integer( Integer(
1 1
+ + max(
max(
height_l, height_l,
height_r, height_r,
) )
@ -67,10 +66,7 @@ class AVL(BinaryBalancing[ActiveKeyType, Integer, TreeType]):
return await BalanceAction().on(protocolized) return await BalanceAction().on(protocolized)
class HeightAction( class HeightAction(BinaryAction[ActiveKeyType, Integer, TreeType, int], Generic[ActiveKeyType, TreeType]):
BinaryAction[ActiveKeyType, Integer, TreeType, int],
Generic[ActiveKeyType, TreeType]
):
async def on_null( async def on_null(
self, self,
protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType], protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType],
@ -78,10 +74,7 @@ class HeightAction(
assert isinstance(protocolized, BinaryProtocolized) assert isinstance(protocolized, BinaryProtocolized)
return 0 return 0
async def on_split( async def on_split(self, case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType]) -> int:
self,
case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType]
) -> int:
assert isinstance(case, ProtocolizedBinarySplit) assert isinstance(case, ProtocolizedBinarySplit)
metadata: Integer = await case.split.metadata.resolve() metadata: Integer = await case.split.metadata.resolve()
assert isinstance(metadata, Integer) assert isinstance(metadata, Integer)
@ -89,13 +82,8 @@ class HeightAction(
class FullHeightAction( class FullHeightAction(
BinaryAction[ BinaryAction[ActiveKeyType, Integer, TreeType, tuple[int, Optional[BinarySplit[ActiveKeyType, Integer, TreeType]]]],
ActiveKeyType, Generic[ActiveKeyType, TreeType],
Integer,
TreeType,
tuple[int, Optional[BinarySplit[ActiveKeyType, Integer, TreeType]]]
],
Generic[ActiveKeyType, TreeType]
): ):
async def on_null( async def on_null(
self, self,
@ -105,8 +93,7 @@ class FullHeightAction(
return 0, None return 0, None
async def on_split( async def on_split(
self, self, case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType]
case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType]
) -> tuple[int, Optional[BinarySplit[ActiveKeyType, Integer, TreeType]]]: ) -> tuple[int, Optional[BinarySplit[ActiveKeyType, Integer, TreeType]]]:
assert isinstance(case, ProtocolizedBinarySplit) assert isinstance(case, ProtocolizedBinarySplit)
metadata: Integer = await case.split.metadata.resolve() metadata: Integer = await case.split.metadata.resolve()
@ -114,10 +101,7 @@ class FullHeightAction(
return metadata.integer, case.split return metadata.integer, case.split
class BalanceAction( class BalanceAction(BinaryAction[ActiveKeyType, Integer, TreeType, TreeType], Generic[ActiveKeyType, TreeType]):
BinaryAction[ActiveKeyType, Integer, TreeType, TreeType],
Generic[ActiveKeyType, TreeType]
):
async def on_null( async def on_null(
self, self,
protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType], protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType],
@ -125,10 +109,7 @@ class BalanceAction(
assert isinstance(protocolized, BinaryProtocolized) assert isinstance(protocolized, BinaryProtocolized)
return protocolized.tree return protocolized.tree
async def on_split( async def on_split(self, case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType]) -> TreeType:
self,
case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType]
) -> TreeType:
assert isinstance(case, ProtocolizedBinarySplit) assert isinstance(case, ProtocolizedBinarySplit)
(height_l, splitl), (height_r, splitr) = await gather( (height_l, splitl), (height_r, splitr) = await gather(
AVL.full_height(case.protocolizedl()), AVL.full_height(case.protocolizedl()),
@ -173,14 +154,8 @@ class BalanceAction(
symmetry.tree(treei, symmetry.inner(splitoi), key), symmetry.tree(treei, symmetry.inner(splitoi), key),
symmetry.tree(symmetry.outer(splitoi), symmetry.outer(splito), splito.key), symmetry.tree(symmetry.outer(splitoi), symmetry.outer(splito), splito.key),
) )
return await symmetry.tree( return await symmetry.tree(inner, outer, splitoi.key)
inner,
outer,
splitoi.key
)
else: else:
return await symmetry.tree( return await symmetry.tree(
await symmetry.tree(treei, symmetry.inner(splito), key), await symmetry.tree(treei, symmetry.inner(splito), key), symmetry.outer(splito), splito.key
symmetry.outer(splito),
splito.key
) )

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -4,11 +4,11 @@ from rainbowadn.core import *
from .binarycreation import * from .binarycreation import *
__all__ = ('BinaryMetadata',) __all__ = ("BinaryMetadata",)
TreeType = TypeVar('TreeType') TreeType = TypeVar("TreeType")
ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable)
MetaDataType = TypeVar('MetaDataType', bound=Mentionable) MetaDataType = TypeVar("MetaDataType", bound=Mentionable)
class BinaryMetadata(Generic[ActiveKeyType, MetaDataType, TreeType]): class BinaryMetadata(Generic[ActiveKeyType, MetaDataType, TreeType]):

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,13 @@
from typing import Any, Iterable, Optional, TypeVar 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: def assert_true(value: bool) -> bool:
@ -19,7 +26,7 @@ def assert_false(value: bool) -> bool:
return True return True
T = TypeVar('T') T = TypeVar("T")
def assert_none(value: Optional[Any]) -> bool: def assert_none(value: Optional[Any]) -> bool:

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -7,9 +7,9 @@ from .metaorigin import *
from .origin import * from .origin import *
from .rainbow_factory 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]): class LocalMetaOrigin(MetaOrigin[Mentioned], Generic[Mentioned]):

View File

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

View File

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

View File

@ -6,9 +6,9 @@ from .mentionable import *
from .origin import * from .origin import *
from .rainbow_factory 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]): class MetaOrigin(Generic[Mentioned]):

View File

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

View File

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

View File

@ -4,7 +4,7 @@ from typing import Iterable
from .hashpoint import * from .hashpoint import *
from .mentionable import * from .mentionable import *
__all__ = ('RecursiveMentionable',) __all__ = ("RecursiveMentionable",)
class RecursiveMentionable(Mentionable, abc.ABC): class RecursiveMentionable(Mentionable, abc.ABC):
@ -20,7 +20,7 @@ class RecursiveMentionable(Mentionable, abc.ABC):
async def str(self, tab: int) -> str: async def str(self, tab: int) -> str:
assert isinstance(tab, int) assert isinstance(tab, int)
return f'(recursive {self.__class__.__name__})' return f"(recursive {self.__class__.__name__})"
def __topology_hash__(self) -> bytes: 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 .rainbow_factory import *
from .resolverorigin 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]): class ResolverMetaOrigin(MetaOrigin[Mentioned], Generic[Mentioned]):

View File

@ -7,18 +7,13 @@ from .mentionable import *
from .origin import * from .origin import *
from .rainbow_factory 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]): class ResolverOrigin(Origin[Mentioned], Generic[Mentioned]):
def __init__( def __init__(self, factory: RainbowFactory[Mentioned], point: bytes, resolver: HashResolver):
self,
factory: RainbowFactory[Mentioned],
point: bytes,
resolver: HashResolver
):
assert isinstance(factory, RainbowFactory) assert isinstance(factory, RainbowFactory)
assert isinstance(point, bytes) assert isinstance(point, bytes)
assert isinstance(resolver, HashResolver) assert isinstance(resolver, HashResolver)

View File

@ -5,9 +5,12 @@ from .hashresolver import *
from .mentionable import * from .mentionable import *
from .rainbow_factory 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): class StaticMentionable(Mentionable, abc.ABC):

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -5,11 +5,11 @@ from rainbowadn.core import *
from ._mapper import * from ._mapper import *
from ._reduce import * from ._reduce import *
__all__ = ('MapReduce',) __all__ = ("MapReduce",)
Element = TypeVar('Element', contravariant=True) Element = TypeVar("Element", contravariant=True)
Mapped = TypeVar('Mapped') Mapped = TypeVar("Mapped")
Out = TypeVar('Out') Out = TypeVar("Out")
class MapReduce(Reduce[Element, Out], Generic[Element, Out, Mapped]): class MapReduce(Reduce[Element, Out], Generic[Element, Out, Mapped]):

View File

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

View File

@ -2,9 +2,9 @@ from typing import Generic, TypeVar
from ._reduce import * from ._reduce import *
__all__ = ('PureReduce',) __all__ = ("PureReduce",)
Pure = TypeVar('Pure') Pure = TypeVar("Pure")
class PureReduce(Reduce[Pure, Pure], Generic[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 * from rainbowadn.core import *
__all__ = ('Reduce',) __all__ = ("Reduce",)
Element = TypeVar('Element', contravariant=True) Element = TypeVar("Element", contravariant=True)
Out = TypeVar('Out') Out = TypeVar("Out")
class Reduce(Generic[Element, Out]): class Reduce(Generic[Element, Out]):

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -12,7 +12,7 @@ from ._flowblock import *
from ._flowcheque import * from ._flowcheque import *
from ._flowstandard import * from ._flowstandard import *
__all__ = ('BankBlock',) __all__ = ("BankBlock",)
Link: TypeAlias = IPair[FlowCheque, FlowBank] Link: TypeAlias = IPair[FlowCheque, FlowBank]
Block: TypeAlias = FlowBlock[Link] Block: TypeAlias = FlowBlock[Link]
@ -25,7 +25,7 @@ class BankBlock:
self.reference = reference self.reference = reference
@classmethod @classmethod
def flow(cls) -> 'BankFlow': def flow(cls) -> "BankFlow":
return BankFlow(FlowBank.empty()) return BankFlow(FlowBank.empty())
@classmethod @classmethod
@ -33,13 +33,8 @@ class BankBlock:
return IPair.f(FlowCheque.factory(), FlowBank.factory()) return IPair.f(FlowCheque.factory(), FlowBank.factory())
@classmethod @classmethod
def empty(cls) -> 'BankBlock': def empty(cls) -> "BankBlock":
return cls( return cls(NullableReference(Null(), FlowBlockFactory(cls.link_factory()).loose()))
NullableReference(
Null(),
FlowBlockFactory(cls.link_factory()).loose()
)
)
@classmethod @classmethod
def verification(cls) -> Verification[Index]: 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))) assert_true(await self.verification().verify(await FlowBlock.outer_of(self.link_factory(), self.reference)))
return True return True
async def add(self, cheque: FlowCheque) -> 'BankBlock': async def add(self, cheque: FlowCheque) -> "BankBlock":
assert isinstance(cheque, FlowCheque) assert isinstance(cheque, FlowCheque)
return await AddCheque(cheque).map(self) return await AddCheque(cheque).map(self)
class AddCheque( class AddCheque(Mapper[BankBlock, BankBlock]):
Mapper[BankBlock, BankBlock]
):
def __init__(self, cheque: FlowCheque): def __init__(self, cheque: FlowCheque):
assert isinstance(cheque, FlowCheque) assert isinstance(cheque, FlowCheque)
self.cheque = cheque self.cheque = cheque
@ -65,7 +58,7 @@ class AddCheque(
@classmethod @classmethod
async def _bank_for_link(cls, link: Nullable[Link]) -> Nullable[FlowBank]: async def _bank_for_link(cls, link: Nullable[Link]) -> Nullable[FlowBank]:
assert isinstance(link, Nullable) 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: async def _next_bank_for_bank(self, bank: Nullable[FlowBank]) -> FlowBank:
return await BankBlock.flow().add(bank, self.cheque) return await BankBlock.flow().add(bank, self.cheque)
@ -74,15 +67,9 @@ class AddCheque(
assert isinstance(bank, FlowBank) assert isinstance(bank, FlowBank)
return HashPoint.of(IPair.of(self.cheque, bank)) return HashPoint.of(IPair.of(self.cheque, bank))
async def _next_link_for_link( async def _next_link_for_link(self, link: Nullable[Link]) -> HashPoint[Link]:
self, link: Nullable[Link]
) -> HashPoint[Link]:
assert isinstance(link, Nullable) assert isinstance(link, Nullable)
return await self._link_for_bank( return await self._link_for_bank(await self._next_bank_for_bank(await self._bank_for_link(link)))
await self._next_bank_for_bank(
await self._bank_for_link(link)
)
)
@classmethod @classmethod
async def _add_link_to_reference( async def _add_link_to_reference(

View File

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

View File

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

View File

@ -1,3 +1,5 @@
from __future__ import annotations
from typing import Iterable from typing import Iterable
from rainbowadn.collection.comparison import * from rainbowadn.collection.comparison import *
@ -6,12 +8,12 @@ from rainbowadn.core import *
from ._flowstandard import * from ._flowstandard import *
from ._flowtransaction import * from ._flowtransaction import *
__all__ = ('FlowBank',) __all__ = ("FlowBank",)
class FlowBank(StaticMentionable, RecursiveMentionable): class FlowBank(StaticMentionable, RecursiveMentionable):
@classmethod @classmethod
def from_bytes(cls, source: bytes, resolver: HashResolver) -> 'FlowBank': def from_bytes(cls, source: bytes, resolver: HashResolver) -> FlowBank:
return FlowBank( return FlowBank(
FlowStandardFactory.of(FlowCoin.factory(), HashComparator(Fail())).from_bytes( FlowStandardFactory.of(FlowCoin.factory(), HashComparator(Fail())).from_bytes(
source[: HashPoint.HASH_LENGTH], resolver source[: HashPoint.HASH_LENGTH], resolver
@ -38,7 +40,7 @@ class FlowBank(StaticMentionable, RecursiveMentionable):
self.used = used self.used = used
@classmethod @classmethod
def empty(cls) -> 'FlowBank': def empty(cls) -> FlowBank:
return FlowBank( return FlowBank(
FlowStandardFactory.empty(FlowCoin.factory(), HashComparator(Fail())), FlowStandardFactory.empty(FlowCoin.factory(), HashComparator(Fail())),
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: async def str(self, tab: int) -> str:
assert isinstance(tab, int) assert isinstance(tab, int)
return f'(' \ return (
f'{tabulate(tab + 1)}bank' \ f"("
f'{tabulate(tab + 1)}(minted)' \ f"{tabulate(tab + 1)}bank"
f'{tabulate(tab + 1)}(used)' \ f"{tabulate(tab + 1)}(minted)"
f'{tabulate(tab)})' 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.collection.comparison import *
from rainbowadn.core import * from rainbowadn.core import *
@ -7,9 +9,14 @@ from rainbowadn.nullability import *
from ._flowstandard 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): class FlowBlock(Generic[LinkT], RecursiveMentionable):
@ -19,13 +26,13 @@ class FlowBlock(Generic[LinkT], RecursiveMentionable):
def __bytes__(self): def __bytes__(self):
return bytes(self.previous) + bytes(self.index) + bytes(self.link) 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) return FlowBlockFactory(self.link.factory)
def __init__( def __init__(
self, self,
previous: NullableReference['FBL'], previous: NullableReference[FBL],
index: 'Index', index: Index,
link: HashPoint[LinkT], link: HashPoint[LinkT],
): ):
assert isinstance(previous, NullableReference) assert isinstance(previous, NullableReference)
@ -34,69 +41,50 @@ class FlowBlock(Generic[LinkT], RecursiveMentionable):
self.index = index self.index = index
self.link = link self.link = link
async def outer(self) -> 'Index': async def outer(self) -> Index:
return FlowStandard( return FlowStandard((await self.index.protocolized.tree.add(HashPoint.of(self))).protocolized())
(
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) assert_eq(await self.outer(), index)
return True return True
@classmethod @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(): if reference.null():
return FlowStandardFactory.empty(FlowBlockFactory(factory), HashComparator(Fail())) return FlowStandardFactory.empty(FlowBlockFactory(factory), HashComparator(Fail()))
else: else:
return await (await reference.resolve()).outer() return await (await reference.resolve()).outer()
@classmethod @classmethod
async def link_of(cls, reference: NullableReference['FBL']) -> Nullable[LinkT]: async def link_of(cls, reference: NullableReference[FBL]) -> Nullable[LinkT]:
if reference.null(): if reference.null():
return Null() return Null()
else: else:
return NotNull(await (await reference.resolve()).link.resolve()) return NotNull(await (await reference.resolve()).link.resolve())
async def add(self, link: HashPoint[LinkT]) -> 'FBL': async def add(self, link: HashPoint[LinkT]) -> FBL:
return FlowBlock( return FlowBlock(NullableReference.off(self), await self.outer(), link)
NullableReference.off(self),
await self.outer(),
link
)
@classmethod @classmethod
async def add_to(cls, reference: NullableReference['FBL'], link: HashPoint[LinkT]) -> 'FBL': async def add_to(cls, reference: NullableReference[FBL], link: HashPoint[LinkT]) -> FBL:
return FlowBlock( return FlowBlock(reference, await cls.outer_of(link.factory, reference), link)
reference,
await cls.outer_of(link.factory, reference),
link
)
async def str(self, tab: int) -> str: async def str(self, tab: int) -> str:
assert isinstance(tab, int) assert isinstance(tab, int)
previous_str: str previous_str: str
link_str: str link_str: str
previous_str, link_str = await gather( previous_str, link_str = await gather(self.previous.str(tab), hash_point_format(self.link, tab))
self.previous.str(tab),
hash_point_format(self.link, tab)
)
assert isinstance(previous_str, str) assert isinstance(previous_str, str)
assert isinstance(link_str, str) assert isinstance(link_str, str)
return f'{previous_str}' \ return f"{previous_str}" f"{tabulate(tab)}(index)" f"{tabulate(tab)}{link_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]): def __init__(self, factory: RainbowFactory[LinkT]):
assert isinstance(factory, RainbowFactory) assert isinstance(factory, RainbowFactory)
self.factory = factory 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(source, bytes)
assert isinstance(resolver, HashResolver) assert isinstance(resolver, HashResolver)
return FlowBlock( return FlowBlock(
@ -107,18 +95,15 @@ class FlowBlockFactory(RainbowFactory['FBL'], Generic[LinkT]):
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 return self
FBL: TypeAlias = 'FlowBlock[LinkT]' FBL: TypeAlias = FlowBlock[LinkT]
Index: TypeAlias = FlowStandard[FBL] Index: TypeAlias = FlowStandard[FBL]
class FlowBlockIndexedVerification( class FlowBlockIndexedVerification(Verification[HashPoint[FBL]], Generic[LinkT]):
Verification[HashPoint[FBL]],
Generic[LinkT]
):
def __init__( def __init__(
self, self,
index: Index, index: Index,
@ -133,9 +118,7 @@ class FlowBlockIndexedVerification(
assert isinstance(block, FlowBlock) assert isinstance(block, FlowBlock)
assert_trues( assert_trues(
await gather( await gather(
self.verification.verify( self.verification.verify((Null(), block.link)),
(Null(), block.link)
),
block.index.verify_empty(), block.index.verify_empty(),
) )
) )
@ -146,9 +129,7 @@ class FlowBlockIndexedVerification(
assert isinstance(block, FlowBlock) assert isinstance(block, FlowBlock)
assert_trues( assert_trues(
await gather( await gather(
self.verification.verify( self.verification.verify((NotNull(previous.link), block.link)),
(NotNull(previous.link), block.link)
),
previous.verify_outer_matches(block.index), previous.verify_outer_matches(block.index),
) )
) )
@ -175,10 +156,7 @@ class FlowBlockIndexedVerification(
return self return self
class FlowBlockVerification( class FlowBlockVerification(Verification[Index], Generic[LinkT]):
Verification[Index],
Generic[LinkT]
):
def __init__( def __init__(
self, self,
verification: Verification[tuple[Nullable[HashPoint[LinkT]], HashPoint[LinkT]]], verification: Verification[tuple[Nullable[HashPoint[LinkT]], HashPoint[LinkT]]],
@ -188,9 +166,7 @@ class FlowBlockVerification(
async def verify(self, element: Index) -> bool: async def verify(self, element: Index) -> bool:
assert_true( assert_true(
await ReduceVerification( await ReduceVerification(FlowBlockIndexedVerification(element, self.verification).loose()).verify(
FlowBlockIndexedVerification(element, self.verification).loose()
).verify(
await element.reducer() await element.reducer()
) )
) )
@ -202,7 +178,6 @@ class FlowBlockVerification(
class FBVF(Generic[LinkT]): class FBVF(Generic[LinkT]):
def make( def make(
self, self, verification: Verification[tuple[Nullable[HashPoint[LinkT]], HashPoint[LinkT]]]
verification: Verification[tuple[Nullable[HashPoint[LinkT]], HashPoint[LinkT]]]
) -> Verification[Index]: ) -> Verification[Index]:
return FlowBlockVerification(verification) return FlowBlockVerification(verification)

View File

@ -1,3 +1,5 @@
from __future__ import annotations
import itertools import itertools
from typing import Iterable from typing import Iterable
@ -13,7 +15,7 @@ from ._flowstandard import *
from ._flowtransaction import * from ._flowtransaction import *
from ._resolvemapper import * from ._resolvemapper import *
__all__ = ('FlowCheque',) __all__ = ("FlowCheque",)
class SumReduce(PureReduce[int]): class SumReduce(PureReduce[int]):
@ -29,7 +31,7 @@ class ValueMapper(Mapper[HashPoint[FlowCoin], int]):
class FlowCheque(StaticMentionable, RecursiveMentionable): class FlowCheque(StaticMentionable, RecursiveMentionable):
@classmethod @classmethod
def from_bytes(cls, source: bytes, resolver: HashResolver) -> 'FlowCheque': def from_bytes(cls, source: bytes, resolver: HashResolver) -> FlowCheque:
return FlowCheque( return FlowCheque(
FlowStandardFactory.of(FlowTransaction.factory(), HashComparator(Fail())).from_bytes( FlowStandardFactory.of(FlowTransaction.factory(), HashComparator(Fail())).from_bytes(
source[: HashPoint.HASH_LENGTH], resolver source[: HashPoint.HASH_LENGTH], resolver
@ -41,11 +43,8 @@ class FlowCheque(StaticMentionable, RecursiveMentionable):
source[2 * HashPoint.HASH_LENGTH : 3 * HashPoint.HASH_LENGTH], resolver source[2 * HashPoint.HASH_LENGTH : 3 * HashPoint.HASH_LENGTH], resolver
), ),
FlowStandardFactory.of( FlowStandardFactory.of(
KeyValue.f(FlowCoin.factory(), FlowTransaction.factory()), KeyValue.f(FlowCoin.factory(), FlowTransaction.factory()), KeyedComparator(HashComparator(Fail()))
KeyedComparator(HashComparator(Fail())) ).from_bytes(source[3 * HashPoint.HASH_LENGTH :], resolver),
).from_bytes(
source[3 * HashPoint.HASH_LENGTH:], resolver
),
) )
def points(self) -> Iterable[HashPoint]: def points(self) -> Iterable[HashPoint]:
@ -108,27 +107,19 @@ class FlowCheque(StaticMentionable, RecursiveMentionable):
return True return True
async def _verify_transactions(self) -> bool: async def _verify_transactions(self) -> bool:
assert_true( assert_true(await self.transactions.verify(TransactionVerification(self).loose()))
await self.transactions.verify(TransactionVerification(self).loose())
)
return True return True
async def _verify_minted(self) -> bool: async def _verify_minted(self) -> bool:
assert_true( assert_true(await self.minted.verify(MintedVerification(self).loose()))
await self.minted.verify(MintedVerification(self).loose())
)
return True return True
async def _verify_used(self) -> bool: async def _verify_used(self) -> bool:
assert_true( assert_true(await self.used.verify(UsedVerification(self).loose()))
await self.used.verify(UsedVerification(self).loose())
)
return True return True
async def _verify_usedx(self) -> bool: async def _verify_usedx(self) -> bool:
assert_true( assert_true(await self.usedx.verify(UsedXVerification(self).loose()))
await self.usedx.verify(UsedXVerification(self).loose())
)
return True return True
async def verify(self) -> bool: async def verify(self) -> bool:
@ -156,22 +147,14 @@ class FlowCheque(StaticMentionable, RecursiveMentionable):
@classmethod @classmethod
async def _transaction_usedx(cls, transaction: FlowTransaction) -> Iterable[KeyValue[FlowCoin, FlowTransaction]]: async def _transaction_usedx(cls, transaction: FlowTransaction) -> Iterable[KeyValue[FlowCoin, FlowTransaction]]:
assert isinstance(transaction, FlowTransaction) assert isinstance(transaction, FlowTransaction)
return ( return (KeyValue.of(coin, transaction) for coin in await cls._transaction_used(transaction))
KeyValue.of(coin, transaction)
for
coin
in
await cls._transaction_used(transaction)
)
@classmethod @classmethod
async def _make_minted(cls, transactions: Iterable[FlowTransaction]) -> FlowStandard[FlowCoin]: async def _make_minted(cls, transactions: Iterable[FlowTransaction]) -> FlowStandard[FlowCoin]:
return await FlowStandardFactory.off( return await FlowStandardFactory.off(
FlowCoin.factory(), FlowCoin.factory(),
HashComparator(Fail()), HashComparator(Fail()),
itertools.chain( itertools.chain(*(await gather(*(cls._transaction_minted(transaction) for transaction in transactions)))),
*(await gather(*(cls._transaction_minted(transaction) for transaction in transactions)))
)
) )
@classmethod @classmethod
@ -179,26 +162,21 @@ class FlowCheque(StaticMentionable, RecursiveMentionable):
return await FlowStandardFactory.off( return await FlowStandardFactory.off(
FlowCoin.factory(), FlowCoin.factory(),
HashComparator(Fail()), HashComparator(Fail()),
itertools.chain( itertools.chain(*(await gather(*(cls._transaction_used(transaction) for transaction in transactions)))),
*(await gather(*(cls._transaction_used(transaction) for transaction in transactions)))
),
) )
@classmethod @classmethod
async def _make_usedx( async def _make_usedx(
cls, cls, transactions: Iterable[FlowTransaction]
transactions: Iterable[FlowTransaction]
) -> FlowStandard[KeyValue[FlowCoin, FlowTransaction]]: ) -> FlowStandard[KeyValue[FlowCoin, FlowTransaction]]:
return await FlowStandardFactory.off( return await FlowStandardFactory.off(
KeyValue.f(FlowCoin.factory(), FlowTransaction.factory()), KeyValue.f(FlowCoin.factory(), FlowTransaction.factory()),
KeyedComparator(HashComparator(Fail())), KeyedComparator(HashComparator(Fail())),
itertools.chain( itertools.chain(*(await gather(*(cls._transaction_usedx(transaction) for transaction in transactions)))),
*(await gather(*(cls._transaction_usedx(transaction) for transaction in transactions)))
)
) )
@classmethod @classmethod
async def make(cls, transactions: Iterable[FlowTransaction]) -> 'FlowCheque': async def make(cls, transactions: Iterable[FlowTransaction]) -> FlowCheque:
transactions_standard: FlowStandard[FlowTransaction] transactions_standard: FlowStandard[FlowTransaction]
minted: FlowStandard[FlowCoin] minted: FlowStandard[FlowCoin]
used: FlowStandard[FlowCoin] used: FlowStandard[FlowCoin]
@ -222,13 +200,15 @@ class FlowCheque(StaticMentionable, RecursiveMentionable):
async def str(self, tab: int) -> str: async def str(self, tab: int) -> str:
assert isinstance(tab, int) assert isinstance(tab, int)
return f'(' \ return (
f'{tabulate(tab + 1)}cheque' \ f"("
f'{tabulate(tab + 1)}{await self.transactions.str(tab + 1)}' \ f"{tabulate(tab + 1)}cheque"
f'{tabulate(tab + 1)}(minted)' \ f"{tabulate(tab + 1)}{await self.transactions.str(tab + 1)}"
f'{tabulate(tab + 1)}(used)' \ f"{tabulate(tab + 1)}(minted)"
f'{tabulate(tab + 1)}(usedx)' \ f"{tabulate(tab + 1)}(used)"
f'{tabulate(tab)})' f"{tabulate(tab + 1)}(usedx)"
f"{tabulate(tab)})"
)
class UsedxMapper(Mapper[HashPoint[FlowCoin], HashPoint[KeyValue[FlowCoin, FlowTransaction]]]): 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 self.transaction = transaction
async def map(self, element: HashPoint[FlowCoin]) -> HashPoint[KeyValue[FlowCoin, FlowTransaction]]: async def map(self, element: HashPoint[FlowCoin]) -> HashPoint[KeyValue[FlowCoin, FlowTransaction]]:
return HashPoint.of( return HashPoint.of(await KeyValue.off(element, self.transaction))
await KeyValue.off(
element,
self.transaction
)
)
class TransactionVerification( class TransactionVerification(Verification[HashPoint[FlowTransaction]]):
Verification[HashPoint[FlowTransaction]]
):
def __init__(self, cheque: FlowCheque): def __init__(self, cheque: FlowCheque):
assert isinstance(cheque, FlowCheque) assert isinstance(cheque, FlowCheque)
self.cheque = cheque self.cheque = cheque
@classmethod @classmethod
def _usedx_reducer( def _usedx_reducer(
cls, cls, reducer: Reducer[HashPoint[FlowCoin], bool], transaction: HashPoint[FlowTransaction]
reducer: Reducer[HashPoint[FlowCoin], bool],
transaction: HashPoint[FlowTransaction]
) -> Reducer[HashPoint[KeyValue[FlowCoin, FlowTransaction]], bool]: ) -> Reducer[HashPoint[KeyValue[FlowCoin, FlowTransaction]], bool]:
assert isinstance(reducer, Reducer) assert isinstance(reducer, Reducer)
assert isinstance(transaction, HashPoint) assert isinstance(transaction, HashPoint)
usedx_reducer: Reducer[HashPoint[KeyValue[FlowCoin, FlowTransaction]], bool] = MapReducer( usedx_reducer: Reducer[HashPoint[KeyValue[FlowCoin, FlowTransaction]], bool] = MapReducer(
UsedxMapper(transaction), UsedxMapper(transaction), reducer
reducer
) )
assert isinstance(usedx_reducer, Reducer) assert isinstance(usedx_reducer, Reducer)
return usedx_reducer return usedx_reducer
async def _verify_transaction_minted(self, transaction: FlowTransaction) -> bool: async def _verify_transaction_minted(self, transaction: FlowTransaction) -> bool:
assert isinstance(transaction, FlowTransaction) assert isinstance(transaction, FlowTransaction)
assert_true( assert_true(await self.cheque.minted.verify_contains_all(await transaction.minted_reducer()))
await self.cheque.minted.verify_contains_all(
await transaction.minted_reducer()
)
)
return True return True
async def _verify_transaction_used(self, transaction: FlowTransaction) -> bool: async def _verify_transaction_used(self, transaction: FlowTransaction) -> bool:
assert isinstance(transaction, FlowTransaction) assert isinstance(transaction, FlowTransaction)
assert_true( assert_true(await self.cheque.used.verify_contains_all(await transaction.used_reducer()))
await self.cheque.used.verify_contains_all(
await transaction.used_reducer()
)
)
return True return True
async def _verify_transaction_usedx(self, transaction: FlowTransaction) -> bool: async def _verify_transaction_usedx(self, transaction: FlowTransaction) -> bool:
@ -313,30 +275,21 @@ class TransactionVerification(
return self return self
class MintedVerification( class MintedVerification(Verification[HashPoint[FlowCoin]]):
Verification[HashPoint[FlowCoin]]
):
def __init__(self, cheque: FlowCheque): def __init__(self, cheque: FlowCheque):
assert isinstance(cheque, FlowCheque) assert isinstance(cheque, FlowCheque)
self.cheque = cheque self.cheque = cheque
async def verify(self, element: HashPoint[FlowCoin]) -> bool: async def verify(self, element: HashPoint[FlowCoin]) -> bool:
assert isinstance(element, HashPoint) assert isinstance(element, HashPoint)
assert_true( assert_true(await self.cheque.transactions.contains((await element.resolve()).transaction, exact=True))
await self.cheque.transactions.contains(
(await element.resolve()).transaction,
exact=True
)
)
return True return True
def loose(self) -> Verification[HashPoint[FlowCoin]]: def loose(self) -> Verification[HashPoint[FlowCoin]]:
return self return self
class UsedVerification( class UsedVerification(Verification[HashPoint[FlowCoin]]):
Verification[HashPoint[FlowCoin]]
):
def __init__(self, cheque: FlowCheque): def __init__(self, cheque: FlowCheque):
assert isinstance(cheque, FlowCheque) assert isinstance(cheque, FlowCheque)
self.cheque = cheque self.cheque = cheque
@ -345,8 +298,7 @@ class UsedVerification(
assert isinstance(element, HashPoint) assert isinstance(element, HashPoint)
assert_true( assert_true(
await self.cheque.usedx.contains( await self.cheque.usedx.contains(
HashPoint.of(await KeyValue.off(element, HashPoint.of(FlowTransaction.empty()))), HashPoint.of(await KeyValue.off(element, HashPoint.of(FlowTransaction.empty()))), exact=False
exact=False
) )
) )
return True return True
@ -355,21 +307,14 @@ class UsedVerification(
return self return self
class UsedXVerification( class UsedXVerification(Verification[HashPoint[KeyValue[FlowCoin, FlowTransaction]]]):
Verification[HashPoint[KeyValue[FlowCoin, FlowTransaction]]]
):
def __init__(self, cheque: FlowCheque): def __init__(self, cheque: FlowCheque):
assert isinstance(cheque, FlowCheque) assert isinstance(cheque, FlowCheque)
self.cheque = cheque self.cheque = cheque
async def _verify_transaction_registred(self, transaction: HashPoint[FlowTransaction]) -> bool: async def _verify_transaction_registred(self, transaction: HashPoint[FlowTransaction]) -> bool:
assert isinstance(transaction, HashPoint) assert isinstance(transaction, HashPoint)
assert_true( assert_true(await self.cheque.transactions.contains(transaction, exact=True))
await self.cheque.transactions.contains(
transaction,
exact=True
)
)
return True return True
@classmethod @classmethod
@ -378,22 +323,12 @@ class UsedXVerification(
) -> bool: ) -> bool:
assert isinstance(transaction, HashPoint) assert isinstance(transaction, HashPoint)
assert isinstance(coin, HashPoint) assert isinstance(coin, HashPoint)
assert_true( assert_true(await (await transaction.resolve()).data.in_coins.contains(coin, exact=True))
await (await transaction.resolve()).data.in_coins.contains(
coin,
exact=True
)
)
return True return True
async def _verify_coin_registred_as_used(self, coin: HashPoint[FlowCoin]) -> bool: async def _verify_coin_registred_as_used(self, coin: HashPoint[FlowCoin]) -> bool:
assert isinstance(coin, HashPoint) assert isinstance(coin, HashPoint)
assert_true( assert_true(await self.cheque.used.contains(coin, exact=True))
await self.cheque.used.contains(
coin,
exact=True
)
)
return True return True
async def _verify(self, pair: KeyValue[FlowCoin, FlowTransaction]): 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 * from rainbowadn.flow.core import *
__all__ = ('FlowIterate',) __all__ = ("FlowIterate",)
Element = TypeVar('Element') Element = TypeVar("Element")
class FlowIterate( class FlowIterate(Reduce[Element, Iterable[Element]], Generic[Element]):
Reduce[Element, Iterable[Element]],
Generic[Element]
):
def __init__(self): def __init__(self):
super().__init__(()) super().__init__(())
@ -32,8 +29,5 @@ class FlowIterate(
return self return self
@classmethod @classmethod
async def iterate( async def iterate(cls, reducer: Reducer[Element, Iterable[Element]]) -> Iterable[Element]:
cls,
reducer: Reducer[Element, Iterable[Element]]
) -> Iterable[Element]:
return await reducer.reduce(cls()) 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 typing import Any, Generic, Iterable, Optional, TypeAlias, TypeVar
from rainbowadn.atomic import * from rainbowadn.atomic import *
@ -15,29 +17,25 @@ from rainbowadn.nullability import *
from ._binaryflow import * from ._binaryflow import *
from ._flowtree import * from ._flowtree import *
__all__ = ('FlowStandard', 'FlowStandardFactory',) __all__ = (
"FlowStandard",
"FlowStandardFactory",
)
KeyT = TypeVar('KeyT', bound=Mentionable) KeyT = TypeVar("KeyT", bound=Mentionable)
ABT: TypeAlias = 'ActiveBinaryTree[KeyT, Integer]' ABT: TypeAlias = "ActiveBinaryTree[KeyT, Integer]"
BP: TypeAlias = 'BinaryProtocolized[KeyT, Integer, ABT]' BP: TypeAlias = "BinaryProtocolized[KeyT, Integer, ABT]"
class FlowStandard( class FlowStandard(RecursiveMentionable, FlowTree[HashPoint[KeyT], "FS"], Generic[KeyT]):
RecursiveMentionable,
FlowTree[HashPoint[KeyT], 'FS'],
Generic[KeyT]
):
def points(self) -> Iterable[HashPoint]: def points(self) -> Iterable[HashPoint]:
return self.protocolized.tree.reference.points() return self.protocolized.tree.reference.points()
def __bytes__(self): def __bytes__(self):
return bytes(self.protocolized.tree.reference) return bytes(self.protocolized.tree.reference)
def __factory__(self) -> RainbowFactory['FlowStandard[KeyT]']: def __factory__(self) -> RainbowFactory[FlowStandard[KeyT]]:
return FlowStandardFactory( return FlowStandardFactory(self.protocolized.tree.reference.factory, self.protocolized.creation.comparator)
self.protocolized.tree.reference.factory,
self.protocolized.creation.comparator
)
def __init__(self, protocolized: BP): def __init__(self, protocolized: BP):
assert isinstance(protocolized, BinaryProtocolized) assert isinstance(protocolized, BinaryProtocolized)
@ -46,27 +44,21 @@ class FlowStandard(
async def contains(self, key: HashPoint[KeyT], *, exact: bool) -> bool: async def contains(self, key: HashPoint[KeyT], *, exact: bool) -> bool:
return await self.protocolized.tree.contains(key, exact=exact) return await self.protocolized.tree.contains(key, exact=exact)
def _protocolized(self: 'FS') -> BP: def _protocolized(self: FS) -> BP:
return self.protocolized return self.protocolized
@classmethod @classmethod
def _protocolized_mapper(cls) -> Mapper['FS', BP]: def _protocolized_mapper(cls) -> Mapper[FS, BP]:
return CallableMapper(FlowStandard._protocolized) 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) assert isinstance(trees, Reducer)
reducer: Reducer[BP, CheckResult] = MapReducer(self._protocolized_mapper(), trees) reducer: Reducer[BP, CheckResult] = MapReducer(self._protocolized_mapper(), trees)
assert_true(await VerifySubsetAction(reducer).on(self.protocolized)) assert_true(await VerifySubsetAction(reducer).on(self.protocolized))
return True return True
async def verify_empty(self) -> bool: async def verify_empty(self) -> bool:
assert_true( assert_true(await ReduceVerification(MapperVerification(ConstMapper(False))).verify(await self.reducer()))
await ReduceVerification(
MapperVerification(ConstMapper(False))
).verify(
await self.reducer()
)
)
return True return True
async def reducer(self) -> Reducer[HashPoint[KeyT], Any]: async def reducer(self) -> Reducer[HashPoint[KeyT], Any]:
@ -83,37 +75,30 @@ class FlowStandard(
return await self.protocolized.tree.reference.str(tab) return await self.protocolized.tree.reference.str(tab)
FS: TypeAlias = 'FlowStandard[KeyT]' FS: TypeAlias = "FlowStandard[KeyT]"
class FlowStandardFactory(Inlining[FlowStandard[KeyT]], Generic[KeyT]): class FlowStandardFactory(Inlining[FlowStandard[KeyT]], Generic[KeyT]):
def __init__( def __init__(self, factory: RainbowFactory[BinaryTree[KeyMetadata[KeyT, Integer]]], comparator: Comparator[KeyT]):
self,
factory: RainbowFactory[BinaryTree[KeyMetadata[KeyT, Integer]]],
comparator: Comparator[KeyT]
):
assert isinstance(factory, RainbowFactory) assert isinstance(factory, RainbowFactory)
assert isinstance(comparator, Comparator) assert isinstance(comparator, Comparator)
self.factory: RainbowFactory[ self.factory: RainbowFactory[NullableReference[BinaryTree[KeyMetadata[KeyT, Integer]]]] = NullableReference.f(
NullableReference[BinaryTree[KeyMetadata[KeyT, Integer]]] factory
] = NullableReference.f(factory) )
self.comparator = comparator self.comparator = comparator
def size(self) -> Optional[int]: def size(self) -> Optional[int]:
return Inlining.factory_size(self.factory) return Inlining.factory_size(self.factory)
@classmethod @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) assert isinstance(factory, RainbowFactory)
return FlowStandardFactory( return FlowStandardFactory(BinaryTreeFactory(KeyMetadataFactory(factory, Integer.factory())), comparator)
BinaryTreeFactory(KeyMetadataFactory(factory, Integer.factory())),
comparator
)
@classmethod @classmethod
async def off( async def off(
cls, factory: RainbowFactory[KeyT], comparator: Comparator[KeyT], keys: Iterable[KeyT] cls, factory: RainbowFactory[KeyT], comparator: Comparator[KeyT], keys: Iterable[KeyT]
) -> 'FlowStandard[KeyT]': ) -> FlowStandard[KeyT]:
assert isinstance(factory, RainbowFactory) assert isinstance(factory, RainbowFactory)
abt: ActiveBinaryTree[KeyT, Integer] = cls.empty(factory, comparator).protocolized.tree abt: ActiveBinaryTree[KeyT, Integer] = cls.empty(factory, comparator).protocolized.tree
for key in keys: for key in keys:
@ -125,18 +110,13 @@ class FlowStandardFactory(Inlining[FlowStandard[KeyT]], Generic[KeyT]):
return AVL(comparator) return AVL(comparator)
@classmethod @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) assert isinstance(factory, RainbowFactory)
return FlowStandard( return FlowStandard(ActiveBinaryTree.empty(cls.protocol(comparator), factory).protocolized())
ActiveBinaryTree.empty(cls.protocol(comparator), factory).protocolized()
)
def from_bytes(self, source: bytes, resolver: HashResolver) -> FlowStandard[KeyT]: def from_bytes(self, source: bytes, resolver: HashResolver) -> FlowStandard[KeyT]:
assert isinstance(source, bytes) assert isinstance(source, bytes)
assert isinstance(resolver, HashResolver) assert isinstance(resolver, HashResolver)
return FlowStandard( return FlowStandard(
ActiveBinaryTree( ActiveBinaryTree(self.protocol(self.comparator), self.factory.from_bytes(source, resolver)).protocolized()
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 typing import Any, Iterable
from nacl.signing import SigningKey from nacl.signing import SigningKey
@ -13,15 +15,16 @@ from rainbowadn.v13 import *
from ._flowstandard import * from ._flowstandard import *
from ._resolvemapper import * from ._resolvemapper import *
__all__ = ('FlowCoinData', 'FlowCoin', 'FlowTransactionData', 'FlowTransaction',) __all__ = (
"FlowCoinData",
"FlowCoin",
"FlowTransactionData",
"FlowTransaction",
)
class FlowCoinData(RecursiveMentionable, StaticMentionable): class FlowCoinData(RecursiveMentionable, StaticMentionable):
def __init__( def __init__(self, owner: Subject, value: HashPoint[Integer]):
self,
owner: Subject,
value: HashPoint[Integer]
):
assert isinstance(owner, Subject) assert isinstance(owner, Subject)
assert isinstance(value, HashPoint) assert isinstance(value, HashPoint)
self.owner = owner self.owner = owner
@ -35,7 +38,7 @@ class FlowCoinData(RecursiveMentionable, StaticMentionable):
return (await self.value.resolve()).integer return (await self.value.resolve()).integer
@classmethod @classmethod
def of(cls, owner: Subject, value: int) -> 'FlowCoinData': def of(cls, owner: Subject, value: int) -> FlowCoinData:
assert isinstance(owner, Subject) assert isinstance(owner, Subject)
assert isinstance(value, int) assert isinstance(value, int)
return cls(owner, HashPoint.of(Integer(value))) return cls(owner, HashPoint.of(Integer(value)))
@ -47,7 +50,7 @@ class FlowCoinData(RecursiveMentionable, StaticMentionable):
return bytes(self.owner) + bytes(self.value) return bytes(self.owner) + bytes(self.value)
@classmethod @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(source, bytes)
assert isinstance(resolver, HashResolver) assert isinstance(resolver, HashResolver)
separation = Subject.size() separation = Subject.size()
@ -58,16 +61,11 @@ class FlowCoinData(RecursiveMentionable, StaticMentionable):
async def str(self, tab: int) -> str: async def str(self, tab: int) -> str:
assert isinstance(tab, int) assert isinstance(tab, int)
return f'{self.owner}' \ return f"{self.owner}" f"{tabulate(tab)}{await hash_point_format(self.value, tab)}"
f'{tabulate(tab)}{await hash_point_format(self.value, tab)}'
class FlowCoin(RecursiveMentionable, StaticMentionable): class FlowCoin(RecursiveMentionable, StaticMentionable):
def __init__( def __init__(self, data: HashPoint[FlowCoinData], transaction: HashPoint[FlowTransaction]):
self,
data: HashPoint[FlowCoinData],
transaction: HashPoint['FlowTransaction']
):
assert isinstance(data, HashPoint) assert isinstance(data, HashPoint)
assert isinstance(transaction, HashPoint) assert isinstance(transaction, HashPoint)
self.data = data self.data = data
@ -87,7 +85,7 @@ class FlowCoin(RecursiveMentionable, StaticMentionable):
return bytes(self.data) + bytes(self.transaction) return bytes(self.data) + bytes(self.transaction)
@classmethod @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(source, bytes)
assert isinstance(resolver, HashResolver) assert isinstance(resolver, HashResolver)
return cls( return cls(
@ -99,11 +97,13 @@ class FlowCoin(RecursiveMentionable, StaticMentionable):
async def str(self, tab: int) -> str: async def str(self, tab: int) -> str:
assert isinstance(tab, int) assert isinstance(tab, int)
return f'(' \ return (
f'{tabulate(tab + 1)}coin' \ f"("
f'{tabulate(tab + 1)}{await hash_point_format(self.data, tab + 1)}' \ f"{tabulate(tab + 1)}coin"
f'{tabulate(tab + 1)}(origin)' \ f"{tabulate(tab + 1)}{await hash_point_format(self.data, tab + 1)}"
f'{tabulate(tab)})' f"{tabulate(tab + 1)}(origin)"
f"{tabulate(tab)})"
)
async def int_value(self) -> int: async def int_value(self) -> int:
return await (await self.data_resolved()).int_value() return await (await self.data_resolved()).int_value()
@ -132,45 +132,34 @@ class FlowTransactionData(RecursiveMentionable, StaticMentionable):
return bytes(self.in_coins) + bytes(self.out_coins) return bytes(self.in_coins) + bytes(self.out_coins)
@classmethod @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(source, bytes)
assert isinstance(resolver, HashResolver) assert isinstance(resolver, HashResolver)
return cls( return cls(
FlowStandardFactory.of( FlowStandardFactory.of(FlowCoin.factory(), HashComparator(Fail())).from_bytes(
FlowCoin.factory(), HashComparator(Fail()) source[: HashPoint.HASH_LENGTH], resolver
).from_bytes(source[:HashPoint.HASH_LENGTH], resolver), ),
FlowStandardFactory.of( FlowStandardFactory.of(FlowCoinData.factory(), HashComparator(Fail())).from_bytes(
FlowCoinData.factory(), HashComparator(Fail()) source[HashPoint.HASH_LENGTH :], resolver
).from_bytes(source[HashPoint.HASH_LENGTH:], resolver), ),
) )
async def _signature_verify(self, coin: FlowCoin, signature: Signature) -> bool: async def _signature_verify(self, coin: FlowCoin, signature: Signature) -> bool:
assert isinstance(coin, FlowCoin) assert isinstance(coin, FlowCoin)
assert isinstance(signature, Signature) assert isinstance(signature, Signature)
assert_true( assert_true(signature.verify(await coin.owner(), self.hash_point))
signature.verify(
await coin.owner(),
self.hash_point
)
)
return True return True
@classmethod @classmethod
def _coin_verification_mapper( def _coin_verification_mapper(
cls, cls,
signatures: FlowStandard[KeyValue[Subject, Signature]], signatures: FlowStandard[KeyValue[Subject, Signature]],
) -> Mapper[ ) -> Mapper[HashPoint[FlowCoin], bool]:
HashPoint[FlowCoin],
bool
]:
assert isinstance(signatures, FlowStandard) assert isinstance(signatures, FlowStandard)
return ResolveMapper.wrap_mapper(CVMapper(signatures).loose()) return ResolveMapper.wrap_mapper(CVMapper(signatures).loose())
def _signature_pair_verification_mapper(self) -> Mapper[ def _signature_pair_verification_mapper(self) -> Mapper[HashPoint[KeyValue[Subject, Signature]], bool]:
HashPoint[KeyValue[Subject, Signature]],
bool
]:
return ResolveMapper.wrap_mapper(SPVMapper(self.hash_point).loose()) return ResolveMapper.wrap_mapper(SPVMapper(self.hash_point).loose())
async def _verify_coin_signatures( async def _verify_coin_signatures(
@ -179,11 +168,9 @@ class FlowTransactionData(RecursiveMentionable, StaticMentionable):
) -> bool: ) -> bool:
assert isinstance(signatures, FlowStandard) assert isinstance(signatures, FlowStandard)
assert_true( assert_true(
await ReduceVerification( await ReduceVerification(MapperVerification(self._coin_verification_mapper(signatures)))
MapperVerification(self._coin_verification_mapper(signatures)) .loose()
).loose().verify( .verify(await self.in_coins.reducer())
await self.in_coins.reducer()
)
) )
return True return True
@ -193,11 +180,9 @@ class FlowTransactionData(RecursiveMentionable, StaticMentionable):
): ):
assert isinstance(signatures, FlowStandard) assert isinstance(signatures, FlowStandard)
assert_true( assert_true(
await ReduceVerification( await ReduceVerification(MapperVerification(self._signature_pair_verification_mapper()))
MapperVerification(self._signature_pair_verification_mapper()) .loose()
).loose().verify( .verify(await signatures.reducer())
await signatures.reducer()
)
) )
return True return True
@ -214,10 +199,7 @@ class FlowTransactionData(RecursiveMentionable, StaticMentionable):
) )
return True return True
async def verify( async def verify(self, signatures: FlowStandard[KeyValue[Subject, Signature]]) -> bool:
self,
signatures: FlowStandard[KeyValue[Subject, Signature]]
) -> bool:
assert isinstance(signatures, FlowStandard) assert isinstance(signatures, FlowStandard)
assert_true(await self._verify_signatures(signatures)) assert_true(await self._verify_signatures(signatures))
return True return True
@ -230,13 +212,10 @@ class FlowTransactionData(RecursiveMentionable, StaticMentionable):
) )
assert isinstance(in_str, str) assert isinstance(in_str, str)
assert isinstance(out_str, str) assert isinstance(out_str, str)
return f'(in)' \ return f"(in)" f"{tabulate(tab)}{in_str}" f"{tabulate(tab)}(out)" f"{tabulate(tab)}{out_str}"
f'{tabulate(tab)}{in_str}' \
f'{tabulate(tab)}(out)' \
f'{tabulate(tab)}{out_str}'
@classmethod @classmethod
def empty(cls) -> 'FlowTransactionData': def empty(cls) -> FlowTransactionData:
return cls( return cls(
FlowStandardFactory.empty(FlowCoin.factory(), HashComparator(Fail())), FlowStandardFactory.empty(FlowCoin.factory(), HashComparator(Fail())),
FlowStandardFactory.empty(FlowCoinData.factory(), HashComparator(Fail())), FlowStandardFactory.empty(FlowCoinData.factory(), HashComparator(Fail())),
@ -252,8 +231,7 @@ class CVMapper(Mapper[FlowCoin, bool]):
assert isinstance(element, FlowCoin) assert isinstance(element, FlowCoin)
assert_true( assert_true(
await self.signatures.contains( await self.signatures.contains(
HashPoint.of(KeyValue.of(await element.owner(), Signature.empty())), HashPoint.of(KeyValue.of(await element.owner(), Signature.empty())), exact=False
exact=False
) )
) )
return True return True
@ -285,11 +263,7 @@ class SPVMapper(Mapper[KeyValue[Subject, Signature], bool]):
class FlowTransaction(RecursiveMentionable, StaticMentionable): class FlowTransaction(RecursiveMentionable, StaticMentionable):
def __init__( def __init__(self, data: FlowTransactionData, signatures: FlowStandard[KeyValue[Subject, Signature]]):
self,
data: FlowTransactionData,
signatures: FlowStandard[KeyValue[Subject, Signature]]
):
assert isinstance(data, FlowTransactionData) assert isinstance(data, FlowTransactionData)
assert isinstance(signatures, FlowStandard) assert isinstance(signatures, FlowStandard)
self.data = data self.data = data
@ -308,17 +282,14 @@ class FlowTransaction(RecursiveMentionable, StaticMentionable):
return bytes(self.data) + bytes(self.signatures) return bytes(self.data) + bytes(self.signatures)
@classmethod @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(source, bytes)
assert isinstance(resolver, HashResolver) assert isinstance(resolver, HashResolver)
return cls( return cls(
FlowTransactionData.from_bytes(source[: -HashPoint.HASH_LENGTH], resolver), FlowTransactionData.from_bytes(source[: -HashPoint.HASH_LENGTH], resolver),
FlowStandardFactory.of( FlowStandardFactory.of(
KeyValue.f(Subject.factory(), Signature.factory()), KeyValue.f(Subject.factory(), Signature.factory()), KeyedComparator(HashComparator(Fail()))
KeyedComparator(HashComparator(Fail())) ).from_bytes(source[-HashPoint.HASH_LENGTH :], resolver),
).from_bytes(
source[-HashPoint.HASH_LENGTH:], resolver
),
) )
def _coin(self, data: HashPoint[FlowCoinData]) -> HashPoint[FlowCoin]: def _coin(self, data: HashPoint[FlowCoinData]) -> HashPoint[FlowCoin]:
@ -337,11 +308,13 @@ class FlowTransaction(RecursiveMentionable, StaticMentionable):
async def str(self, tab: int) -> str: async def str(self, tab: int) -> str:
assert isinstance(tab, int) assert isinstance(tab, int)
return f'(' \ return (
f'{tabulate(tab + 1)}transaction' \ f"("
f'{tabulate(tab + 1)}{await self.data.str(tab + 1)}' \ f"{tabulate(tab + 1)}transaction"
f'{tabulate(tab + 1)}(signatures)' \ f"{tabulate(tab + 1)}{await self.data.str(tab + 1)}"
f'{tabulate(tab)})' f"{tabulate(tab + 1)}(signatures)"
f"{tabulate(tab)})"
)
@classmethod @classmethod
def empty(cls): def empty(cls):
@ -358,7 +331,7 @@ class FlowTransaction(RecursiveMentionable, StaticMentionable):
used: Iterable[FlowCoin], used: Iterable[FlowCoin],
minted: Iterable[FlowCoinData], minted: Iterable[FlowCoinData],
keys: Iterable[SigningKey], keys: Iterable[SigningKey],
) -> 'FlowTransaction': ) -> FlowTransaction:
used_std: FlowStandard[FlowCoin] used_std: FlowStandard[FlowCoin]
minted_std: FlowStandard[FlowCoinData] minted_std: FlowStandard[FlowCoinData]
used_std, minted_std = await gather( used_std, minted_std = await gather(
@ -376,14 +349,11 @@ class FlowTransaction(RecursiveMentionable, StaticMentionable):
Subject(signing_key.verify_key), Subject(signing_key.verify_key),
Signature.sign(signing_key, transaction_data.hash_point), Signature.sign(signing_key, transaction_data.hash_point),
) )
for for signing_key in keys
signing_key
in
keys
] ]
return cls( return cls(
transaction_data, transaction_data,
await FlowStandardFactory.off( await FlowStandardFactory.off(
KeyValue.f(Subject.factory(), Signature.factory()), KeyedComparator(HashComparator(Fail())), signatures 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 typing import Any, Generic, TypeVar
from rainbowadn.core import * from rainbowadn.core import *
from rainbowadn.flow.core import * from rainbowadn.flow.core import *
from rainbowadn.flow.verification.core import * from rainbowadn.flow.verification.core import *
__all__ = ('FlowTree',) __all__ = ("FlowTree",)
Key = TypeVar('Key') Key = TypeVar("Key")
Tree = TypeVar('Tree') Tree = TypeVar("Tree")
class FlowTree(Generic[Key, Tree]): class FlowTree(Generic[Key, Tree]):
@ -28,7 +30,7 @@ class FlowTree(Generic[Key, Tree]):
assert_true(await ReduceVerification(key_verification).loose().verify(keys)) assert_true(await ReduceVerification(key_verification).loose().verify(keys))
return True 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 raise NotImplementedError
async def reducer(self) -> Reducer[Key, Any]: async def reducer(self) -> Reducer[Key, Any]:
@ -36,13 +38,7 @@ class FlowTree(Generic[Key, Tree]):
async def verify(self, verification: Verification[Key]) -> bool: async def verify(self, verification: Verification[Key]) -> bool:
assert isinstance(verification, Verification) assert isinstance(verification, Verification)
assert_true( assert_true(await ReduceVerification(verification).loose().verify(await self.reducer()))
await ReduceVerification(
verification
).loose().verify(
await self.reducer()
)
)
return True return True

View File

@ -4,9 +4,9 @@ from rainbowadn.core import *
from ._flowstandard 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]: 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.core import *
from rainbowadn.flow.core import * from rainbowadn.flow.core import *
__all__ = ('ResolveMapper',) __all__ = ("ResolveMapper",)
MentionedT = TypeVar('MentionedT', bound=Mentionable) MentionedT = TypeVar("MentionedT", bound=Mentionable)
Out = TypeVar('Out') Out = TypeVar("Out")
class ResolveMapper(Mapper[HashPoint[MentionedT], MentionedT], Generic[MentionedT]): class ResolveMapper(Mapper[HashPoint[MentionedT], MentionedT], Generic[MentionedT]):

View File

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

View File

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

View File

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

View File

@ -1,6 +1,8 @@
from __future__ import annotations
from .iatomic import * from .iatomic import *
__all__ = ('IByte',) __all__ = ("IByte",)
class IByte(IAtomic): class IByte(IAtomic):
@ -14,7 +16,7 @@ class IByte(IAtomic):
return 1 return 1
@classmethod @classmethod
def _from_bytes(cls, source: bytes) -> 'IByte': def _from_bytes(cls, source: bytes) -> IByte:
assert isinstance(source, bytes) assert isinstance(source, bytes)
[value] = source [value] = source
return IByte(value) return IByte(value)
@ -23,4 +25,4 @@ class IByte(IAtomic):
return bytes([self.value]) return bytes([self.value])
def __str__(self): 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 * 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] _FTuple: TypeAlias = tuple[int, Callable[[bytes, HashResolver], HashPoint], int]
_HTuple: TypeAlias = tuple[int, Callable[[], Coroutine[Any, Any, bytes]]] _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 typing import Generic, TypeVar
from rainbowadn.core import * from rainbowadn.core import *
from .iauto import * from .iauto import *
__all__ = ('IPair',) __all__ = ("IPair",)
E0 = TypeVar('E0', bound=Mentionable) E0 = TypeVar("E0", bound=Mentionable)
E1 = TypeVar('E1', bound=Mentionable) E1 = TypeVar("E1", bound=Mentionable)
class IPair(IAuto, Generic[E0, E1]): class IPair(IAuto, Generic[E0, E1]):
@ -19,19 +21,19 @@ class IPair(IAuto, Generic[E0, E1]):
self.e0, self.e1 = self.hashpoints() self.e0, self.e1 = self.hashpoints()
@classmethod @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(e0, HashPoint)
assert isinstance(e1, HashPoint) assert isinstance(e1, HashPoint)
return await cls.auto_off(e0, e1) return await cls.auto_off(e0, e1)
@classmethod @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(v0, Mentionable)
assert isinstance(v1, Mentionable) assert isinstance(v1, Mentionable)
return cls.auto_of(v0, v1) return cls.auto_of(v0, v1)
@classmethod @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(f0, RainbowFactory)
assert isinstance(f1, RainbowFactory) assert isinstance(f1, RainbowFactory)
return cls.auto_f(f0, f1) return cls.auto_f(f0, f1)

View File

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

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