From 8915fc6afa6c80718ce3bb687421de3c22b597f2 Mon Sep 17 00:00:00 2001 From: timofey Date: Mon, 2 Oct 2023 19:07:57 +0000 Subject: [PATCH] refactor --- main.py | 12 +- plot.py | 46 ++--- rainbowadn/atomic/__init__.py | 6 +- rainbowadn/atomic/atomic.py | 6 +- rainbowadn/atomic/integer.py | 10 +- rainbowadn/atomic/plain.py | 8 +- rainbowadn/collection/collectioninterface.py | 13 +- rainbowadn/collection/comparison/__init__.py | 25 ++- .../collection/comparison/comparator.py | 11 +- .../collection/comparison/hashcomparator.py | 4 +- .../collection/comparison/keyedcomparator.py | 12 +- .../collection/comparison/plaincomparator.py | 2 +- .../comparison/protocolcomparator.py | 4 +- rainbowadn/collection/keyed.py | 4 +- rainbowadn/collection/keymetadata.py | 28 +-- rainbowadn/collection/keyvalue.py | 18 +- rainbowadn/collection/linear/__init__.py | 7 +- rainbowadn/collection/linear/_array.py | 46 ++--- .../collection/linear/treelist/__init__.py | 5 +- .../collection/linear/treelist/tlnode.py | 59 +++--- .../linear/treelist/tlparametres.py | 24 +-- .../collection/linear/treelist/tlroot.py | 41 ++-- .../linear/treelist/tlrparametres.py | 14 +- .../collection/trees/binary/__init__.py | 7 +- .../trees/binary/actions/__init__.py | 20 +- .../trees/binary/actions/binaryaction.py | 23 +-- .../trees/binary/actions/compareaction.py | 31 +-- .../trees/binary/actions/stdactions.py | 163 +++++----------- .../trees/binary/actions/symmetric.py | 87 +++------ .../trees/binary/activebinarytree.py | 102 ++++------ rainbowadn/collection/trees/binary/avl.py | 95 ++++------ .../collection/trees/binary/binarytree.py | 34 ++-- .../collection/trees/binary/core/__init__.py | 14 +- .../trees/binary/core/balancedcreation.py | 30 +-- .../trees/binary/core/binarybalancing.py | 16 +- .../trees/binary/core/binarycreation.py | 14 +- .../trees/binary/core/binarymetadata.py | 30 +-- .../trees/binary/core/binaryprotocolized.py | 18 +- .../trees/binary/core/binarysplit.py | 18 +- .../binary/core/protocolizedbinarysplit.py | 33 ++-- rainbowadn/core/__init__.py | 68 ++++--- rainbowadn/core/asserts.py | 11 +- rainbowadn/core/extendableresolver.py | 8 +- rainbowadn/core/gather.py | 52 +++--- rainbowadn/core/hashpoint.py | 26 ++- rainbowadn/core/hashpointformat.py | 11 +- rainbowadn/core/hashresolver.py | 6 +- rainbowadn/core/localmetaorigin.py | 4 +- rainbowadn/core/localorigin.py | 4 +- rainbowadn/core/mentionable.py | 4 +- rainbowadn/core/metaorigin.py | 4 +- rainbowadn/core/origin.py | 4 +- rainbowadn/core/rainbow_factory.py | 4 +- rainbowadn/core/recursivementionable.py | 6 +- rainbowadn/core/resolvermetaorigin.py | 4 +- rainbowadn/core/resolverorigin.py | 15 +- rainbowadn/core/static.py | 7 +- rainbowadn/encryption/__init__.py | 3 +- rainbowadn/encryption/encrypted.py | 113 +++++------ rainbowadn/flow/bridge/__init__.py | 4 +- rainbowadn/flow/bridge/_listbridge.py | 11 +- rainbowadn/flow/core/__init__.py | 16 +- rainbowadn/flow/core/_callablemapper.py | 11 +- rainbowadn/flow/core/_composition.py | 13 +- rainbowadn/flow/core/_mapper.py | 6 +- rainbowadn/flow/core/_mapreduce.py | 20 +- rainbowadn/flow/core/_mapreducer.py | 8 +- rainbowadn/flow/core/_purereduce.py | 4 +- rainbowadn/flow/core/_reduce.py | 18 +- rainbowadn/flow/core/_reducer.py | 6 +- rainbowadn/flow/primitive/__init__.py | 4 +- rainbowadn/flow/primitive/_constmapper.py | 6 +- rainbowadn/flow/primitive/_unitreducer.py | 11 +- rainbowadn/flow/verification/core/__init__.py | 10 +- .../core/_compositionverification.py | 11 +- .../verification/core/_mapperverification.py | 4 +- .../verification/core/_reduceverification.py | 9 +- .../flow/verification/core/_verification.py | 9 +- .../flow/verification/core/_verifyreduce.py | 2 +- .../flow/verification/stateverification.py | 22 +-- rainbowadn/flow13/__init__.py | 22 ++- rainbowadn/flow13/_bankblock.py | 47 ++--- rainbowadn/flow13/_bankflow.py | 44 ++--- rainbowadn/flow13/_binaryflow.py | 25 ++- rainbowadn/flow13/_flowbank.py | 30 +-- rainbowadn/flow13/_flowblock.py | 113 +++++------ rainbowadn/flow13/_flowcheque.py | 161 +++++----------- rainbowadn/flow13/_flowiterate.py | 14 +- rainbowadn/flow13/_flowstandard.py | 76 +++----- rainbowadn/flow13/_flowtransaction.py | 176 ++++++++---------- rainbowadn/flow13/_flowtree.py | 18 +- rainbowadn/flow13/_flowunion.py | 4 +- rainbowadn/flow13/_resolvemapper.py | 6 +- rainbowadn/inlining/__init__.py | 19 +- rainbowadn/inlining/iatomic.py | 6 +- rainbowadn/inlining/iauto.py | 112 ++++++----- rainbowadn/inlining/ibyte.py | 8 +- rainbowadn/inlining/inlining.py | 4 +- rainbowadn/inlining/ipair.py | 14 +- rainbowadn/inlining/iref.py | 12 +- rainbowadn/inlining/istatic.py | 7 +- rainbowadn/inlining/iunit.py | 10 +- rainbowadn/instrument/__init__.py | 15 +- rainbowadn/instrument/_measure.py | 2 +- rainbowadn/instrument/_terminate.py | 2 +- rainbowadn/instrument/classreport.py | 6 +- rainbowadn/instrument/concurrency.py | 2 +- rainbowadn/instrument/counter.py | 2 +- rainbowadn/instrument/entryexit.py | 2 +- rainbowadn/instrument/instrumentation.py | 12 +- rainbowadn/nullability/__init__.py | 9 +- rainbowadn/nullability/notnull.py | 4 +- rainbowadn/nullability/null.py | 6 +- rainbowadn/nullability/nullable.py | 4 +- rainbowadn/nullability/nullablereference.py | 31 +-- rainbowadn/testing/resolvers/__init__.py | 10 +- .../testing/resolvers/cachingresolver.py | 4 +- .../testing/resolvers/defaultresolver.py | 2 +- .../testing/resolvers/delayedresolver.py | 6 +- rainbowadn/testing/resolvers/dictresolver.py | 12 +- rainbowadn/testing/resolvers/failresolver.py | 6 +- rainbowadn/testing/test_bridge.py | 4 +- rainbowadn/testing/test_encryption.py | 24 +-- rainbowadn/testing/test_inlining.py | 28 ++- rainbowadn/testing/test_trees.py | 38 ++-- rainbowadn/toplevel/__init__.py | 5 +- rainbowadn/toplevel/thresholdprotocol.py | 4 +- rainbowadn/toplevel/validreference.py | 8 +- rainbowadn/v13/__init__.py | 7 +- rainbowadn/v13/algo.py | 2 +- rainbowadn/v13/signature.py | 19 +- rainbowadn/v13/subject.py | 6 +- rainbowadn/wrisbt/__init__.py | 5 +- .../wrisbt/weakreferenceindexsetbtree.py | 121 +++++------- rainbowadn/wrisbt/wrisbtindex.py | 26 ++- rainbowadn/wrisbt/wrisbtparametres.py | 2 +- rainbowadn/wrisbt/wrisbtroot.py | 35 ++-- setup.py | 18 +- trace_common.py | 46 ++--- trace_flow.py | 81 ++++---- 140 files changed, 1412 insertions(+), 1831 deletions(-) diff --git a/main.py b/main.py index 4217ec6..ba9f354 100644 --- a/main.py +++ b/main.py @@ -7,20 +7,20 @@ class Print(Instrumentation): self.msg = msg def instrument(self, method, *args, **kwargs): - print(self.msg, end=' ') + print(self.msg, end=" ") return method(*args, **kwargs) class C: @classmethod def m(cls): - print('m') + print("m") -with Print(Instrumentation, '__exit__', 'exit'): - print1 = Print(C, 'm', '1') - print2 = Print(C, 'm', '2') - print3 = Print(C, 'm', '3') +with Print(Instrumentation, "__exit__", "exit"): + print1 = Print(C, "m", "1") + print2 = Print(C, "m", "2") + print3 = Print(C, "m", "3") C.m() print1.__enter__() C.m() diff --git a/plot.py b/plot.py index 9b99df2..d6e3e34 100644 --- a/plot.py +++ b/plot.py @@ -5,7 +5,7 @@ from typing import Any import matplotlib.pyplot as plt import numpy as np -__all__ = ('plot',) +__all__ = ("plot",) def plottable(log: list[tuple[float, int]]): @@ -18,7 +18,7 @@ def plottable(log: list[tuple[float, int]]): def format_params(params) -> str: match params: case dict(): - return '{' + ' '.join(f'{key}={format_params(value)}' for key, value in params.items()) + '}' + return "{" + " ".join(f"{key}={format_params(value)}" for key, value in params.items()) + "}" case list(): return f'[{" ".join(format_params(value) for value in params)}]' case _: @@ -26,42 +26,42 @@ def format_params(params) -> str: def plot(fn: str): - plt.rcParams['figure.figsize'] = [16, 9] - plt.style.use('dark_background') + plt.rcParams["figure.figsize"] = [16, 9] + plt.style.use("dark_background") plt.subplots_adjust(left=0.05, right=0.99, top=0.95, bottom=0.05) - plt.xlabel('time (s)') - plt.ylabel('concurrency (1)') + plt.xlabel("time (s)") + plt.ylabel("concurrency (1)") with open(fn) as file: jsonified: dict[str, Any] = json.load(file) title = fn - if (params := jsonified.pop('params', None)) is not None: - title += f' {format_params(params)}' + if (params := jsonified.pop("params", None)) is not None: + title += f" {format_params(params)}" plt.title(title) def logplot(plot_function, metric: str, **kwargs): if (log := jsonified.pop(metric, None)) is not None: - plot_function(*plottable(log), label=f'{metric} ({len(log)})', **kwargs) + plot_function(*plottable(log), label=f"{metric} ({len(log)})", **kwargs) - logplot(plt.plot, 'DelayedResolver:sleep:concurrency') - logplot(plt.plot, 'ActiveBinaryTree:add:concurrency') - logplot(plt.plot, 'ActiveBinaryTree:contains:concurrency') - logplot(plt.plot, 'FlowStandard:verify_subset:concurrency') - logplot(plt.plot, 'Stack:list:concurrency') - logplot(plt.scatter, 'ActiveBinaryTree:add:entry', c='tomato', zorder=100, s=.5) - logplot(plt.scatter, 'ActiveBinaryTree:add:exit', c='gold', zorder=99, s=.5) + logplot(plt.plot, "DelayedResolver:sleep:concurrency") + logplot(plt.plot, "ActiveBinaryTree:add:concurrency") + logplot(plt.plot, "ActiveBinaryTree:contains:concurrency") + logplot(plt.plot, "FlowStandard:verify_subset:concurrency") + logplot(plt.plot, "Stack:list:concurrency") + logplot(plt.scatter, "ActiveBinaryTree:add:entry", c="tomato", zorder=100, s=0.5) + logplot(plt.scatter, "ActiveBinaryTree:add:exit", c="gold", zorder=99, s=0.5) plt.legend() - plt.savefig(f'{fn}.png') + plt.savefig(f"{fn}.png") plt.show() plt.clf() -if __name__ == '__main__': - Path('trace').mkdir(exist_ok=True) - if Path('trace/latest.json').exists(): - plot('trace/latest.json') - for fp in list(Path('trace').glob('*.json')): - if fp != Path('trace/latest.json'): +if __name__ == "__main__": + Path("trace").mkdir(exist_ok=True) + if Path("trace/latest.json").exists(): + plot("trace/latest.json") + for fp in list(Path("trace").glob("*.json")): + if fp != Path("trace/latest.json"): plot(str(fp)) diff --git a/rainbowadn/atomic/__init__.py b/rainbowadn/atomic/__init__.py index 2278b91..4d7fa01 100644 --- a/rainbowadn/atomic/__init__.py +++ b/rainbowadn/atomic/__init__.py @@ -1,7 +1,7 @@ __all__ = ( - 'Atomic', - 'Integer', - 'Plain', + "Atomic", + "Integer", + "Plain", ) from .atomic import Atomic diff --git a/rainbowadn/atomic/atomic.py b/rainbowadn/atomic/atomic.py index ec9dc60..52532be 100644 --- a/rainbowadn/atomic/atomic.py +++ b/rainbowadn/atomic/atomic.py @@ -3,14 +3,14 @@ from typing import Type, TypeVar from rainbowadn.core import * -__all__ = ('Atomic',) +__all__ = ("Atomic",) -AtomicMentioned = TypeVar('AtomicMentioned', bound='Atomic') +AtomicMentioned = TypeVar("AtomicMentioned", bound="Atomic") class Atomic(StaticMentionable, abc.ABC): def __topology_hash__(self) -> bytes: - return HashPoint.hash(b'') + return HashPoint.hash(b"") @classmethod def from_bytes(cls: Type[AtomicMentioned], source: bytes, resolver: HashResolver) -> AtomicMentioned: diff --git a/rainbowadn/atomic/integer.py b/rainbowadn/atomic/integer.py index 49d5693..b1bdc68 100644 --- a/rainbowadn/atomic/integer.py +++ b/rainbowadn/atomic/integer.py @@ -1,6 +1,8 @@ +from __future__ import annotations + from .atomic import * -__all__ = ('Integer',) +__all__ = ("Integer",) class Integer(Atomic): @@ -10,14 +12,14 @@ class Integer(Atomic): self.integer = integer @classmethod - def _from_bytes(cls, source: bytes) -> 'Integer': + def _from_bytes(cls, source: bytes) -> Integer: assert isinstance(source, bytes) if source: assert source[-1] > 0 - return cls(int.from_bytes(source, 'little')) + return cls(int.from_bytes(source, "little")) def __bytes__(self): - return self.integer.to_bytes((self.integer.bit_length() + 7) // 8, 'little') + return self.integer.to_bytes((self.integer.bit_length() + 7) // 8, "little") def __str__(self): return str(self.integer) diff --git a/rainbowadn/atomic/plain.py b/rainbowadn/atomic/plain.py index 99d884e..521e6e8 100644 --- a/rainbowadn/atomic/plain.py +++ b/rainbowadn/atomic/plain.py @@ -1,6 +1,8 @@ +from __future__ import annotations + from .atomic import * -__all__ = ('Plain',) +__all__ = ("Plain",) class Plain(Atomic): @@ -9,7 +11,7 @@ class Plain(Atomic): self.source = source @classmethod - def _from_bytes(cls, source: bytes) -> 'Plain': + def _from_bytes(cls, source: bytes) -> Plain: assert isinstance(source, bytes) return cls(source) @@ -17,4 +19,4 @@ class Plain(Atomic): return self.source def __str__(self): - return self.source.decode(errors='replace') + return self.source.decode(errors="replace") diff --git a/rainbowadn/collection/collectioninterface.py b/rainbowadn/collection/collectioninterface.py index f1d3950..d56e18b 100644 --- a/rainbowadn/collection/collectioninterface.py +++ b/rainbowadn/collection/collectioninterface.py @@ -3,17 +3,12 @@ from typing import Generic, TypeVar from rainbowadn.core import * from rainbowadn.nullability import * -__all__ = ('CollectionInterface',) +__all__ = ("CollectionInterface",) -CollectionType = TypeVar('CollectionType', bound=Mentionable, covariant=True) +CollectionType = TypeVar("CollectionType", bound=Mentionable, covariant=True) -class CollectionInterface( - Generic[CollectionType] -): - def __init__( - self, - reference: NullableReference[CollectionType] - ): +class CollectionInterface(Generic[CollectionType]): + def __init__(self, reference: NullableReference[CollectionType]): assert isinstance(reference, NullableReference) self.reference = reference diff --git a/rainbowadn/collection/comparison/__init__.py b/rainbowadn/collection/comparison/__init__.py index 2ad009b..f6f90b3 100644 --- a/rainbowadn/collection/comparison/__init__.py +++ b/rainbowadn/collection/comparison/__init__.py @@ -1,13 +1,26 @@ __all__ = ( - 'Comparison', 'Left', 'Right', 'Equal', 'Replace', 'Fail', 'Duplicate', 'Comparator', - 'HashComparator', - 'KeyedComparator', - 'PlainComparator', + "Comparison", + "Left", + "Right", + "Equal", + "Replace", + "Fail", + "Duplicate", + "Comparator", + "HashComparator", + "KeyedComparator", + "PlainComparator", ) from .comparator import ( - Comparator, Comparison, Duplicate, Equal, Fail, Left, - Replace, Right + Comparator, + Comparison, + Duplicate, + Equal, + Fail, + Left, + Replace, + Right, ) from .hashcomparator import HashComparator from .keyedcomparator import KeyedComparator diff --git a/rainbowadn/collection/comparison/comparator.py b/rainbowadn/collection/comparison/comparator.py index 946d426..5c187dd 100644 --- a/rainbowadn/collection/comparison/comparator.py +++ b/rainbowadn/collection/comparison/comparator.py @@ -4,7 +4,14 @@ from typing import Generic, TypeVar from rainbowadn.core import * __all__ = ( - 'Comparison', 'Left', 'Right', 'Equal', 'Replace', 'Fail', 'Duplicate', 'Comparator', + "Comparison", + "Left", + "Right", + "Equal", + "Replace", + "Fail", + "Duplicate", + "Comparator", ) @@ -36,7 +43,7 @@ class Duplicate(Equal): pass -KeyType = TypeVar('KeyType', bound=Mentionable, contravariant=True) +KeyType = TypeVar("KeyType", bound=Mentionable, contravariant=True) class Comparator(Generic[KeyType]): diff --git a/rainbowadn/collection/comparison/hashcomparator.py b/rainbowadn/collection/comparison/hashcomparator.py index bccc434..d3812bd 100644 --- a/rainbowadn/collection/comparison/hashcomparator.py +++ b/rainbowadn/collection/comparison/hashcomparator.py @@ -5,9 +5,9 @@ from rainbowadn.core import * from .comparator import * from .protocolcomparator import * -__all__ = ('HashComparator',) +__all__ = ("HashComparator",) -KeyType = TypeVar('KeyType', bound=Mentionable, contravariant=True) +KeyType = TypeVar("KeyType", bound=Mentionable, contravariant=True) class HashComparator(ProtocolComparator[KeyType], Generic[KeyType]): diff --git a/rainbowadn/collection/comparison/keyedcomparator.py b/rainbowadn/collection/comparison/keyedcomparator.py index b8bf781..4dca608 100644 --- a/rainbowadn/collection/comparison/keyedcomparator.py +++ b/rainbowadn/collection/comparison/keyedcomparator.py @@ -5,23 +5,19 @@ from rainbowadn.core import * from .comparator import * -__all__ = ('KeyedComparator',) +__all__ = ("KeyedComparator",) -ComparatorKeyType = TypeVar('ComparatorKeyType', bound=Mentionable, contravariant=True) +ComparatorKeyType = TypeVar("ComparatorKeyType", bound=Mentionable, contravariant=True) -class KeyedComparator( - Comparator[Keyed[ComparatorKeyType]], Generic[ComparatorKeyType] -): +class KeyedComparator(Comparator[Keyed[ComparatorKeyType]], Generic[ComparatorKeyType]): def __init__(self, comparator: Comparator[ComparatorKeyType]): assert isinstance(comparator, Comparator) self.comparator = comparator super().__init__() async def compare( - self, - original: HashPoint[Keyed[ComparatorKeyType]], - key: HashPoint[Keyed[ComparatorKeyType]] + self, original: HashPoint[Keyed[ComparatorKeyType]], key: HashPoint[Keyed[ComparatorKeyType]] ) -> Comparison: assert isinstance(original, HashPoint) assert isinstance(key, HashPoint) diff --git a/rainbowadn/collection/comparison/plaincomparator.py b/rainbowadn/collection/comparison/plaincomparator.py index 1bffaa9..ff5c5c8 100644 --- a/rainbowadn/collection/comparison/plaincomparator.py +++ b/rainbowadn/collection/comparison/plaincomparator.py @@ -4,7 +4,7 @@ from rainbowadn.core import * from .comparator import * from .protocolcomparator import * -__all__ = ('PlainComparator',) +__all__ = ("PlainComparator",) class PlainComparator(ProtocolComparator[Plain]): diff --git a/rainbowadn/collection/comparison/protocolcomparator.py b/rainbowadn/collection/comparison/protocolcomparator.py index b2e18ea..a118c1d 100644 --- a/rainbowadn/collection/comparison/protocolcomparator.py +++ b/rainbowadn/collection/comparison/protocolcomparator.py @@ -5,9 +5,9 @@ from rainbowadn.core import * from .comparator import * -__all__ = ('ProtocolComparator',) +__all__ = ("ProtocolComparator",) -KeyType = TypeVar('KeyType', bound=Mentionable, contravariant=True) +KeyType = TypeVar("KeyType", bound=Mentionable, contravariant=True) class ProtocolComparator(Comparator[KeyType], abc.ABC, Generic[KeyType]): diff --git a/rainbowadn/collection/keyed.py b/rainbowadn/collection/keyed.py index 94c35a6..eab4d2c 100644 --- a/rainbowadn/collection/keyed.py +++ b/rainbowadn/collection/keyed.py @@ -3,9 +3,9 @@ from typing import Generic, TypeVar from rainbowadn.core import * -__all__ = ('Keyed',) +__all__ = ("Keyed",) -KKeyType = TypeVar('KKeyType', bound=Mentionable, covariant=True) +KKeyType = TypeVar("KKeyType", bound=Mentionable, covariant=True) class Keyed(RecursiveMentionable, Generic[KKeyType], abc.ABC): diff --git a/rainbowadn/collection/keymetadata.py b/rainbowadn/collection/keymetadata.py index 3d8a696..d72983b 100644 --- a/rainbowadn/collection/keymetadata.py +++ b/rainbowadn/collection/keymetadata.py @@ -1,13 +1,18 @@ +from __future__ import annotations + from typing import Generic, Iterable, TypeVar from rainbowadn.core import * from .keyed import * -__all__ = ('KeyMetadata', 'KeyMetadataFactory',) +__all__ = ( + "KeyMetadata", + "KeyMetadataFactory", +) -ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable, covariant=True) -MetaDataType = TypeVar('MetaDataType', bound=Mentionable, covariant=True) +ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable, covariant=True) +MetaDataType = TypeVar("MetaDataType", bound=Mentionable, covariant=True) class KeyMetadata(Keyed[ActiveKeyType], Generic[ActiveKeyType, MetaDataType]): @@ -23,24 +28,19 @@ class KeyMetadata(Keyed[ActiveKeyType], Generic[ActiveKeyType, MetaDataType]): def __bytes__(self): return bytes(self.key) + bytes(self.metadata) - def __factory__(self) -> RainbowFactory['KeyMetadata[ActiveKeyType, MetaDataType]']: + def __factory__(self) -> RainbowFactory[KeyMetadata[ActiveKeyType, MetaDataType]]: return KeyMetadataFactory(self.key.factory, self.metadata.factory) async def str(self, tab: int) -> str: assert isinstance(tab, int) - key_str, metadata_str = await gather( - hash_point_format(self.key, tab), - hash_point_format(self.metadata, tab) - ) + key_str, metadata_str = await gather(hash_point_format(self.key, tab), hash_point_format(self.metadata, tab)) assert isinstance(key_str, str) assert isinstance(metadata_str, str) - return f'{key_str}' \ - f'{tabulate(tab)}{metadata_str}' + return f"{key_str}" f"{tabulate(tab)}{metadata_str}" class KeyMetadataFactory( - RainbowFactory[KeyMetadata[ActiveKeyType, MetaDataType]], - Generic[ActiveKeyType, MetaDataType] + RainbowFactory[KeyMetadata[ActiveKeyType, MetaDataType]], Generic[ActiveKeyType, MetaDataType] ): def __init__(self, key_factory: RainbowFactory[ActiveKeyType], metadata_factory: RainbowFactory[MetaDataType]): assert isinstance(key_factory, RainbowFactory) @@ -52,8 +52,8 @@ class KeyMetadataFactory( assert isinstance(source, bytes) assert isinstance(resolver, HashResolver) return KeyMetadata( - ResolverOrigin(self.key_factory, source[:HashPoint.HASH_LENGTH], resolver).hash_point(), - ResolverOrigin(self.metadata_factory, source[HashPoint.HASH_LENGTH:], resolver).hash_point(), + ResolverOrigin(self.key_factory, source[: HashPoint.HASH_LENGTH], resolver).hash_point(), + ResolverOrigin(self.metadata_factory, source[HashPoint.HASH_LENGTH :], resolver).hash_point(), ) def loose(self) -> RainbowFactory[KeyMetadata[ActiveKeyType, MetaDataType]]: diff --git a/rainbowadn/collection/keyvalue.py b/rainbowadn/collection/keyvalue.py index f6b3be1..07449bc 100644 --- a/rainbowadn/collection/keyvalue.py +++ b/rainbowadn/collection/keyvalue.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from typing import Generic, TypeVar from rainbowadn.core import * @@ -5,10 +7,10 @@ from rainbowadn.inlining import * from .keyed import * -__all__ = ('KeyValue',) +__all__ = ("KeyValue",) -KVKeyType = TypeVar('KVKeyType', bound=Mentionable) -KVValueType = TypeVar('KVValueType', bound=Mentionable) +KVKeyType = TypeVar("KVKeyType", bound=Mentionable) +KVValueType = TypeVar("KVValueType", bound=Mentionable) class KeyValue(Keyed[KVKeyType], IAuto, Generic[KVKeyType, KVValueType]): @@ -20,23 +22,21 @@ class KeyValue(Keyed[KVKeyType], IAuto, Generic[KVKeyType, KVValueType]): Keyed.__init__(self, key) @classmethod - async def off( - cls, key: HashPoint[KVKeyType], value: HashPoint[KVValueType] - ) -> 'KeyValue[KVKeyType, KVValueType]': + async def off(cls, key: HashPoint[KVKeyType], value: HashPoint[KVValueType]) -> KeyValue[KVKeyType, KVValueType]: assert isinstance(key, HashPoint) assert isinstance(value, HashPoint) return await cls.auto_off(key, value) @classmethod - def of(cls, vk: KVKeyType, vv: KVValueType) -> 'KeyValue[KVKeyType, KVValueType]': + def of(cls, vk: KVKeyType, vv: KVValueType) -> KeyValue[KVKeyType, KVValueType]: assert isinstance(vk, Mentionable) assert isinstance(vv, Mentionable) return cls.auto_of(vk, vv) @classmethod def f( - cls, f0: RainbowFactory[KVKeyType], f1: RainbowFactory[KVValueType] - ) -> RainbowFactory['KeyValue[KVKeyType, KVValueType]']: + cls, f0: RainbowFactory[KVKeyType], f1: RainbowFactory[KVValueType] + ) -> RainbowFactory[KeyValue[KVKeyType, KVValueType]]: assert issubclass(cls, KeyValue) assert isinstance(f0, RainbowFactory) assert isinstance(f1, RainbowFactory) diff --git a/rainbowadn/collection/linear/__init__.py b/rainbowadn/collection/linear/__init__.py index cca475f..3b67dbc 100644 --- a/rainbowadn/collection/linear/__init__.py +++ b/rainbowadn/collection/linear/__init__.py @@ -1,6 +1,9 @@ __all__ = ( - 'Array', 'ArrayFactory', - 'TLRoot', 'TLRootFactory', 'TLRParametres', + "Array", + "ArrayFactory", + "TLRoot", + "TLRootFactory", + "TLRParametres", ) from ._array import Array, ArrayFactory diff --git a/rainbowadn/collection/linear/_array.py b/rainbowadn/collection/linear/_array.py index fc17670..1634dcc 100644 --- a/rainbowadn/collection/linear/_array.py +++ b/rainbowadn/collection/linear/_array.py @@ -2,17 +2,16 @@ from typing import Generic, Iterable, TypeVar from rainbowadn.core import * -__all__ = ('Array', 'ArrayFactory',) +__all__ = ( + "Array", + "ArrayFactory", +) -ElementType = TypeVar('ElementType', bound=Mentionable, covariant=True) +ElementType = TypeVar("ElementType", bound=Mentionable, covariant=True) class Array(RecursiveMentionable, Generic[ElementType]): - def __init__( - self, - factory: RainbowFactory[ElementType], - array: tuple[HashPoint[ElementType], ...] - ): + def __init__(self, factory: RainbowFactory[ElementType], array: tuple[HashPoint[ElementType], ...]): assert isinstance(factory, RainbowFactory) assert isinstance(array, tuple) self.factory = factory @@ -22,31 +21,23 @@ class Array(RecursiveMentionable, Generic[ElementType]): return self.array def __bytes__(self): - return b''.join(map(HashPoint.__bytes__, self.array)) + return b"".join(map(HashPoint.__bytes__, self.array)) - def __factory__(self) -> RainbowFactory['Array']: + def __factory__(self) -> RainbowFactory["Array"]: return ArrayFactory(self.factory) async def str(self, tab: int) -> str: assert isinstance(tab, int) - formatted = f'(' - formatted += ''.join( - f'{tabulate(tab + 1)}{hash_point_str}' - for hash_point_str in await gather( - *( - hash_point_format(hash_point, tab + 1) for hash_point in self.array - ) - ) + formatted = f"(" + formatted += "".join( + f"{tabulate(tab + 1)}{hash_point_str}" + for hash_point_str in await gather(*(hash_point_format(hash_point, tab + 1) for hash_point in self.array)) ) - return f'{formatted}' \ - f'{tabulate(tab)})' + return f"{formatted}" f"{tabulate(tab)})" class ArrayFactory(RainbowFactory[Array], Generic[ElementType]): - def __init__( - self, - factory: RainbowFactory[ElementType] - ): + def __init__(self, factory: RainbowFactory[ElementType]): assert isinstance(factory, RainbowFactory) self.factory = factory @@ -56,10 +47,7 @@ class ArrayFactory(RainbowFactory[Array], Generic[ElementType]): return Array( self.factory, tuple( - ResolverOrigin(self.factory, source[i:i + HashPoint.HASH_LENGTH], resolver).hash_point() - for - i - in - range(0, len(source), HashPoint.HASH_LENGTH) - ) + ResolverOrigin(self.factory, source[i : i + HashPoint.HASH_LENGTH], resolver).hash_point() + for i in range(0, len(source), HashPoint.HASH_LENGTH) + ), ) diff --git a/rainbowadn/collection/linear/treelist/__init__.py b/rainbowadn/collection/linear/treelist/__init__.py index bde1635..c592557 100644 --- a/rainbowadn/collection/linear/treelist/__init__.py +++ b/rainbowadn/collection/linear/treelist/__init__.py @@ -1,6 +1,7 @@ __all__ = ( - 'TLRoot', 'TLRootFactory', - 'TLRParametres', + "TLRoot", + "TLRootFactory", + "TLRParametres", ) from .tlroot import TLRoot, TLRootFactory diff --git a/rainbowadn/collection/linear/treelist/tlnode.py b/rainbowadn/collection/linear/treelist/tlnode.py index 4c1bf18..3a0e76f 100644 --- a/rainbowadn/collection/linear/treelist/tlnode.py +++ b/rainbowadn/collection/linear/treelist/tlnode.py @@ -1,21 +1,26 @@ +from __future__ import annotations + from typing import Generic, Iterable, TypeVar from rainbowadn.core import * from .tlparametres import * -__all__ = ('TLNode', 'TLNodeFactory',) +__all__ = ( + "TLNode", + "TLNodeFactory", +) -ElementType = TypeVar('ElementType', bound=Mentionable) +ElementType = TypeVar("ElementType", bound=Mentionable) class TLNode(RecursiveMentionable, Generic[ElementType]): def __init__( - self, - source: bytes, - parametres: TLParametres[ElementType], - node_cache: tuple[MetaOrigin['TLNode[ElementType]'], ...], - element_cache: tuple[MetaOrigin[ElementType], ...], + self, + source: bytes, + parametres: TLParametres[ElementType], + node_cache: tuple[MetaOrigin[TLNode[ElementType]], ...], + element_cache: tuple[MetaOrigin[ElementType], ...], ): assert isinstance(source, bytes) assert isinstance(parametres, TLParametres) @@ -37,7 +42,7 @@ class TLNode(RecursiveMentionable, Generic[ElementType]): def bytes_no(self, index: int) -> bytes: assert isinstance(index, int) assert index < self.parametres.branching - return self.source[HashPoint.HASH_LENGTH * index:HashPoint.HASH_LENGTH * (index + 1)] + return self.source[HashPoint.HASH_LENGTH * index : HashPoint.HASH_LENGTH * (index + 1)] def element_no(self, index: int) -> HashPoint[ElementType]: assert isinstance(index, int) @@ -45,18 +50,13 @@ class TLNode(RecursiveMentionable, Generic[ElementType]): meta_origin: MetaOrigin[ElementType] = self.element_cache[index] return meta_origin.hash_point(self.parametres.tlr.factory, self.bytes_no(index)) - def node_no(self, index: int) -> HashPoint['TLNode[ElementType]']: + def node_no(self, index: int) -> HashPoint[TLNode[ElementType]]: assert isinstance(index, int) assert index < self.nodes meta_origin: MetaOrigin[TLNode[ElementType]] = self.node_cache[index] - return meta_origin.hash_point( - TLNodeFactory( - self.parametres.params_no(index) - ), - self.bytes_no(index) - ) + return meta_origin.hash_point(TLNodeFactory(self.parametres.params_no(index)), self.bytes_no(index)) - async def node_no_resolved(self, index: int) -> 'TLNode[ElementType]': + async def node_no_resolved(self, index: int) -> TLNode[ElementType]: assert isinstance(index, int) assert index < self.nodes return await self.node_no(index).resolve() @@ -73,19 +73,17 @@ class TLNode(RecursiveMentionable, Generic[ElementType]): def __bytes__(self): return self.source - def __factory__(self) -> RainbowFactory['TLNode[ElementType]']: - return TLNodeFactory( - self.parametres - ) + def __factory__(self) -> RainbowFactory[TLNode[ElementType]]: + return TLNodeFactory(self.parametres) async def str(self, tab: int) -> str: assert isinstance(tab, int) if self.parametres.size == 0: - return f'-' + return f"-" else: - return f'{tabulate(tab)}'.join(await gather(*(hash_point_format(point, tab) for point in self.points()))) + return f"{tabulate(tab)}".join(await gather(*(hash_point_format(point, tab) for point in self.points()))) - def unit(self, element: HashPoint[ElementType]) -> 'TLNode[ElementType]': + def unit(self, element: HashPoint[ElementType]) -> TLNode[ElementType]: assert isinstance(element, HashPoint) return TLNode( bytes(element), @@ -95,13 +93,13 @@ class TLNode(RecursiveMentionable, Generic[ElementType]): ) def source_without_last(self) -> bytes: - return self.source[:-HashPoint.HASH_LENGTH] + return self.source[: -HashPoint.HASH_LENGTH] - async def last(self) -> 'TLNode[ElementType]': + async def last(self) -> TLNode[ElementType]: assert not self.parametres.leaf return await self.node_no_resolved(self.nodes - 1) - async def add(self, element: HashPoint[ElementType]) -> 'TLNode[ElementType]': + async def add(self, element: HashPoint[ElementType]) -> TLNode[ElementType]: assert isinstance(self, TLNode) assert isinstance(element, HashPoint) if self.parametres.full: @@ -114,7 +112,10 @@ class TLNode(RecursiveMentionable, Generic[ElementType]): return TLNode( bytes(self_hp) + bytes(unit_hp), self.parametres.superparams(), - (LocalMetaOrigin(self_hp.origin), LocalMetaOrigin(unit_hp.origin),), + ( + LocalMetaOrigin(self_hp.origin), + LocalMetaOrigin(unit_hp.origin), + ), (), ) elif self.parametres.leaf: @@ -150,8 +151,8 @@ class TLNode(RecursiveMentionable, Generic[ElementType]): class TLNodeFactory(RainbowFactory[TLNode[ElementType]], Generic[ElementType]): def __init__( - self, - parametres: TLParametres[ElementType], + self, + parametres: TLParametres[ElementType], ): assert isinstance(parametres, TLParametres) self.parametres = parametres diff --git a/rainbowadn/collection/linear/treelist/tlparametres.py b/rainbowadn/collection/linear/treelist/tlparametres.py index bdfb42c..1b143f2 100644 --- a/rainbowadn/collection/linear/treelist/tlparametres.py +++ b/rainbowadn/collection/linear/treelist/tlparametres.py @@ -1,21 +1,21 @@ +from __future__ import annotations + from typing import Generic, TypeVar from rainbowadn.core import * from .tlrparametres import * -__all__ = ('TLParametres',) +__all__ = ("TLParametres",) -ElementType = TypeVar('ElementType', bound=Mentionable) +ElementType = TypeVar("ElementType", bound=Mentionable) -class TLParametres( - Generic[ElementType] -): +class TLParametres(Generic[ElementType]): def __init__( - self, - tlr: TLRParametres[ElementType], - size: int, + self, + tlr: TLRParametres[ElementType], + size: int, ): assert isinstance(tlr, TLRParametres) assert isinstance(size, int) @@ -49,12 +49,12 @@ class TLParametres( return self.order ** (self.height + 1) def _subsize(self) -> int: - return self.order ** self.height + return self.order**self.height - def superparams(self) -> 'TLParametres[ElementType]': + def superparams(self) -> TLParametres[ElementType]: return TLParametres(self.tlr, self.size + 1) - def unit(self) -> 'TLParametres[ElementType]': + def unit(self) -> TLParametres[ElementType]: return TLParametres(self.tlr, 1) def _subsize_no(self, index: int) -> int: @@ -65,7 +65,7 @@ class TLParametres( else: return self.subsize - def params_no(self, index: int) -> 'TLParametres[ElementType]': + def params_no(self, index: int) -> TLParametres[ElementType]: assert isinstance(index, int) assert not self.leaf assert index < self.branching diff --git a/rainbowadn/collection/linear/treelist/tlroot.py b/rainbowadn/collection/linear/treelist/tlroot.py index d261a8f..3a1aa1c 100644 --- a/rainbowadn/collection/linear/treelist/tlroot.py +++ b/rainbowadn/collection/linear/treelist/tlroot.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from typing import Generic, Iterable, TypeVar from rainbowadn.atomic import * @@ -7,17 +9,16 @@ from .tlnode import * from .tlparametres import * from .tlrparametres import * -__all__ = ('TLRoot', 'TLRootFactory',) +__all__ = ( + "TLRoot", + "TLRootFactory", +) -ElementType = TypeVar('ElementType', bound=Mentionable) +ElementType = TypeVar("ElementType", bound=Mentionable) class TLRoot(RecursiveMentionable, Generic[ElementType]): - def __init__( - self, - node: HashPoint[TLNode[ElementType]], - parametres: TLParametres - ): + def __init__(self, node: HashPoint[TLNode[ElementType]], parametres: TLParametres): assert isinstance(node, HashPoint) assert isinstance(parametres, TLParametres) self.node = node @@ -29,19 +30,16 @@ class TLRoot(RecursiveMentionable, Generic[ElementType]): def __bytes__(self): return bytes(self.node) + bytes(Integer(self.parametres.size)) - def __factory__(self) -> RainbowFactory['TLRoot[ElementType]']: + def __factory__(self) -> RainbowFactory[TLRoot[ElementType]]: return TLRootFactory(self.parametres.tlr) async def node_resolved(self) -> TLNode[ElementType]: return await self.node.resolve() - async def add(self, element: HashPoint[ElementType]) -> 'TLRoot[ElementType]': + async def add(self, element: HashPoint[ElementType]) -> TLRoot[ElementType]: assert isinstance(element, HashPoint) node = await (await self.node_resolved()).add(element) - return TLRoot( - HashPoint.of(node), - node.parametres - ) + return TLRoot(HashPoint.of(node), node.parametres) async def str(self, tab: int) -> str: assert isinstance(tab, int) @@ -50,8 +48,8 @@ class TLRoot(RecursiveMentionable, Generic[ElementType]): class TLRootFactory(RainbowFactory[TLRoot[ElementType]]): def __init__( - self, - tlr: TLRParametres, + self, + tlr: TLRParametres, ): assert isinstance(tlr, TLRParametres) self.tlr = tlr @@ -59,19 +57,14 @@ class TLRootFactory(RainbowFactory[TLRoot[ElementType]]): def from_bytes(self, source: bytes, resolver: HashResolver) -> TLRoot[ElementType]: assert isinstance(source, bytes) assert isinstance(resolver, HashResolver) - size: int = Integer.from_bytes(source[HashPoint.HASH_LENGTH:], resolver).integer + size: int = Integer.from_bytes(source[HashPoint.HASH_LENGTH :], resolver).integer assert isinstance(size, int) parametres = TLParametres(self.tlr, size) return TLRoot( - ResolverOrigin( - TLNodeFactory(parametres), source[:HashPoint.HASH_LENGTH], resolver - ).hash_point(), - parametres + ResolverOrigin(TLNodeFactory(parametres), source[: HashPoint.HASH_LENGTH], resolver).hash_point(), + parametres, ) def empty(self) -> TLRoot[ElementType]: parametres = TLParametres(self.tlr, 0) - return TLRoot( - HashPoint.of(TLNode(b'', parametres, (), ())), - parametres - ) + return TLRoot(HashPoint.of(TLNode(b"", parametres, (), ())), parametres) diff --git a/rainbowadn/collection/linear/treelist/tlrparametres.py b/rainbowadn/collection/linear/treelist/tlrparametres.py index 8e9ea83..ce40fda 100644 --- a/rainbowadn/collection/linear/treelist/tlrparametres.py +++ b/rainbowadn/collection/linear/treelist/tlrparametres.py @@ -2,18 +2,16 @@ from typing import Generic, TypeVar from rainbowadn.core import * -__all__ = ('TLRParametres',) +__all__ = ("TLRParametres",) -ElementType = TypeVar('ElementType', bound=Mentionable) +ElementType = TypeVar("ElementType", bound=Mentionable) -class TLRParametres( - Generic[ElementType] -): +class TLRParametres(Generic[ElementType]): def __init__( - self, - order: int, - factory: RainbowFactory[ElementType], + self, + order: int, + factory: RainbowFactory[ElementType], ): assert isinstance(order, int) assert isinstance(factory, RainbowFactory) diff --git a/rainbowadn/collection/trees/binary/__init__.py b/rainbowadn/collection/trees/binary/__init__.py index 7ca31ec..1f07a91 100644 --- a/rainbowadn/collection/trees/binary/__init__.py +++ b/rainbowadn/collection/trees/binary/__init__.py @@ -1,7 +1,8 @@ __all__ = ( - 'ActiveBinaryTree', - 'AVL', - 'BinaryTree', 'BinaryTreeFactory', + "ActiveBinaryTree", + "AVL", + "BinaryTree", + "BinaryTreeFactory", ) from .activebinarytree import ActiveBinaryTree diff --git a/rainbowadn/collection/trees/binary/actions/__init__.py b/rainbowadn/collection/trees/binary/actions/__init__.py index a869715..8500c80 100644 --- a/rainbowadn/collection/trees/binary/actions/__init__.py +++ b/rainbowadn/collection/trees/binary/actions/__init__.py @@ -1,14 +1,18 @@ __all__ = ( - 'BinaryAction', - 'CompareAction', - 'AddAction', 'RemoveAction', 'ContainsAction', 'SplitAction', 'UnionAction', 'MergeAction', - 'Symmetric', 'InnerOuter', 'OuterInner', + "BinaryAction", + "CompareAction", + "AddAction", + "RemoveAction", + "ContainsAction", + "SplitAction", + "UnionAction", + "MergeAction", + "Symmetric", + "InnerOuter", + "OuterInner", ) from .binaryaction import BinaryAction from .compareaction import CompareAction -from .stdactions import ( - AddAction, ContainsAction, MergeAction, RemoveAction, - SplitAction, UnionAction -) +from .stdactions import AddAction, ContainsAction, MergeAction, RemoveAction, SplitAction, UnionAction from .symmetric import InnerOuter, OuterInner, Symmetric diff --git a/rainbowadn/collection/trees/binary/actions/binaryaction.py b/rainbowadn/collection/trees/binary/actions/binaryaction.py index 8fe3f2e..637d5c2 100644 --- a/rainbowadn/collection/trees/binary/actions/binaryaction.py +++ b/rainbowadn/collection/trees/binary/actions/binaryaction.py @@ -3,18 +3,18 @@ from typing import Generic, TypeVar from rainbowadn.collection.trees.binary.core import * from rainbowadn.core import * -__all__ = ('BinaryAction',) +__all__ = ("BinaryAction",) -TreeType = TypeVar('TreeType') -ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) -MetaDataType = TypeVar('MetaDataType', bound=Mentionable) -ActionType = TypeVar('ActionType') +TreeType = TypeVar("TreeType") +ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable) +MetaDataType = TypeVar("MetaDataType", bound=Mentionable) +ActionType = TypeVar("ActionType") class BinaryAction(Generic[ActiveKeyType, MetaDataType, TreeType, ActionType]): async def on( - self, - protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType], + self, + protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType], ) -> ActionType: assert isinstance(protocolized, BinaryProtocolized) if (split := await ProtocolizedBinarySplit.split_of(protocolized)) is None: @@ -24,13 +24,10 @@ class BinaryAction(Generic[ActiveKeyType, MetaDataType, TreeType, ActionType]): return await self.on_split(split) async def on_null( - self, - protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType], + self, + protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType], ) -> ActionType: raise NotImplementedError - async def on_split( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType] - ) -> ActionType: + async def on_split(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> ActionType: raise NotImplementedError diff --git a/rainbowadn/collection/trees/binary/actions/compareaction.py b/rainbowadn/collection/trees/binary/actions/compareaction.py index 2bff00a..5706d79 100644 --- a/rainbowadn/collection/trees/binary/actions/compareaction.py +++ b/rainbowadn/collection/trees/binary/actions/compareaction.py @@ -7,27 +7,24 @@ from rainbowadn.core import * from .binaryaction import * -__all__ = ('CompareAction',) +__all__ = ("CompareAction",) -TreeType = TypeVar('TreeType') -ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) -MetaDataType = TypeVar('MetaDataType', bound=Mentionable) -ActionType = TypeVar('ActionType') +TreeType = TypeVar("TreeType") +ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable) +MetaDataType = TypeVar("MetaDataType", bound=Mentionable) +ActionType = TypeVar("ActionType") class CompareAction( BinaryAction[ActiveKeyType, MetaDataType, TreeType, ActionType], Generic[ActiveKeyType, MetaDataType, TreeType, ActionType], - abc.ABC + abc.ABC, ): def __init__(self, key: HashPoint[ActiveKeyType]): assert isinstance(key, HashPoint) self.key = key - async def on_split( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType] - ) -> ActionType: + async def on_split(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> ActionType: assert isinstance(case, ProtocolizedBinarySplit) comparison: Comparison = await case.protocol.comparator.compare(case.split.key, self.key) assert isinstance(comparison, Comparison) @@ -41,20 +38,12 @@ class CompareAction( raise TypeError async def on_equal( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], - equal: Equal + self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], equal: Equal ) -> ActionType: raise NotImplementedError - async def on_left( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType] - ) -> ActionType: + async def on_left(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> ActionType: raise NotImplementedError - async def on_right( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType] - ) -> ActionType: + async def on_right(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> ActionType: raise NotImplementedError diff --git a/rainbowadn/collection/trees/binary/actions/stdactions.py b/rainbowadn/collection/trees/binary/actions/stdactions.py index 5c9c372..2f013cf 100644 --- a/rainbowadn/collection/trees/binary/actions/stdactions.py +++ b/rainbowadn/collection/trees/binary/actions/stdactions.py @@ -7,26 +7,25 @@ from rainbowadn.core import * from .binaryaction import * from .compareaction import * -__all__ = ('AddAction', 'RemoveAction', 'ContainsAction', 'SplitAction', 'UnionAction', 'MergeAction',) +__all__ = ( + "AddAction", + "RemoveAction", + "ContainsAction", + "SplitAction", + "UnionAction", + "MergeAction", +) -TreeType = TypeVar('TreeType') -ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) -MetaDataType = TypeVar('MetaDataType', bound=Mentionable) +TreeType = TypeVar("TreeType") +ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable) +MetaDataType = TypeVar("MetaDataType", bound=Mentionable) class AddAction( - CompareAction[ - ActiveKeyType, - MetaDataType, - TreeType, - TreeType - ], - Generic[ActiveKeyType, MetaDataType, TreeType] + CompareAction[ActiveKeyType, MetaDataType, TreeType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType] ): async def on_equal( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], - equal: Equal + self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], equal: Equal ) -> TreeType: assert isinstance(case, ProtocolizedBinarySplit) assert isinstance(equal, Equal) @@ -35,123 +34,70 @@ class AddAction( else: raise TypeError - async def on_left( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType] - ) -> TreeType: + async def on_left(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType: assert isinstance(case, ProtocolizedBinarySplit) - return await case.protocol.tree( - await self.on(case.protocolizedl()), - case.split.treer, - case.split.key - ) + return await case.protocol.tree(await self.on(case.protocolizedl()), case.split.treer, case.split.key) - async def on_right( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType] - ) -> TreeType: + async def on_right(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType: assert isinstance(case, ProtocolizedBinarySplit) - return await case.protocol.tree( - case.split.treel, - await self.on(case.protocolizedr()), - case.split.key - ) + return await case.protocol.tree(case.split.treel, await self.on(case.protocolizedr()), case.split.key) async def on_null( - self, - protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType], + self, + protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType], ) -> TreeType: assert isinstance(protocolized, BinaryProtocolized) return await protocolized.creation.tree(protocolized.tree, protocolized.tree, self.key) class MergeAction( - BinaryAction[ - ActiveKeyType, - MetaDataType, - TreeType, - TreeType - ], - Generic[ActiveKeyType, MetaDataType, TreeType] + BinaryAction[ActiveKeyType, MetaDataType, TreeType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType] ): def __init__(self, treer: TreeType): self.treer = treer async def on_null( - self, - protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType], + self, + protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType], ) -> TreeType: assert isinstance(protocolized, BinaryProtocolized) return self.treer - async def on_split( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType] - ) -> TreeType: + async def on_split(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType: assert isinstance(case, ProtocolizedBinarySplit) return await case.protocol.tree( - case.split.treel, - await MergeAction(self.treer).on(case.protocolizedr()), - case.split.key + case.split.treel, await MergeAction(self.treer).on(case.protocolizedr()), case.split.key ) class RemoveAction( - CompareAction[ - ActiveKeyType, - MetaDataType, - TreeType, - TreeType - ], - Generic[ActiveKeyType, MetaDataType, TreeType] + CompareAction[ActiveKeyType, MetaDataType, TreeType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType] ): async def on_equal( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], - equal: Equal + self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], equal: Equal ) -> TreeType: assert isinstance(case, ProtocolizedBinarySplit) assert isinstance(equal, Equal) return await MergeAction(case.split.treer).on(case.protocolizedl()) - async def on_left( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType] - ) -> TreeType: + async def on_left(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType: assert isinstance(case, ProtocolizedBinarySplit) - return await case.protocol.tree( - await self.on(case.protocolizedl()), - case.split.treer, - case.split.key - ) + return await case.protocol.tree(await self.on(case.protocolizedl()), case.split.treer, case.split.key) - async def on_right( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType] - ) -> TreeType: + async def on_right(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType: assert isinstance(case, ProtocolizedBinarySplit) - return await case.protocol.tree( - case.split.treel, - await self.on(case.protocolizedr()), - case.split.key - ) + return await case.protocol.tree(case.split.treel, await self.on(case.protocolizedr()), case.split.key) async def on_null( - self, - protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType], + self, + protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType], ) -> TreeType: assert isinstance(protocolized, BinaryProtocolized) return protocolized.tree class ContainsAction( - CompareAction[ - ActiveKeyType, - MetaDataType, - TreeType, - bool - ], - Generic[ActiveKeyType, MetaDataType, TreeType] + CompareAction[ActiveKeyType, MetaDataType, TreeType, bool], Generic[ActiveKeyType, MetaDataType, TreeType] ): def __init__(self, key: HashPoint[ActiveKeyType], *, exact: bool): assert isinstance(exact, bool) @@ -159,9 +105,7 @@ class ContainsAction( super().__init__(key) async def on_equal( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], - equal: Equal + self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], equal: Equal ) -> bool: assert isinstance(case, ProtocolizedBinarySplit) assert isinstance(equal, Equal) @@ -170,39 +114,28 @@ class ContainsAction( else: return True - async def on_left( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType] - ) -> bool: + async def on_left(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> bool: assert isinstance(case, ProtocolizedBinarySplit) return await self.on(case.protocolizedl()) - async def on_right( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType] - ) -> bool: + async def on_right(self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> bool: assert isinstance(case, ProtocolizedBinarySplit) return await self.on(case.protocolizedr()) async def on_null( - self, - protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType], + self, + protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType], ) -> bool: assert isinstance(protocolized, BinaryProtocolized) return False class SplitAction( - CompareAction[ - ActiveKeyType, - MetaDataType, - TreeType, - tuple[TreeType, TreeType] - ], - Generic[ActiveKeyType, MetaDataType, TreeType] + CompareAction[ActiveKeyType, MetaDataType, TreeType, tuple[TreeType, TreeType]], + Generic[ActiveKeyType, MetaDataType, TreeType], ): async def on_equal( - self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], equal: Equal + self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType], equal: Equal ) -> tuple[TreeType, TreeType]: if isinstance(equal, Replace): return case.split.treel, case.split.treer @@ -210,31 +143,25 @@ class SplitAction( raise TypeError async def on_left( - self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType] + self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType] ) -> tuple[TreeType, TreeType]: ll, lr = await self.on(case.protocolizedl()) return ll, await case.protocol.tree(lr, case.split.treer, case.split.key) async def on_right( - self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType] + self, case: ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType] ) -> tuple[TreeType, TreeType]: rl, rr = await self.on(case.protocolizedr()) return await case.protocol.tree(case.split.treel, rl, case.split.key), rr async def on_null( - self, protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType] + self, protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType] ) -> tuple[TreeType, TreeType]: return protocolized.tree, protocolized.tree class UnionAction( - BinaryAction[ - ActiveKeyType, - MetaDataType, - TreeType, - TreeType - ], - Generic[ActiveKeyType, MetaDataType, TreeType] + BinaryAction[ActiveKeyType, MetaDataType, TreeType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType] ): def __init__(self, protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType]): assert isinstance(protocolized, BinaryProtocolized) diff --git a/rainbowadn/collection/trees/binary/actions/symmetric.py b/rainbowadn/collection/trees/binary/actions/symmetric.py index fba4ba8..7e47b92 100644 --- a/rainbowadn/collection/trees/binary/actions/symmetric.py +++ b/rainbowadn/collection/trees/binary/actions/symmetric.py @@ -3,109 +3,70 @@ from typing import Generic, TypeVar from rainbowadn.collection.trees.binary.core import * from rainbowadn.core import * -__all__ = ('Symmetric', 'InnerOuter', 'OuterInner',) +__all__ = ( + "Symmetric", + "InnerOuter", + "OuterInner", +) -TreeType = TypeVar('TreeType') -ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) -MetaDataType = TypeVar('MetaDataType', bound=Mentionable) +TreeType = TypeVar("TreeType") +ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable) +MetaDataType = TypeVar("MetaDataType", bound=Mentionable) -class Symmetric( - Generic[ActiveKeyType, MetaDataType, TreeType] -): +class Symmetric(Generic[ActiveKeyType, MetaDataType, TreeType]): def __init__( - self, - protocol: BinaryCreation[ActiveKeyType, MetaDataType, TreeType], + self, + protocol: BinaryCreation[ActiveKeyType, MetaDataType, TreeType], ): assert isinstance(protocol, BinaryCreation) self.protocol = protocol - def inner( - self, - split: BinarySplit[ActiveKeyType, MetaDataType, TreeType] - ) -> TreeType: + def inner(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType: raise NotImplementedError - def outer( - self, - split: BinarySplit[ActiveKeyType, MetaDataType, TreeType] - ) -> TreeType: + def outer(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType: raise NotImplementedError - async def tree( - self, - inner: TreeType, - outer: TreeType, - key: HashPoint[ActiveKeyType] - ) -> TreeType: + async def tree(self, inner: TreeType, outer: TreeType, key: HashPoint[ActiveKeyType]) -> TreeType: raise NotImplementedError def protocolizedi( - self, - split: BinarySplit[ActiveKeyType, MetaDataType, TreeType] + self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType] ) -> BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType]: assert isinstance(split, BinarySplit) return BinaryProtocolized(self.protocol, self.inner(split)) def protocolizedo( - self, - split: BinarySplit[ActiveKeyType, MetaDataType, TreeType] + self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType] ) -> BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType]: assert isinstance(split, BinarySplit) return BinaryProtocolized(self.protocol, self.outer(split)) -class InnerOuter( - Symmetric[ActiveKeyType, MetaDataType, TreeType], - Generic[ActiveKeyType, MetaDataType, TreeType] -): - def inner( - self, - split: BinarySplit[ActiveKeyType, MetaDataType, TreeType] - ) -> TreeType: +class InnerOuter(Symmetric[ActiveKeyType, MetaDataType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType]): + def inner(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType: assert isinstance(split, BinarySplit) return split.treel - def outer( - self, - split: BinarySplit[ActiveKeyType, MetaDataType, TreeType] - ) -> TreeType: + def outer(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType: assert isinstance(split, BinarySplit) return split.treer - async def tree( - self, - inner: TreeType, - outer: TreeType, - key: HashPoint[ActiveKeyType] - ) -> TreeType: + async def tree(self, inner: TreeType, outer: TreeType, key: HashPoint[ActiveKeyType]) -> TreeType: assert isinstance(key, HashPoint) return await self.protocol.tree(inner, outer, key) -class OuterInner( - Symmetric[ActiveKeyType, MetaDataType, TreeType], - Generic[ActiveKeyType, MetaDataType, TreeType] -): - def inner( - self, - split: BinarySplit[ActiveKeyType, MetaDataType, TreeType] - ) -> TreeType: +class OuterInner(Symmetric[ActiveKeyType, MetaDataType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType]): + def inner(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType: assert isinstance(split, BinarySplit) return split.treer - def outer( - self, - split: BinarySplit[ActiveKeyType, MetaDataType, TreeType] - ) -> TreeType: + def outer(self, split: BinarySplit[ActiveKeyType, MetaDataType, TreeType]) -> TreeType: assert isinstance(split, BinarySplit) return split.treel - async def tree( - self, - inner: TreeType, - outer: TreeType, - key: HashPoint[ActiveKeyType] - ) -> TreeType: + async def tree(self, inner: TreeType, outer: TreeType, key: HashPoint[ActiveKeyType]) -> TreeType: assert isinstance(key, HashPoint) return await self.protocol.tree(outer, inner, key) diff --git a/rainbowadn/collection/trees/binary/activebinarytree.py b/rainbowadn/collection/trees/binary/activebinarytree.py index 1c5acc9..4fb145b 100644 --- a/rainbowadn/collection/trees/binary/activebinarytree.py +++ b/rainbowadn/collection/trees/binary/activebinarytree.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from typing import Generic, Optional, TypeVar from rainbowadn.collection.collectioninterface import * @@ -9,24 +11,19 @@ from .actions import * from .binarytree import * from .core import * -__all__ = ('ActiveBinaryTree',) +__all__ = ("ActiveBinaryTree",) -ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) -MetaDataType = TypeVar('MetaDataType', bound=Mentionable) +ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable) +MetaDataType = TypeVar("MetaDataType", bound=Mentionable) class ActiveBinaryTree( - CollectionInterface[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]], - Generic[ActiveKeyType, MetaDataType] + CollectionInterface[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]], Generic[ActiveKeyType, MetaDataType] ): def __init__( - self, - protocol: BinaryBalancing[ - ActiveKeyType, - MetaDataType, - 'ActiveBinaryTree[ActiveKeyType, MetaDataType]' - ], - reference: NullableReference[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]] + self, + protocol: BinaryBalancing[ActiveKeyType, MetaDataType, ActiveBinaryTree[ActiveKeyType, MetaDataType]], + reference: NullableReference[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]], ): assert isinstance(protocol, BinaryBalancing) assert isinstance(reference, NullableReference) @@ -37,45 +34,33 @@ class ActiveBinaryTree( @classmethod def empty( - cls, - protocol: BinaryBalancing[ActiveKeyType, MetaDataType, 'ActiveBinaryTree'], - factory: RainbowFactory[ActiveKeyType] + cls, + protocol: BinaryBalancing[ActiveKeyType, MetaDataType, ActiveBinaryTree], + factory: RainbowFactory[ActiveKeyType], ): assert isinstance(protocol, BinaryBalancing) assert isinstance(factory, RainbowFactory) return cls( protocol, - NullableReference( - Null(), - BinaryTreeFactory(KeyMetadataFactory(factory, protocol.empty_metadata.factory)) - ) + NullableReference(Null(), BinaryTreeFactory(KeyMetadataFactory(factory, protocol.empty_metadata.factory))), ) def create( - self, - reference: NullableReference[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]] - ) -> 'ActiveBinaryTree[ActiveKeyType, MetaDataType]': + self, reference: NullableReference[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]] + ) -> ActiveBinaryTree[ActiveKeyType, MetaDataType]: assert isinstance(reference, NullableReference) - return ActiveBinaryTree( - self.protocol, - reference - ) + return ActiveBinaryTree(self.protocol, reference) - def protocolized(self) -> BinaryProtocolized[ - ActiveKeyType, - MetaDataType, - 'ActiveBinaryTree[ActiveKeyType, MetaDataType]' - ]: - return BinaryProtocolized( - self.creation, - self - ) + def protocolized( + self, + ) -> BinaryProtocolized[ActiveKeyType, MetaDataType, ActiveBinaryTree[ActiveKeyType, MetaDataType]]: + return BinaryProtocolized(self.creation, self) - async def add(self, key: HashPoint[ActiveKeyType]) -> 'ActiveBinaryTree[ActiveKeyType, MetaDataType]': + async def add(self, key: HashPoint[ActiveKeyType]) -> ActiveBinaryTree[ActiveKeyType, MetaDataType]: assert isinstance(key, HashPoint) return await AddAction(key).on(self.protocolized()) - async def remove(self, key: HashPoint[ActiveKeyType]) -> 'ActiveBinaryTree[ActiveKeyType, MetaDataType]': + async def remove(self, key: HashPoint[ActiveKeyType]) -> ActiveBinaryTree[ActiveKeyType, MetaDataType]: assert isinstance(key, HashPoint) return await RemoveAction(key).on(self.protocolized()) @@ -83,20 +68,17 @@ class ActiveBinaryTree( assert isinstance(key, HashPoint) return await ContainsAction(key, exact=exact).on(self.protocolized()) - async def split(self, key: HashPoint[ActiveKeyType]) -> tuple[ - 'ActiveBinaryTree[ActiveKeyType, MetaDataType]', - 'ActiveBinaryTree[ActiveKeyType, MetaDataType]', - ]: + async def split( + self, key: HashPoint[ActiveKeyType] + ) -> tuple[ActiveBinaryTree[ActiveKeyType, MetaDataType], ActiveBinaryTree[ActiveKeyType, MetaDataType]]: return await SplitAction(key).on(self.protocolized()) async def union( - self, other: 'ActiveBinaryTree[ActiveKeyType, MetaDataType]' - ) -> 'ActiveBinaryTree[ActiveKeyType, MetaDataType]': + self, other: ActiveBinaryTree[ActiveKeyType, MetaDataType] + ) -> ActiveBinaryTree[ActiveKeyType, MetaDataType]: return await UnionAction(other.protocolized()).on(self.protocolized()) - def loose(self) -> CollectionInterface[ - BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]] - ]: + def loose(self) -> CollectionInterface[BinaryTree[KeyMetadata[ActiveKeyType, MetaDataType]]]: return self def __eq__(self, other): @@ -106,23 +88,10 @@ class ActiveBinaryTree( return NotImplemented -class ActiveCreation( - BalancedCreation[ - ActiveKeyType, - MetaDataType, - ActiveBinaryTree[ActiveKeyType, MetaDataType] - ] -): +class ActiveCreation(BalancedCreation[ActiveKeyType, MetaDataType, ActiveBinaryTree[ActiveKeyType, MetaDataType]]): async def split( - self, - tree: ActiveBinaryTree[ActiveKeyType, MetaDataType] - ) -> Optional[ - BinarySplit[ - ActiveKeyType, - MetaDataType, - ActiveBinaryTree[ActiveKeyType, MetaDataType] - ] - ]: + self, tree: ActiveBinaryTree[ActiveKeyType, MetaDataType] + ) -> Optional[BinarySplit[ActiveKeyType, MetaDataType, ActiveBinaryTree[ActiveKeyType, MetaDataType]]]: assert isinstance(tree, ActiveBinaryTree) if tree.reference.null(): return None @@ -136,10 +105,7 @@ class ActiveCreation( ) async def _tree( - self, - treel: ActiveBinaryTree, - treer: ActiveBinaryTree, - key: HashPoint[ActiveKeyType] + self, treel: ActiveBinaryTree, treer: ActiveBinaryTree, key: HashPoint[ActiveKeyType] ) -> ActiveBinaryTree: assert isinstance(treel, ActiveBinaryTree) assert isinstance(treer, ActiveBinaryTree) @@ -150,7 +116,7 @@ class ActiveCreation( BinaryTree( treel.reference, treer.reference, - KeyMetadata(key, await self.protocol.metadata(treel, treer, key, self)) + KeyMetadata(key, await self.protocol.metadata(treel, treer, key, self)), ) - ) + ), ) diff --git a/rainbowadn/collection/trees/binary/avl.py b/rainbowadn/collection/trees/binary/avl.py index 761c217..301e6a3 100644 --- a/rainbowadn/collection/trees/binary/avl.py +++ b/rainbowadn/collection/trees/binary/avl.py @@ -7,10 +7,10 @@ from rainbowadn.core import * from .actions import * from .core import * -__all__ = ('AVL',) +__all__ = ("AVL",) -ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) -TreeType = TypeVar('TreeType') +ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable) +TreeType = TypeVar("TreeType") class AVL(BinaryBalancing[ActiveKeyType, Integer, TreeType]): @@ -18,11 +18,11 @@ class AVL(BinaryBalancing[ActiveKeyType, Integer, TreeType]): super().__init__(comparator_, HashPoint.of(Integer(0))) async def metadata( - self, - treel: TreeType, - treer: TreeType, - key: HashPoint[ActiveKeyType], - creation: BinaryCreation[ActiveKeyType, Integer, TreeType] + self, + treel: TreeType, + treer: TreeType, + key: HashPoint[ActiveKeyType], + creation: BinaryCreation[ActiveKeyType, Integer, TreeType], ) -> HashPoint[Integer]: assert isinstance(key, HashPoint) assert isinstance(creation, BinaryCreation) @@ -35,8 +35,7 @@ class AVL(BinaryBalancing[ActiveKeyType, Integer, TreeType]): return HashPoint.of( Integer( 1 - + - max( + + max( height_l, height_r, ) @@ -45,43 +44,37 @@ class AVL(BinaryBalancing[ActiveKeyType, Integer, TreeType]): @classmethod async def height( - cls, - protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType], + cls, + protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType], ) -> int: assert isinstance(protocolized, BinaryProtocolized) return await HeightAction().on(protocolized) @classmethod async def full_height( - cls, - protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType], + cls, + protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType], ) -> tuple[int, Optional[BinarySplit[ActiveKeyType, Integer, TreeType]]]: assert isinstance(protocolized, BinaryProtocolized) return await FullHeightAction().on(protocolized) async def balance( - self, - protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType], + self, + protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType], ) -> TreeType: assert isinstance(protocolized, BinaryProtocolized) return await BalanceAction().on(protocolized) -class HeightAction( - BinaryAction[ActiveKeyType, Integer, TreeType, int], - Generic[ActiveKeyType, TreeType] -): +class HeightAction(BinaryAction[ActiveKeyType, Integer, TreeType, int], Generic[ActiveKeyType, TreeType]): async def on_null( - self, - protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType], + self, + protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType], ) -> int: assert isinstance(protocolized, BinaryProtocolized) return 0 - async def on_split( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType] - ) -> int: + async def on_split(self, case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType]) -> int: assert isinstance(case, ProtocolizedBinarySplit) metadata: Integer = await case.split.metadata.resolve() assert isinstance(metadata, Integer) @@ -89,24 +82,18 @@ class HeightAction( class FullHeightAction( - BinaryAction[ - ActiveKeyType, - Integer, - TreeType, - tuple[int, Optional[BinarySplit[ActiveKeyType, Integer, TreeType]]] - ], - Generic[ActiveKeyType, TreeType] + BinaryAction[ActiveKeyType, Integer, TreeType, tuple[int, Optional[BinarySplit[ActiveKeyType, Integer, TreeType]]]], + Generic[ActiveKeyType, TreeType], ): async def on_null( - self, - protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType], + self, + protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType], ) -> tuple[int, Optional[BinarySplit[ActiveKeyType, Integer, TreeType]]]: assert isinstance(protocolized, BinaryProtocolized) return 0, None async def on_split( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType] + self, case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType] ) -> tuple[int, Optional[BinarySplit[ActiveKeyType, Integer, TreeType]]]: assert isinstance(case, ProtocolizedBinarySplit) metadata: Integer = await case.split.metadata.resolve() @@ -114,21 +101,15 @@ class FullHeightAction( return metadata.integer, case.split -class BalanceAction( - BinaryAction[ActiveKeyType, Integer, TreeType, TreeType], - Generic[ActiveKeyType, TreeType] -): +class BalanceAction(BinaryAction[ActiveKeyType, Integer, TreeType, TreeType], Generic[ActiveKeyType, TreeType]): async def on_null( - self, - protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType], + self, + protocolized: BinaryProtocolized[ActiveKeyType, Integer, TreeType], ) -> TreeType: assert isinstance(protocolized, BinaryProtocolized) return protocolized.tree - async def on_split( - self, - case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType] - ) -> TreeType: + async def on_split(self, case: ProtocolizedBinarySplit[ActiveKeyType, Integer, TreeType]) -> TreeType: assert isinstance(case, ProtocolizedBinarySplit) (height_l, splitl), (height_r, splitr) = await gather( AVL.full_height(case.protocolizedl()), @@ -151,11 +132,11 @@ class BalanceAction( @classmethod async def on_symmetric( - cls, - symmetry: Symmetric[ActiveKeyType, Integer, TreeType], - treei: TreeType, - key: HashPoint[ActiveKeyType], - splito: BinarySplit[ActiveKeyType, Integer, TreeType], + cls, + symmetry: Symmetric[ActiveKeyType, Integer, TreeType], + treei: TreeType, + key: HashPoint[ActiveKeyType], + splito: BinarySplit[ActiveKeyType, Integer, TreeType], ) -> TreeType: assert isinstance(symmetry, Symmetric) assert isinstance(key, HashPoint) @@ -173,14 +154,8 @@ class BalanceAction( symmetry.tree(treei, symmetry.inner(splitoi), key), symmetry.tree(symmetry.outer(splitoi), symmetry.outer(splito), splito.key), ) - return await symmetry.tree( - inner, - outer, - splitoi.key - ) + return await symmetry.tree(inner, outer, splitoi.key) else: return await symmetry.tree( - await symmetry.tree(treei, symmetry.inner(splito), key), - symmetry.outer(splito), - splito.key + await symmetry.tree(treei, symmetry.inner(splito), key), symmetry.outer(splito), splito.key ) diff --git a/rainbowadn/collection/trees/binary/binarytree.py b/rainbowadn/collection/trees/binary/binarytree.py index 66bbf07..eb0eff9 100644 --- a/rainbowadn/collection/trees/binary/binarytree.py +++ b/rainbowadn/collection/trees/binary/binarytree.py @@ -1,27 +1,32 @@ +from __future__ import annotations + from typing import Generic, Iterable, TypeVar from rainbowadn.core import * from rainbowadn.nullability import * -__all__ = ('BinaryTree', 'BinaryTreeFactory',) +__all__ = ( + "BinaryTree", + "BinaryTreeFactory", +) -TreeKeyType = TypeVar('TreeKeyType', bound=Mentionable) +TreeKeyType = TypeVar("TreeKeyType", bound=Mentionable) class BinaryTree(RecursiveMentionable, Generic[TreeKeyType]): - def __factory__(self) -> RainbowFactory['BinaryTree[TreeKeyType]']: + def __factory__(self) -> RainbowFactory[BinaryTree[TreeKeyType]]: return self.factory(self.key.__factory__()) @classmethod - def factory(cls, factory: RainbowFactory[TreeKeyType]) -> RainbowFactory['BinaryTree[TreeKeyType]']: + def factory(cls, factory: RainbowFactory[TreeKeyType]) -> RainbowFactory[BinaryTree[TreeKeyType]]: assert isinstance(factory, RainbowFactory) return BinaryTreeFactory(factory) def __init__( - self, - treel: NullableReference['BinaryTree[TreeKeyType]'], - treer: NullableReference['BinaryTree[TreeKeyType]'], - key: TreeKeyType + self, + treel: NullableReference[BinaryTree[TreeKeyType]], + treer: NullableReference[BinaryTree[TreeKeyType]], + key: TreeKeyType, ): assert isinstance(treel, NullableReference) assert isinstance(treer, NullableReference) @@ -46,9 +51,7 @@ class BinaryTree(RecursiveMentionable, Generic[TreeKeyType]): assert isinstance(treel_str, str) assert isinstance(key_str, str) assert isinstance(treer_str, str) - return f'{treel_str}' \ - f'{tabulate(tab)}{key_str}' \ - f'{tabulate(tab)}{treer_str}' + return f"{treel_str}" f"{tabulate(tab)}{key_str}" f"{tabulate(tab)}{treer_str}" class BinaryTreeFactory(RainbowFactory[BinaryTree[TreeKeyType]], Generic[TreeKeyType]): @@ -61,12 +64,9 @@ class BinaryTreeFactory(RainbowFactory[BinaryTree[TreeKeyType]], Generic[TreeKey assert isinstance(source, bytes) assert isinstance(resolver, HashResolver) return BinaryTree( - self.reference_factory.from_bytes(source[:HashPoint.HASH_LENGTH], resolver), - self.reference_factory.from_bytes( - source[HashPoint.HASH_LENGTH:HashPoint.HASH_LENGTH * 2], - resolver - ), - self.factory.from_bytes(source[HashPoint.HASH_LENGTH * 2:], resolver), + self.reference_factory.from_bytes(source[: HashPoint.HASH_LENGTH], resolver), + self.reference_factory.from_bytes(source[HashPoint.HASH_LENGTH : HashPoint.HASH_LENGTH * 2], resolver), + self.factory.from_bytes(source[HashPoint.HASH_LENGTH * 2 :], resolver), ) def loose(self) -> RainbowFactory[BinaryTree[TreeKeyType]]: diff --git a/rainbowadn/collection/trees/binary/core/__init__.py b/rainbowadn/collection/trees/binary/core/__init__.py index d6cf214..95c0ac7 100644 --- a/rainbowadn/collection/trees/binary/core/__init__.py +++ b/rainbowadn/collection/trees/binary/core/__init__.py @@ -1,11 +1,11 @@ __all__ = ( - 'BalancedCreation', - 'BinaryBalancing', - 'BinaryCreation', - 'BinaryMetadata', - 'BinaryProtocolized', - 'BinarySplit', - 'ProtocolizedBinarySplit', + "BalancedCreation", + "BinaryBalancing", + "BinaryCreation", + "BinaryMetadata", + "BinaryProtocolized", + "BinarySplit", + "ProtocolizedBinarySplit", ) from .balancedcreation import BalancedCreation diff --git a/rainbowadn/collection/trees/binary/core/balancedcreation.py b/rainbowadn/collection/trees/binary/core/balancedcreation.py index c42b1ce..a740859 100644 --- a/rainbowadn/collection/trees/binary/core/balancedcreation.py +++ b/rainbowadn/collection/trees/binary/core/balancedcreation.py @@ -7,22 +7,17 @@ from .binarybalancing import * from .binarycreation import * from .binaryprotocolized import * -__all__ = ('BalancedCreation',) +__all__ = ("BalancedCreation",) -TreeType = TypeVar('TreeType') -ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) -MetaDataType = TypeVar('MetaDataType', bound=Mentionable) +TreeType = TypeVar("TreeType") +ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable) +MetaDataType = TypeVar("MetaDataType", bound=Mentionable) class BalancedCreation( - BinaryCreation[ActiveKeyType, MetaDataType, TreeType], - Generic[ActiveKeyType, MetaDataType, TreeType], - abc.ABC + BinaryCreation[ActiveKeyType, MetaDataType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType], abc.ABC ): - def __init__( - self, - protocol: BinaryBalancing[ActiveKeyType, MetaDataType, TreeType] - ): + def __init__(self, protocol: BinaryBalancing[ActiveKeyType, MetaDataType, TreeType]): assert isinstance(protocol, BinaryBalancing) self.protocol = protocol super().__init__(protocol.comparator) @@ -36,19 +31,10 @@ class BalancedCreation( self.protocol.balance(BinaryProtocolized(self, treel)), self.protocol.balance(BinaryProtocolized(self, treer)), ) - return await self.protocol.balance( - BinaryProtocolized( - self, - await self._tree( - balancedl, - balancedr, - key - ) - ) - ) + return await self.protocol.balance(BinaryProtocolized(self, await self._tree(balancedl, balancedr, key))) async def verify_metadata( - self, treel: TreeType, treer: TreeType, key: HashPoint[ActiveKeyType], metadata: HashPoint[MetaDataType] + self, treel: TreeType, treer: TreeType, key: HashPoint[ActiveKeyType], metadata: HashPoint[MetaDataType] ) -> bool: assert_true(await self.protocol.verify_metadata(treel, treer, key, metadata, self)) return True diff --git a/rainbowadn/collection/trees/binary/core/binarybalancing.py b/rainbowadn/collection/trees/binary/core/binarybalancing.py index 2047c8e..4cfc781 100644 --- a/rainbowadn/collection/trees/binary/core/binarybalancing.py +++ b/rainbowadn/collection/trees/binary/core/binarybalancing.py @@ -7,17 +7,15 @@ from rainbowadn.core import * from .binarymetadata import * from .binaryprotocolized import * -__all__ = ('BinaryBalancing',) +__all__ = ("BinaryBalancing",) -TreeType = TypeVar('TreeType') -ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) -MetaDataType = TypeVar('MetaDataType', bound=Mentionable) +TreeType = TypeVar("TreeType") +ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable) +MetaDataType = TypeVar("MetaDataType", bound=Mentionable) class BinaryBalancing( - BinaryMetadata[ActiveKeyType, MetaDataType, TreeType], - Generic[ActiveKeyType, MetaDataType, TreeType], - abc.ABC + BinaryMetadata[ActiveKeyType, MetaDataType, TreeType], Generic[ActiveKeyType, MetaDataType, TreeType], abc.ABC ): def __init__(self, comparator_: Comparator[ActiveKeyType], empty_metadata: HashPoint[MetaDataType]): assert isinstance(comparator_, Comparator) @@ -26,7 +24,7 @@ class BinaryBalancing( super().__init__(empty_metadata) async def balance( - self, - protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType], + self, + protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType], ) -> TreeType: raise NotImplementedError diff --git a/rainbowadn/collection/trees/binary/core/binarycreation.py b/rainbowadn/collection/trees/binary/core/binarycreation.py index c5856b9..4096cf4 100644 --- a/rainbowadn/collection/trees/binary/core/binarycreation.py +++ b/rainbowadn/collection/trees/binary/core/binarycreation.py @@ -5,11 +5,11 @@ from rainbowadn.core import * from .binarysplit import * -__all__ = ('BinaryCreation',) +__all__ = ("BinaryCreation",) -TreeType = TypeVar('TreeType') -ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) -MetaDataType = TypeVar('MetaDataType', bound=Mentionable) +TreeType = TypeVar("TreeType") +ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable) +MetaDataType = TypeVar("MetaDataType", bound=Mentionable) class BinaryCreation(Generic[ActiveKeyType, MetaDataType, TreeType]): @@ -17,9 +17,7 @@ class BinaryCreation(Generic[ActiveKeyType, MetaDataType, TreeType]): assert isinstance(comparator, Comparator) self.comparator = comparator - async def split(self, tree: TreeType) -> Optional[ - BinarySplit[ActiveKeyType, MetaDataType, TreeType] - ]: + async def split(self, tree: TreeType) -> Optional[BinarySplit[ActiveKeyType, MetaDataType, TreeType]]: """result of this method is supposed to be used right after the call, therefore all values are resolved""" raise NotImplementedError @@ -27,6 +25,6 @@ class BinaryCreation(Generic[ActiveKeyType, MetaDataType, TreeType]): raise NotImplementedError async def verify_metadata( - self, treel: TreeType, treer: TreeType, key: HashPoint[ActiveKeyType], metadata: HashPoint[MetaDataType] + self, treel: TreeType, treer: TreeType, key: HashPoint[ActiveKeyType], metadata: HashPoint[MetaDataType] ) -> bool: raise NotImplementedError diff --git a/rainbowadn/collection/trees/binary/core/binarymetadata.py b/rainbowadn/collection/trees/binary/core/binarymetadata.py index 40854a6..0bf4bc5 100644 --- a/rainbowadn/collection/trees/binary/core/binarymetadata.py +++ b/rainbowadn/collection/trees/binary/core/binarymetadata.py @@ -4,11 +4,11 @@ from rainbowadn.core import * from .binarycreation import * -__all__ = ('BinaryMetadata',) +__all__ = ("BinaryMetadata",) -TreeType = TypeVar('TreeType') -ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) -MetaDataType = TypeVar('MetaDataType', bound=Mentionable) +TreeType = TypeVar("TreeType") +ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable) +MetaDataType = TypeVar("MetaDataType", bound=Mentionable) class BinaryMetadata(Generic[ActiveKeyType, MetaDataType, TreeType]): @@ -17,21 +17,21 @@ class BinaryMetadata(Generic[ActiveKeyType, MetaDataType, TreeType]): self.empty_metadata = empty_metadata async def metadata( - self, - treel: TreeType, - treer: TreeType, - key: HashPoint[ActiveKeyType], - creation: BinaryCreation[ActiveKeyType, MetaDataType, TreeType], + self, + treel: TreeType, + treer: TreeType, + key: HashPoint[ActiveKeyType], + creation: BinaryCreation[ActiveKeyType, MetaDataType, TreeType], ) -> HashPoint[MetaDataType]: raise NotImplementedError async def verify_metadata( - self, - treel: TreeType, - treer: TreeType, - key: HashPoint[ActiveKeyType], - metadata: HashPoint[MetaDataType], - creation: BinaryCreation[ActiveKeyType, MetaDataType, TreeType], + self, + treel: TreeType, + treer: TreeType, + key: HashPoint[ActiveKeyType], + metadata: HashPoint[MetaDataType], + creation: BinaryCreation[ActiveKeyType, MetaDataType, TreeType], ) -> bool: assert_eq(await self.metadata(treel, treer, key, creation), metadata) return True diff --git a/rainbowadn/collection/trees/binary/core/binaryprotocolized.py b/rainbowadn/collection/trees/binary/core/binaryprotocolized.py index 6ae9cfd..2a85e4b 100644 --- a/rainbowadn/collection/trees/binary/core/binaryprotocolized.py +++ b/rainbowadn/collection/trees/binary/core/binaryprotocolized.py @@ -5,21 +5,15 @@ from rainbowadn.core import * from .binarycreation import * from .binarysplit import * -__all__ = ('BinaryProtocolized',) +__all__ = ("BinaryProtocolized",) -TreeType = TypeVar('TreeType') -ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) -MetaDataType = TypeVar('MetaDataType', bound=Mentionable) +TreeType = TypeVar("TreeType") +ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable) +MetaDataType = TypeVar("MetaDataType", bound=Mentionable) -class BinaryProtocolized( - Generic[ActiveKeyType, MetaDataType, TreeType] -): - def __init__( - self, - creation: BinaryCreation[ActiveKeyType, MetaDataType, TreeType], - tree: TreeType - ): +class BinaryProtocolized(Generic[ActiveKeyType, MetaDataType, TreeType]): + def __init__(self, creation: BinaryCreation[ActiveKeyType, MetaDataType, TreeType], tree: TreeType): assert isinstance(creation, BinaryCreation) self.creation = creation self.tree = tree diff --git a/rainbowadn/collection/trees/binary/core/binarysplit.py b/rainbowadn/collection/trees/binary/core/binarysplit.py index 46dbdc3..9ec2bad 100644 --- a/rainbowadn/collection/trees/binary/core/binarysplit.py +++ b/rainbowadn/collection/trees/binary/core/binarysplit.py @@ -2,22 +2,16 @@ from typing import Generic, TypeVar from rainbowadn.core import * -__all__ = ('BinarySplit',) +__all__ = ("BinarySplit",) -TreeType = TypeVar('TreeType') -ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) -MetaDataType = TypeVar('MetaDataType', bound=Mentionable) +TreeType = TypeVar("TreeType") +ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable) +MetaDataType = TypeVar("MetaDataType", bound=Mentionable) -class BinarySplit( - Generic[ActiveKeyType, MetaDataType, TreeType] -): +class BinarySplit(Generic[ActiveKeyType, MetaDataType, TreeType]): def __init__( - self, - treel: TreeType, - key: HashPoint[ActiveKeyType], - metadata: HashPoint[MetaDataType], - treer: TreeType + self, treel: TreeType, key: HashPoint[ActiveKeyType], metadata: HashPoint[MetaDataType], treer: TreeType ): assert isinstance(key, HashPoint) assert isinstance(metadata, HashPoint) diff --git a/rainbowadn/collection/trees/binary/core/protocolizedbinarysplit.py b/rainbowadn/collection/trees/binary/core/protocolizedbinarysplit.py index 8b1ea34..ebd3dca 100644 --- a/rainbowadn/collection/trees/binary/core/protocolizedbinarysplit.py +++ b/rainbowadn/collection/trees/binary/core/protocolizedbinarysplit.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from typing import Generic, Optional, TypeVar from rainbowadn.core import * @@ -6,21 +8,19 @@ from .binarycreation import * from .binaryprotocolized import * from .binarysplit import * -__all__ = ('ProtocolizedBinarySplit',) +__all__ = ("ProtocolizedBinarySplit",) -TreeType = TypeVar('TreeType') -ActiveKeyType = TypeVar('ActiveKeyType', bound=Mentionable) -MetaDataType = TypeVar('MetaDataType', bound=Mentionable) +TreeType = TypeVar("TreeType") +ActiveKeyType = TypeVar("ActiveKeyType", bound=Mentionable) +MetaDataType = TypeVar("MetaDataType", bound=Mentionable) -class ProtocolizedBinarySplit( - Generic[ActiveKeyType, MetaDataType, TreeType] -): +class ProtocolizedBinarySplit(Generic[ActiveKeyType, MetaDataType, TreeType]): def __init__( - self, - protocol: BinaryCreation[ActiveKeyType, MetaDataType, TreeType], - split: BinarySplit[ActiveKeyType, MetaDataType, TreeType], - tree: TreeType + self, + protocol: BinaryCreation[ActiveKeyType, MetaDataType, TreeType], + split: BinarySplit[ActiveKeyType, MetaDataType, TreeType], + tree: TreeType, ): assert isinstance(protocol, BinaryCreation) assert isinstance(split, BinarySplit) @@ -42,11 +42,8 @@ class ProtocolizedBinarySplit( @classmethod async def split_of( - cls, - protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType] - ) -> Optional[ - 'ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]' - ]: + cls, protocolized: BinaryProtocolized[ActiveKeyType, MetaDataType, TreeType] + ) -> Optional[ProtocolizedBinarySplit[ActiveKeyType, MetaDataType, TreeType]]: assert isinstance(protocolized, BinaryProtocolized) if (split := await protocolized.split()) is None: return None @@ -55,8 +52,6 @@ class ProtocolizedBinarySplit( async def verify_metadata(self) -> bool: assert_true( - await self.protocol.verify_metadata( - self.split.treel, self.split.treer, self.split.key, self.split.metadata - ) + await self.protocol.verify_metadata(self.split.treel, self.split.treer, self.split.key, self.split.metadata) ) return True diff --git a/rainbowadn/core/__init__.py b/rainbowadn/core/__init__.py index 0008eb2..0a08d15 100644 --- a/rainbowadn/core/__init__.py +++ b/rainbowadn/core/__init__.py @@ -1,35 +1,59 @@ __all__ = ( - 'assert_true', 'assert_trues', 'assert_false', 'assert_none', 'assert_none_strict', 'assert_eq', - 'ExtendableResolver', - 'gather', 'asum', 'alist', 'set_gather_asyncio', 'set_gather_linear', 'aidentity', - 'hash_point_format', 'tabulate', 'enable_newline', 'disable_newline', - 'HashPoint', - 'HashResolver', - 'LocalMetaOrigin', - 'LocalOrigin', - 'Mentionable', - 'MetaOrigin', - 'Origin', - 'RainbowFactory', - 'RecursiveMentionable', - 'ResolverMetaOrigin', - 'ResolverOrigin', - 'StaticMentionable', 'StaticFactory', + "assert_true", + "assert_trues", + "assert_false", + "assert_none", + "assert_none_strict", + "assert_eq", + "ExtendableResolver", + "gather", + "asum", + "alist", + "set_gather_asyncio", + "set_gather_linear", + "aidentity", + "hash_point_format", + "tabulate", + "enable_newline", + "disable_newline", + "HashPoint", + "HashResolver", + "LocalMetaOrigin", + "LocalOrigin", + "Mentionable", + "MetaOrigin", + "Origin", + "RainbowFactory", + "RecursiveMentionable", + "ResolverMetaOrigin", + "ResolverOrigin", + "StaticMentionable", + "StaticFactory", ) from .asserts import ( - assert_eq, assert_false, assert_none, assert_none_strict, - assert_true, assert_trues + assert_eq, + assert_false, + assert_none, + assert_none_strict, + assert_true, + assert_trues, ) from .extendableresolver import ExtendableResolver from .gather import ( - aidentity, alist, asum, gather, set_gather_asyncio, - set_gather_linear + aidentity, + alist, + asum, + gather, + set_gather_asyncio, + set_gather_linear, ) from .hashpoint import HashPoint from .hashpointformat import ( - disable_newline, enable_newline, - hash_point_format, tabulate + disable_newline, + enable_newline, + hash_point_format, + tabulate, ) from .hashresolver import HashResolver from .localmetaorigin import LocalMetaOrigin diff --git a/rainbowadn/core/asserts.py b/rainbowadn/core/asserts.py index 21f9fa3..6c453e9 100644 --- a/rainbowadn/core/asserts.py +++ b/rainbowadn/core/asserts.py @@ -1,6 +1,13 @@ from typing import Any, Iterable, Optional, TypeVar -__all__ = ('assert_true', 'assert_trues', 'assert_false', 'assert_none', 'assert_none_strict', 'assert_eq',) +__all__ = ( + "assert_true", + "assert_trues", + "assert_false", + "assert_none", + "assert_none_strict", + "assert_eq", +) def assert_true(value: bool) -> bool: @@ -19,7 +26,7 @@ def assert_false(value: bool) -> bool: return True -T = TypeVar('T') +T = TypeVar("T") def assert_none(value: Optional[Any]) -> bool: diff --git a/rainbowadn/core/extendableresolver.py b/rainbowadn/core/extendableresolver.py index 5b07571..7fc9749 100644 --- a/rainbowadn/core/extendableresolver.py +++ b/rainbowadn/core/extendableresolver.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import abc from typing import TypeVar @@ -6,13 +8,13 @@ from .hashresolver import * from .mentionable import * from .resolvermetaorigin import * -__all__ = ('ExtendableResolver',) +__all__ = ("ExtendableResolver",) -Mentioned = TypeVar('Mentioned', bound=Mentionable) +Mentioned = TypeVar("Mentioned", bound=Mentionable) class ExtendableResolver(HashResolver, abc.ABC): - async def extend(self, hash_point: HashPoint[Mentionable]) -> 'ExtendableResolver': + async def extend(self, hash_point: HashPoint[Mentionable]) -> ExtendableResolver: raise NotImplementedError async def migrate(self, hash_point: HashPoint[Mentioned]) -> HashPoint[Mentioned]: diff --git a/rainbowadn/core/gather.py b/rainbowadn/core/gather.py index b958752..6a1e1fd 100644 --- a/rainbowadn/core/gather.py +++ b/rainbowadn/core/gather.py @@ -1,7 +1,14 @@ import asyncio from typing import Any, AsyncIterable, Awaitable, Coroutine, TypeVar, overload -__all__ = ('gather', 'asum', 'alist', 'set_gather_asyncio', 'set_gather_linear', 'aidentity',) +__all__ = ( + "gather", + "asum", + "alist", + "set_gather_asyncio", + "set_gather_linear", + "aidentity", +) _gather: Any = asyncio.gather @@ -20,28 +27,23 @@ def set_gather_linear(): _gather = _local_gather -T0 = TypeVar('T0') -T1 = TypeVar('T1') -T2 = TypeVar('T2') -T3 = TypeVar('T3') -T4 = TypeVar('T4') +T0 = TypeVar("T0") +T1 = TypeVar("T1") +T2 = TypeVar("T2") +T3 = TypeVar("T3") +T4 = TypeVar("T4") + + +@overload +def gather(a0: Coroutine[Any, Any, T0], a1: Coroutine[Any, Any, T1], /) -> Awaitable[tuple[T0, T1]]: + ... @overload def gather( - a0: Coroutine[Any, Any, T0], - a1: Coroutine[Any, Any, T1], - / -) -> Awaitable[tuple[T0, T1]]: ... - - -@overload -def gather( - a0: Coroutine[Any, Any, T0], - a1: Coroutine[Any, Any, T1], - a2: Coroutine[Any, Any, T2], - / -) -> Awaitable[tuple[T0, T1, T2]]: ... + a0: Coroutine[Any, Any, T0], a1: Coroutine[Any, Any, T1], a2: Coroutine[Any, Any, T2], / +) -> Awaitable[tuple[T0, T1, T2]]: + ... @overload @@ -50,8 +52,9 @@ def gather( a1: Coroutine[Any, Any, T1], a2: Coroutine[Any, Any, T2], a3: Coroutine[Any, Any, T3], - / -) -> Awaitable[tuple[T0, T1, T2, T3]]: ... + /, +) -> Awaitable[tuple[T0, T1, T2, T3]]: + ... @overload @@ -61,8 +64,9 @@ def gather( a2: Coroutine[Any, Any, T2], a3: Coroutine[Any, Any, T3], a4: Coroutine[Any, Any, T4], - / -) -> Awaitable[tuple[T0, T1, T2, T3, T4]]: ... + /, +) -> Awaitable[tuple[T0, T1, T2, T3, T4]]: + ... # @overload @@ -77,7 +81,7 @@ async def asum(iterable): return sum(await gather(*iterable)) -T = TypeVar('T') +T = TypeVar("T") async def alist(aiterable: AsyncIterable[T]) -> list[T]: diff --git a/rainbowadn/core/hashpoint.py b/rainbowadn/core/hashpoint.py index 31f5e57..c7096ca 100644 --- a/rainbowadn/core/hashpoint.py +++ b/rainbowadn/core/hashpoint.py @@ -1,5 +1,7 @@ +from __future__ import annotations + import hashlib -from typing import Generic, TypeVar +from typing import Generic, Type, TypeVar from .asserts import * from .localorigin import * @@ -7,10 +9,10 @@ from .mentionable import * from .origin import * from .rainbow_factory import * -__all__ = ('HashPoint',) +__all__ = ("HashPoint",) -Mentioned = TypeVar('Mentioned', bound=Mentionable, covariant=True) -MentionedI = TypeVar('MentionedI', bound=Mentionable) +Mentioned = TypeVar("Mentioned", bound=Mentionable, covariant=True) +MentionedI = TypeVar("MentionedI", bound=Mentionable) def _hash(source: bytes) -> bytes: @@ -19,11 +21,7 @@ def _hash(source: bytes) -> bytes: class HashPoint(Generic[Mentioned]): - def __init__( - self, - point: bytes, - origin: Origin[Mentioned] - ): + def __init__(self, point: bytes, origin: Origin[Mentioned]): assert isinstance(point, bytes) assert isinstance(origin, Origin) assert_eq(len(point), self.HASH_LENGTH) @@ -35,8 +33,8 @@ class HashPoint(Generic[Mentioned]): def __bytes__(self): return self.point - HASH_LENGTH = len(_hash(b'')) - NULL_HASH = b'\0' * HASH_LENGTH + HASH_LENGTH = len(_hash(b"")) + NULL_HASH = b"\0" * HASH_LENGTH @classmethod def hash(cls, source: bytes) -> bytes: @@ -55,12 +53,10 @@ class HashPoint(Generic[Mentioned]): return topology_hash + bytes(mentioned) @classmethod - def of(cls, mentioned: MentionedI) -> 'HashPoint[MentionedI]': + def of(cls: Type[HashPoint[MentionedI]], mentioned: MentionedI) -> HashPoint[MentionedI]: assert issubclass(cls, HashPoint) assert isinstance(mentioned, Mentionable) - return cls( - cls.hash(cls.bytes_of_mentioned(mentioned)), LocalOrigin(mentioned) - ) + return cls(cls.hash(cls.bytes_of_mentioned(mentioned)), LocalOrigin(mentioned)) async def resolve(self) -> Mentioned: resolved: Mentioned = await self.origin.resolve() diff --git a/rainbowadn/core/hashpointformat.py b/rainbowadn/core/hashpointformat.py index 3cdcc7d..6b82b2e 100644 --- a/rainbowadn/core/hashpointformat.py +++ b/rainbowadn/core/hashpointformat.py @@ -2,7 +2,12 @@ from .hashpoint import * from .mentionable import * from .recursivementionable import * -__all__ = ('hash_point_format', 'tabulate', 'enable_newline', 'disable_newline',) +__all__ = ( + "hash_point_format", + "tabulate", + "enable_newline", + "disable_newline", +) async def hash_point_format(hash_point: HashPoint, tab: int) -> str: @@ -32,6 +37,6 @@ def disable_newline(): def tabulate(tab: int) -> str: assert isinstance(tab, int) if newline: - return '\n' + ' ' * tab + return "\n" + " " * tab else: - return ' ' + return " " diff --git a/rainbowadn/core/hashresolver.py b/rainbowadn/core/hashresolver.py index 850194a..452c211 100644 --- a/rainbowadn/core/hashresolver.py +++ b/rainbowadn/core/hashresolver.py @@ -1,6 +1,8 @@ -__all__ = ('HashResolver',) +from __future__ import annotations + +__all__ = ("HashResolver",) class HashResolver: - async def resolve(self, point: bytes) -> tuple[bytes, 'HashResolver']: + async def resolve(self, point: bytes) -> tuple[bytes, HashResolver]: raise NotImplementedError diff --git a/rainbowadn/core/localmetaorigin.py b/rainbowadn/core/localmetaorigin.py index e80041e..ca6df1f 100644 --- a/rainbowadn/core/localmetaorigin.py +++ b/rainbowadn/core/localmetaorigin.py @@ -7,9 +7,9 @@ from .metaorigin import * from .origin import * from .rainbow_factory import * -__all__ = ('LocalMetaOrigin',) +__all__ = ("LocalMetaOrigin",) -Mentioned = TypeVar('Mentioned', bound=Mentionable) +Mentioned = TypeVar("Mentioned", bound=Mentionable) class LocalMetaOrigin(MetaOrigin[Mentioned], Generic[Mentioned]): diff --git a/rainbowadn/core/localorigin.py b/rainbowadn/core/localorigin.py index c165fd3..5a7b50d 100644 --- a/rainbowadn/core/localorigin.py +++ b/rainbowadn/core/localorigin.py @@ -3,9 +3,9 @@ from typing import Generic, TypeVar from .mentionable import * from .origin import * -__all__ = ('LocalOrigin',) +__all__ = ("LocalOrigin",) -Mentioned = TypeVar('Mentioned') +Mentioned = TypeVar("Mentioned") class LocalOrigin(Origin[Mentioned], Generic[Mentioned]): diff --git a/rainbowadn/core/mentionable.py b/rainbowadn/core/mentionable.py index 7daa366..717f15f 100644 --- a/rainbowadn/core/mentionable.py +++ b/rainbowadn/core/mentionable.py @@ -2,9 +2,9 @@ from typing import TypeVar from .rainbow_factory import * -__all__ = ('Mentionable',) +__all__ = ("Mentionable",) -Mentioned = TypeVar('Mentioned') +Mentioned = TypeVar("Mentioned") class Mentionable: diff --git a/rainbowadn/core/metaorigin.py b/rainbowadn/core/metaorigin.py index 0c9b08e..b60bfd9 100644 --- a/rainbowadn/core/metaorigin.py +++ b/rainbowadn/core/metaorigin.py @@ -6,9 +6,9 @@ from .mentionable import * from .origin import * from .rainbow_factory import * -__all__ = ('MetaOrigin',) +__all__ = ("MetaOrigin",) -Mentioned = TypeVar('Mentioned', bound=Mentionable, covariant=True) +Mentioned = TypeVar("Mentioned", bound=Mentionable, covariant=True) class MetaOrigin(Generic[Mentioned]): diff --git a/rainbowadn/core/origin.py b/rainbowadn/core/origin.py index 7a0ae8c..f5e29b1 100644 --- a/rainbowadn/core/origin.py +++ b/rainbowadn/core/origin.py @@ -2,9 +2,9 @@ from typing import Generic, TypeVar from .rainbow_factory import * -__all__ = ('Origin',) +__all__ = ("Origin",) -Mentioned = TypeVar('Mentioned', covariant=True) +Mentioned = TypeVar("Mentioned", covariant=True) class Origin(Generic[Mentioned]): diff --git a/rainbowadn/core/rainbow_factory.py b/rainbowadn/core/rainbow_factory.py index 2b7830a..db6e925 100644 --- a/rainbowadn/core/rainbow_factory.py +++ b/rainbowadn/core/rainbow_factory.py @@ -2,9 +2,9 @@ from typing import Generic, TypeVar from .hashresolver import * -__all__ = ('RainbowFactory',) +__all__ = ("RainbowFactory",) -Mentioned = TypeVar('Mentioned', covariant=True) +Mentioned = TypeVar("Mentioned", covariant=True) class RainbowFactory(Generic[Mentioned]): diff --git a/rainbowadn/core/recursivementionable.py b/rainbowadn/core/recursivementionable.py index 1979c2e..684537a 100644 --- a/rainbowadn/core/recursivementionable.py +++ b/rainbowadn/core/recursivementionable.py @@ -4,7 +4,7 @@ from typing import Iterable from .hashpoint import * from .mentionable import * -__all__ = ('RecursiveMentionable',) +__all__ = ("RecursiveMentionable",) class RecursiveMentionable(Mentionable, abc.ABC): @@ -20,7 +20,7 @@ class RecursiveMentionable(Mentionable, abc.ABC): async def str(self, tab: int) -> str: assert isinstance(tab, int) - return f'(recursive {self.__class__.__name__})' + return f"(recursive {self.__class__.__name__})" def __topology_hash__(self) -> bytes: - return HashPoint.hash(b''.join(hash_point.point for hash_point in self.points())) + return HashPoint.hash(b"".join(hash_point.point for hash_point in self.points())) diff --git a/rainbowadn/core/resolvermetaorigin.py b/rainbowadn/core/resolvermetaorigin.py index b663bd9..aa80905 100644 --- a/rainbowadn/core/resolvermetaorigin.py +++ b/rainbowadn/core/resolvermetaorigin.py @@ -9,9 +9,9 @@ from .origin import * from .rainbow_factory import * from .resolverorigin import * -__all__ = ('ResolverMetaOrigin',) +__all__ = ("ResolverMetaOrigin",) -Mentioned = TypeVar('Mentioned', bound=Mentionable, covariant=True) +Mentioned = TypeVar("Mentioned", bound=Mentionable, covariant=True) class ResolverMetaOrigin(MetaOrigin[Mentioned], Generic[Mentioned]): diff --git a/rainbowadn/core/resolverorigin.py b/rainbowadn/core/resolverorigin.py index 0fd7817..820a4c5 100644 --- a/rainbowadn/core/resolverorigin.py +++ b/rainbowadn/core/resolverorigin.py @@ -7,18 +7,13 @@ from .mentionable import * from .origin import * from .rainbow_factory import * -__all__ = ('ResolverOrigin',) +__all__ = ("ResolverOrigin",) -Mentioned = TypeVar('Mentioned', bound=Mentionable, covariant=True) +Mentioned = TypeVar("Mentioned", bound=Mentionable, covariant=True) class ResolverOrigin(Origin[Mentioned], Generic[Mentioned]): - def __init__( - self, - factory: RainbowFactory[Mentioned], - point: bytes, - resolver: HashResolver - ): + def __init__(self, factory: RainbowFactory[Mentioned], point: bytes, resolver: HashResolver): assert isinstance(factory, RainbowFactory) assert isinstance(point, bytes) assert isinstance(resolver, HashResolver) @@ -31,9 +26,9 @@ class ResolverOrigin(Origin[Mentioned], Generic[Mentioned]): resolved, resolver = await self.resolver.resolve(self.point) assert isinstance(resolved, bytes) assert isinstance(resolver, HashResolver) - mentioned: Mentioned = self.factory.from_bytes(resolved[HashPoint.HASH_LENGTH:], resolver) + mentioned: Mentioned = self.factory.from_bytes(resolved[HashPoint.HASH_LENGTH :], resolver) assert isinstance(mentioned, Mentionable) - assert_eq(mentioned.__topology_hash__(), resolved[:HashPoint.HASH_LENGTH]) + assert_eq(mentioned.__topology_hash__(), resolved[: HashPoint.HASH_LENGTH]) assert_eq(self.point, HashPoint.hash(HashPoint.bytes_of_mentioned(mentioned))) return mentioned diff --git a/rainbowadn/core/static.py b/rainbowadn/core/static.py index adcf5b1..022edb0 100644 --- a/rainbowadn/core/static.py +++ b/rainbowadn/core/static.py @@ -5,9 +5,12 @@ from .hashresolver import * from .mentionable import * from .rainbow_factory import * -__all__ = ('StaticMentionable', 'StaticFactory',) +__all__ = ( + "StaticMentionable", + "StaticFactory", +) -StaticMentioned = TypeVar('StaticMentioned', bound='StaticMentionable') +StaticMentioned = TypeVar("StaticMentioned", bound="StaticMentionable") class StaticMentionable(Mentionable, abc.ABC): diff --git a/rainbowadn/encryption/__init__.py b/rainbowadn/encryption/__init__.py index 03dba0b..b882347 100644 --- a/rainbowadn/encryption/__init__.py +++ b/rainbowadn/encryption/__init__.py @@ -1,5 +1,6 @@ __all__ = ( - 'Encrypted', 'EncryptedFactory', + "Encrypted", + "EncryptedFactory", ) from .encrypted import Encrypted, EncryptedFactory diff --git a/rainbowadn/encryption/encrypted.py b/rainbowadn/encryption/encrypted.py index 0293305..7a5d7d2 100644 --- a/rainbowadn/encryption/encrypted.py +++ b/rainbowadn/encryption/encrypted.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from typing import Generic, Iterable, TypeVar from nacl.bindings import crypto_hash_sha256 @@ -5,20 +7,23 @@ from nacl.secret import SecretBox from rainbowadn.core import * -__all__ = ('Encrypted', 'EncryptedFactory',) +__all__ = ( + "Encrypted", + "EncryptedFactory", +) -EncryptedType = TypeVar('EncryptedType', bound=Mentionable) +EncryptedType = TypeVar("EncryptedType", bound=Mentionable) class Encrypted(RecursiveMentionable, Generic[EncryptedType]): """unstable""" def __init__( - self, - key: bytes, - resolution: tuple[HashPoint['Encrypted'], ...], - mapping: dict[bytes, HashPoint['Encrypted']], - decrypted: EncryptedType + self, + key: bytes, + resolution: tuple[HashPoint[Encrypted], ...], + mapping: dict[bytes, HashPoint[Encrypted]], + decrypted: EncryptedType, ): assert isinstance(key, bytes) assert isinstance(resolution, tuple) @@ -38,49 +43,34 @@ class Encrypted(RecursiveMentionable, Generic[EncryptedType]): return self.resolution @classmethod - async def encrypt(cls, decrypted: EncryptedType, key: bytes) -> 'Encrypted[EncryptedType]': + async def encrypt(cls, decrypted: EncryptedType, key: bytes) -> Encrypted[EncryptedType]: assert isinstance(decrypted, Mentionable) assert isinstance(key, bytes) hashpoints = tuple(decrypted.points()) if isinstance(decrypted, RecursiveMentionable) else () - resolution = tuple( - await gather( - *( - cls.encrypt_hashpoint(hash_point, key) for hash_point in hashpoints - ) - ) - ) - return cls.construct( - key, - resolution, - hashpoints, - decrypted - ) + resolution = tuple(await gather(*(cls.encrypt_hashpoint(hash_point, key) for hash_point in hashpoints))) + return cls.construct(key, resolution, hashpoints, decrypted) @classmethod async def encrypt_hashpoint( - cls, hash_point: HashPoint[EncryptedType], key: bytes - ) -> HashPoint['Encrypted[EncryptedType]']: + cls, hash_point: HashPoint[EncryptedType], key: bytes + ) -> HashPoint[Encrypted[EncryptedType]]: assert isinstance(hash_point, HashPoint) assert isinstance(key, bytes) if isinstance(hash_point.origin, ResolverOrigin): resolver: HashResolver = hash_point.origin.resolver assert isinstance(resolver, HashResolver) if isinstance(resolver, EncryptedResolver) and resolver.key == key: - return ShortcutOrigin( - hash_point.factory, - resolver.mapping[hash_point.point], - key - ).hash_point() + return ShortcutOrigin(hash_point.factory, resolver.mapping[hash_point.point], key).hash_point() return HashPoint.of(await cls.encrypt(await hash_point.resolve(), key)) @classmethod def construct( - cls, - key: bytes, - resolution: tuple[HashPoint['Encrypted'], ...], - hashpoints: tuple[HashPoint, ...], - decrypted: EncryptedType - ) -> 'Encrypted[EncryptedType]': + cls, + key: bytes, + resolution: tuple[HashPoint[Encrypted], ...], + hashpoints: tuple[HashPoint, ...], + decrypted: EncryptedType, + ) -> Encrypted[EncryptedType]: assert isinstance(key, bytes) assert isinstance(resolution, tuple) assert isinstance(hashpoints, tuple) @@ -92,23 +82,19 @@ class Encrypted(RecursiveMentionable, Generic[EncryptedType]): key, resolution, mapping, - decrypted.__factory__().from_bytes( - bytes(decrypted), - EncryptedResolver(mapping, key) - ) + decrypted.__factory__().from_bytes(bytes(decrypted), EncryptedResolver(mapping, key)), ) def __bytes__(self): - source: bytes = len(self.resolution).to_bytes(8, 'little') + b''.join( - encrypted.point - for - encrypted - in self.resolution - ) + bytes(self.decrypted) + source: bytes = ( + len(self.resolution).to_bytes(8, "little") + + b"".join(encrypted.point for encrypted in self.resolution) + + bytes(self.decrypted) + ) nonce: bytes = crypto_hash_sha256(self.key + source)[:24] return SecretBox(self.key).encrypt(source, nonce=nonce) - def __factory__(self) -> RainbowFactory['Encrypted[EncryptedType]']: + def __factory__(self) -> RainbowFactory[Encrypted[EncryptedType]]: return EncryptedFactory(self.factory, self.key) @@ -123,9 +109,9 @@ class EncryptedFactory(RainbowFactory[Encrypted[EncryptedType]], Generic[Encrypt assert isinstance(source, bytes) assert isinstance(resolver, HashResolver) plain: bytes = SecretBox(self.key).decrypt(source) - resolution_size: int = int.from_bytes(plain[:8], 'little') + resolution_size: int = int.from_bytes(plain[:8], "little") decrypted: EncryptedType = self.factory.from_bytes( - plain[8 + resolution_size * HashPoint.HASH_LENGTH:], + plain[8 + resolution_size * HashPoint.HASH_LENGTH :], resolver, ) assert isinstance(decrypted, Mentionable) @@ -133,20 +119,13 @@ class EncryptedFactory(RainbowFactory[Encrypted[EncryptedType]], Generic[Encrypt assert_eq(len(hashpoints), resolution_size) resolution: tuple[HashPoint[Encrypted], ...] = tuple( ResolverOrigin( - EncryptedFactory( - hash_point.factory, - self.key - ), - plain[8 + i * HashPoint.HASH_LENGTH: 8 + (i + 1) * HashPoint.HASH_LENGTH], - resolver - ).hash_point() for i, hash_point in enumerate(hashpoints) - ) - return Encrypted.construct( - self.key, - resolution, - hashpoints, - decrypted + EncryptedFactory(hash_point.factory, self.key), + plain[8 + i * HashPoint.HASH_LENGTH : 8 + (i + 1) * HashPoint.HASH_LENGTH], + resolver, + ).hash_point() + for i, hash_point in enumerate(hashpoints) ) + return Encrypted.construct(self.key, resolution, hashpoints, decrypted) class EncryptedResolver(HashResolver): @@ -156,7 +135,7 @@ class EncryptedResolver(HashResolver): self.mapping = mapping self.key = key - async def resolve(self, point: bytes) -> tuple[bytes, 'HashResolver']: + async def resolve(self, point: bytes) -> tuple[bytes, HashResolver]: assert isinstance(point, bytes) encrypted: Encrypted = await self.mapping[point].resolve() assert isinstance(encrypted, Encrypted) @@ -182,10 +161,7 @@ class ShortcutOrigin(Origin[Encrypted[EncryptedType]], Generic[EncryptedType]): return encrypted def hash_point(self) -> HashPoint[Encrypted[EncryptedType]]: - return HashPoint( - self.hashpoint.point, - self - ) + return HashPoint(self.hashpoint.point, self) class ShortcutResolver(HashResolver): @@ -195,11 +171,8 @@ class ShortcutResolver(HashResolver): hash_point.point: hash_point for hash_point in encrypted.resolution } - async def resolve(self, point: bytes) -> tuple[bytes, 'HashResolver']: + async def resolve(self, point: bytes) -> tuple[bytes, HashResolver]: assert isinstance(point, bytes) resolved: Encrypted = await self.mapping[point].resolve() assert isinstance(resolved, Encrypted) - return ( - HashPoint.bytes_of_mentioned(resolved), - ShortcutResolver(resolved) - ) + return (HashPoint.bytes_of_mentioned(resolved), ShortcutResolver(resolved)) diff --git a/rainbowadn/flow/bridge/__init__.py b/rainbowadn/flow/bridge/__init__.py index 5ef5d98..436d530 100644 --- a/rainbowadn/flow/bridge/__init__.py +++ b/rainbowadn/flow/bridge/__init__.py @@ -2,8 +2,6 @@ todo: deprecate """ -__all__ = ( - 'ListBridge', -) +__all__ = ("ListBridge",) from ._listbridge import ListBridge diff --git a/rainbowadn/flow/bridge/_listbridge.py b/rainbowadn/flow/bridge/_listbridge.py index 7006851..df4f7ff 100644 --- a/rainbowadn/flow/bridge/_listbridge.py +++ b/rainbowadn/flow/bridge/_listbridge.py @@ -3,16 +3,13 @@ from typing import Generic, TypeVar from rainbowadn.core import * from rainbowadn.flow.core import * -__all__ = ('ListBridge',) +__all__ = ("ListBridge",) -Element = TypeVar('Element') -Out = TypeVar('Out') +Element = TypeVar("Element") +Out = TypeVar("Out") -class ListBridge( - Reducer[Element, Out], - Generic[Element, Out] -): +class ListBridge(Reducer[Element, Out], Generic[Element, Out]): def __init__(self, target: list[Element]): assert isinstance(target, list) self.target = target diff --git a/rainbowadn/flow/core/__init__.py b/rainbowadn/flow/core/__init__.py index af78026..c986b1c 100644 --- a/rainbowadn/flow/core/__init__.py +++ b/rainbowadn/flow/core/__init__.py @@ -1,12 +1,12 @@ __all__ = ( - 'CallableMapper', - 'Composition', - 'Mapper', - 'MapReduce', - 'MapReducer', - 'PureReduce', - 'Reduce', - 'Reducer', + "CallableMapper", + "Composition", + "Mapper", + "MapReduce", + "MapReducer", + "PureReduce", + "Reduce", + "Reducer", ) from ._callablemapper import CallableMapper diff --git a/rainbowadn/flow/core/_callablemapper.py b/rainbowadn/flow/core/_callablemapper.py index b989419..c0a0a27 100644 --- a/rainbowadn/flow/core/_callablemapper.py +++ b/rainbowadn/flow/core/_callablemapper.py @@ -2,16 +2,13 @@ from typing import Callable, Generic, TypeVar from ._mapper import Mapper -__all__ = ('CallableMapper',) +__all__ = ("CallableMapper",) -Element = TypeVar('Element', contravariant=True) -Mapped = TypeVar('Mapped', covariant=True) +Element = TypeVar("Element", contravariant=True) +Mapped = TypeVar("Mapped", covariant=True) -class CallableMapper( - Mapper[Element, Mapped], - Generic[Element, Mapped] -): +class CallableMapper(Mapper[Element, Mapped], Generic[Element, Mapped]): def __init__(self, target: Callable[[Element], Mapped]): assert callable(target) self.target = target diff --git a/rainbowadn/flow/core/_composition.py b/rainbowadn/flow/core/_composition.py index 0fd18f6..c07d70c 100644 --- a/rainbowadn/flow/core/_composition.py +++ b/rainbowadn/flow/core/_composition.py @@ -2,17 +2,14 @@ from typing import Generic, TypeVar from ._mapper import * -__all__ = ('Composition',) +__all__ = ("Composition",) -Element = TypeVar('Element', contravariant=True) -Middle = TypeVar('Middle') -Mapped = TypeVar('Mapped', covariant=True) +Element = TypeVar("Element", contravariant=True) +Middle = TypeVar("Middle") +Mapped = TypeVar("Mapped", covariant=True) -class Composition( - Mapper[Element, Mapped], - Generic[Element, Mapped, Middle] -): +class Composition(Mapper[Element, Mapped], Generic[Element, Mapped, Middle]): def __init__(self, domain: Mapper[Element, Middle], codomain: Mapper[Middle, Mapped]): assert isinstance(domain, Mapper) assert isinstance(codomain, Mapper) diff --git a/rainbowadn/flow/core/_mapper.py b/rainbowadn/flow/core/_mapper.py index 5b0455d..a9a740f 100644 --- a/rainbowadn/flow/core/_mapper.py +++ b/rainbowadn/flow/core/_mapper.py @@ -1,9 +1,9 @@ from typing import Any, Callable, Coroutine, Generic, TypeVar -__all__ = ('Mapper',) +__all__ = ("Mapper",) -Element = TypeVar('Element', contravariant=True) -Mapped = TypeVar('Mapped', covariant=True) +Element = TypeVar("Element", contravariant=True) +Mapped = TypeVar("Mapped", covariant=True) class Mapper(Generic[Element, Mapped]): diff --git a/rainbowadn/flow/core/_mapreduce.py b/rainbowadn/flow/core/_mapreduce.py index 13bd99c..05e6794 100644 --- a/rainbowadn/flow/core/_mapreduce.py +++ b/rainbowadn/flow/core/_mapreduce.py @@ -5,11 +5,11 @@ from rainbowadn.core import * from ._mapper import * from ._reduce import * -__all__ = ('MapReduce',) +__all__ = ("MapReduce",) -Element = TypeVar('Element', contravariant=True) -Mapped = TypeVar('Mapped') -Out = TypeVar('Out') +Element = TypeVar("Element", contravariant=True) +Mapped = TypeVar("Mapped") +Out = TypeVar("Out") class MapReduce(Reduce[Element, Out], Generic[Element, Out, Mapped]): @@ -24,9 +24,9 @@ class MapReduce(Reduce[Element, Out], Generic[Element, Out, Mapped]): return await self.reduce_mapped.reducec(lambda: aidentity(out), lambda: self.mapper.map(element)) async def reducec( - self, - outc: Callable[[], Coroutine[Any, Any, Out]], - elementc: Callable[[], Coroutine[Any, Any, Element]], + self, + outc: Callable[[], Coroutine[Any, Any, Out]], + elementc: Callable[[], Coroutine[Any, Any, Element]], ) -> Out: return await self.reduce_mapped.reducec(outc, self.mapper.bind(elementc)) @@ -34,9 +34,9 @@ class MapReduce(Reduce[Element, Out], Generic[Element, Out, Mapped]): return await self.reduce_mapped.merge(left, right) async def mergec( - self, - leftc: Callable[[], Coroutine[Any, Any, Out]], - rightc: Callable[[], Coroutine[Any, Any, Out]], + self, + leftc: Callable[[], Coroutine[Any, Any, Out]], + rightc: Callable[[], Coroutine[Any, Any, Out]], ) -> Out: return await self.reduce_mapped.mergec(leftc, rightc) diff --git a/rainbowadn/flow/core/_mapreducer.py b/rainbowadn/flow/core/_mapreducer.py index ed16c2b..593ee34 100644 --- a/rainbowadn/flow/core/_mapreducer.py +++ b/rainbowadn/flow/core/_mapreducer.py @@ -5,11 +5,11 @@ from ._mapreduce import * from ._reduce import * from ._reducer import * -__all__ = ('MapReducer',) +__all__ = ("MapReducer",) -Element = TypeVar('Element', contravariant=True) -Mapped = TypeVar('Mapped') -Out = TypeVar('Out') +Element = TypeVar("Element", contravariant=True) +Mapped = TypeVar("Mapped") +Out = TypeVar("Out") class MapReducer(Reducer[Mapped, Out], Generic[Mapped, Out, Element]): diff --git a/rainbowadn/flow/core/_purereduce.py b/rainbowadn/flow/core/_purereduce.py index c51f647..1cbfa23 100644 --- a/rainbowadn/flow/core/_purereduce.py +++ b/rainbowadn/flow/core/_purereduce.py @@ -2,9 +2,9 @@ from typing import Generic, TypeVar from ._reduce import * -__all__ = ('PureReduce',) +__all__ = ("PureReduce",) -Pure = TypeVar('Pure') +Pure = TypeVar("Pure") class PureReduce(Reduce[Pure, Pure], Generic[Pure]): diff --git a/rainbowadn/flow/core/_reduce.py b/rainbowadn/flow/core/_reduce.py index 017e4ea..e5c57a3 100644 --- a/rainbowadn/flow/core/_reduce.py +++ b/rainbowadn/flow/core/_reduce.py @@ -2,10 +2,10 @@ from typing import Any, Callable, Coroutine, Generic, TypeVar from rainbowadn.core import * -__all__ = ('Reduce',) +__all__ = ("Reduce",) -Element = TypeVar('Element', contravariant=True) -Out = TypeVar('Out') +Element = TypeVar("Element", contravariant=True) +Out = TypeVar("Out") class Reduce(Generic[Element, Out]): @@ -16,9 +16,9 @@ class Reduce(Generic[Element, Out]): raise NotImplementedError async def reducec( - self, - out2: Callable[[], Coroutine[Any, Any, Out]], - element2: Callable[[], Coroutine[Any, Any, Element]], + self, + out2: Callable[[], Coroutine[Any, Any, Out]], + element2: Callable[[], Coroutine[Any, Any, Element]], ) -> Out: out, element = await gather(out2(), element2()) return await self.reduce(out, element) @@ -27,9 +27,9 @@ class Reduce(Generic[Element, Out]): raise NotImplementedError async def mergec( - self, - leftc: Callable[[], Coroutine[Any, Any, Out]], - rightc: Callable[[], Coroutine[Any, Any, Out]], + self, + leftc: Callable[[], Coroutine[Any, Any, Out]], + rightc: Callable[[], Coroutine[Any, Any, Out]], ) -> Out: left, right = await gather(leftc(), rightc()) return await self.merge(left, right) diff --git a/rainbowadn/flow/core/_reducer.py b/rainbowadn/flow/core/_reducer.py index 8db4d25..134c860 100644 --- a/rainbowadn/flow/core/_reducer.py +++ b/rainbowadn/flow/core/_reducer.py @@ -2,10 +2,10 @@ from typing import Generic, TypeVar from ._reduce import * -__all__ = ('Reducer',) +__all__ = ("Reducer",) -Element = TypeVar('Element', contravariant=True) -Out = TypeVar('Out') +Element = TypeVar("Element", contravariant=True) +Out = TypeVar("Out") class Reducer(Generic[Element, Out]): diff --git a/rainbowadn/flow/primitive/__init__.py b/rainbowadn/flow/primitive/__init__.py index 47fb1ba..d102585 100644 --- a/rainbowadn/flow/primitive/__init__.py +++ b/rainbowadn/flow/primitive/__init__.py @@ -1,6 +1,6 @@ __all__ = ( - 'ConstMapper', - 'UnitReducer', + "ConstMapper", + "UnitReducer", ) from ._constmapper import ConstMapper diff --git a/rainbowadn/flow/primitive/_constmapper.py b/rainbowadn/flow/primitive/_constmapper.py index 2e9d9ad..d078919 100644 --- a/rainbowadn/flow/primitive/_constmapper.py +++ b/rainbowadn/flow/primitive/_constmapper.py @@ -2,10 +2,10 @@ from typing import Generic, TypeVar from rainbowadn.flow.core import * -__all__ = ('ConstMapper',) +__all__ = ("ConstMapper",) -Element = TypeVar('Element', contravariant=True) -Mapped = TypeVar('Mapped', covariant=True) +Element = TypeVar("Element", contravariant=True) +Mapped = TypeVar("Mapped", covariant=True) class ConstMapper(Mapper[Element, Mapped], Generic[Element, Mapped]): diff --git a/rainbowadn/flow/primitive/_unitreducer.py b/rainbowadn/flow/primitive/_unitreducer.py index 3ef36d8..09d6030 100644 --- a/rainbowadn/flow/primitive/_unitreducer.py +++ b/rainbowadn/flow/primitive/_unitreducer.py @@ -2,16 +2,13 @@ from typing import Generic, TypeVar from rainbowadn.flow.core import * -__all__ = ('UnitReducer',) +__all__ = ("UnitReducer",) -Element = TypeVar('Element', contravariant=True) -Out = TypeVar('Out') +Element = TypeVar("Element", contravariant=True) +Out = TypeVar("Out") -class UnitReducer( - Reducer[Element, Out], - Generic[Element, Out] -): +class UnitReducer(Reducer[Element, Out], Generic[Element, Out]): def __init__(self, element: Element): self.element = element diff --git a/rainbowadn/flow/verification/core/__init__.py b/rainbowadn/flow/verification/core/__init__.py index 6be338b..e0278fb 100644 --- a/rainbowadn/flow/verification/core/__init__.py +++ b/rainbowadn/flow/verification/core/__init__.py @@ -1,9 +1,9 @@ __all__ = ( - 'CompositionVerification', - 'MapperVerification', - 'ReduceVerification', - 'Verification', - 'VerifyReduce', + "CompositionVerification", + "MapperVerification", + "ReduceVerification", + "Verification", + "VerifyReduce", ) from ._compositionverification import CompositionVerification diff --git a/rainbowadn/flow/verification/core/_compositionverification.py b/rainbowadn/flow/verification/core/_compositionverification.py index 161b3db..277df78 100644 --- a/rainbowadn/flow/verification/core/_compositionverification.py +++ b/rainbowadn/flow/verification/core/_compositionverification.py @@ -5,16 +5,13 @@ from rainbowadn.flow.core import * from ._verification import * -__all__ = ('CompositionVerification',) +__all__ = ("CompositionVerification",) -Verified = TypeVar('Verified', contravariant=True) -Middle = TypeVar('Middle') +Verified = TypeVar("Verified", contravariant=True) +Middle = TypeVar("Middle") -class CompositionVerification( - Verification[Verified], - Generic[Verified, Middle] -): +class CompositionVerification(Verification[Verified], Generic[Verified, Middle]): def __init__(self, domain: Mapper[Verified, Middle], codomain: Verification[Middle]): assert isinstance(domain, Mapper) assert isinstance(codomain, Verification) diff --git a/rainbowadn/flow/verification/core/_mapperverification.py b/rainbowadn/flow/verification/core/_mapperverification.py index 78cd4ae..0a0d89e 100644 --- a/rainbowadn/flow/verification/core/_mapperverification.py +++ b/rainbowadn/flow/verification/core/_mapperverification.py @@ -4,9 +4,9 @@ from rainbowadn.flow.core import * from ._verification import * -__all__ = ('MapperVerification',) +__all__ = ("MapperVerification",) -Verified = TypeVar('Verified', contravariant=True) +Verified = TypeVar("Verified", contravariant=True) class MapperVerification(Verification[Verified], Generic[Verified]): diff --git a/rainbowadn/flow/verification/core/_reduceverification.py b/rainbowadn/flow/verification/core/_reduceverification.py index a1bb666..a9e5448 100644 --- a/rainbowadn/flow/verification/core/_reduceverification.py +++ b/rainbowadn/flow/verification/core/_reduceverification.py @@ -6,19 +6,16 @@ from rainbowadn.flow.core import * from ._verification import * from ._verifyreduce import * -__all__ = ('ReduceVerification',) +__all__ = ("ReduceVerification",) -Verified = TypeVar('Verified', contravariant=True) +Verified = TypeVar("Verified", covariant=True) class ReduceVerification( Verification[Reducer[Verified, bool]], Generic[Verified], ): - def __init__( - self, - verification: Verification[Verified] - ): + def __init__(self, verification: Verification[Verified]): assert isinstance(verification, Mapper) self.verification = verification diff --git a/rainbowadn/flow/verification/core/_verification.py b/rainbowadn/flow/verification/core/_verification.py index 1f2ebac..bd22b25 100644 --- a/rainbowadn/flow/verification/core/_verification.py +++ b/rainbowadn/flow/verification/core/_verification.py @@ -3,15 +3,12 @@ from typing import Generic, TypeVar from rainbowadn.core import * from rainbowadn.flow.core import * -__all__ = ('Verification',) +__all__ = ("Verification",) -Verified = TypeVar('Verified', contravariant=True) +Verified = TypeVar("Verified", contravariant=True) -class Verification( - Mapper[Verified, bool], - Generic[Verified] -): +class Verification(Mapper[Verified, bool], Generic[Verified]): async def map(self, element: Verified) -> bool: assert_true(await self.verify(element)) return True diff --git a/rainbowadn/flow/verification/core/_verifyreduce.py b/rainbowadn/flow/verification/core/_verifyreduce.py index c677dac..53796af 100644 --- a/rainbowadn/flow/verification/core/_verifyreduce.py +++ b/rainbowadn/flow/verification/core/_verifyreduce.py @@ -1,7 +1,7 @@ from rainbowadn.core import * from rainbowadn.flow.core import * -__all__ = ('VerifyReduce',) +__all__ = ("VerifyReduce",) class VerifyReduce(PureReduce[bool]): diff --git a/rainbowadn/flow/verification/stateverification.py b/rainbowadn/flow/verification/stateverification.py index b228780..588546c 100644 --- a/rainbowadn/flow/verification/stateverification.py +++ b/rainbowadn/flow/verification/stateverification.py @@ -5,21 +5,21 @@ from rainbowadn.flow.core import * from rainbowadn.flow.verification.core import * from rainbowadn.nullability import * -__all__ = ('StateVerification', 'SVF',) +__all__ = ( + "StateVerification", + "SVF", +) -Header = TypeVar('Header') -State = TypeVar('State') -Link = TypeVar('Link') +Header = TypeVar("Header") +State = TypeVar("State") +Link = TypeVar("Link") -class StateVerification( - Verification[tuple[Nullable[Link], Link]], - Generic[Header, State, Link] -): +class StateVerification(Verification[tuple[Nullable[Link], Link]], Generic[Header, State, Link]): def __init__( - self, - mapper: Mapper[Link, tuple[Header, State]], - verification: Verification[tuple[Nullable[State], Header, State]], + self, + mapper: Mapper[Link, tuple[Header, State]], + verification: Verification[tuple[Nullable[State], Header, State]], ): assert isinstance(mapper, Mapper) assert isinstance(verification, Mapper) diff --git a/rainbowadn/flow13/__init__.py b/rainbowadn/flow13/__init__.py index e0d571e..34aef0a 100644 --- a/rainbowadn/flow13/__init__.py +++ b/rainbowadn/flow13/__init__.py @@ -1,10 +1,15 @@ __all__ = ( - 'BankBlock', - 'FlowBlock', 'FlowBlockFactory', 'FlowBlockVerification', - 'FlowCheque', - 'FlowIterate', - 'FlowStandard', - 'FlowCoinData', 'FlowCoin', 'FlowTransactionData', 'FlowTransaction', + "BankBlock", + "FlowBlock", + "FlowBlockFactory", + "FlowBlockVerification", + "FlowCheque", + "FlowIterate", + "FlowStandard", + "FlowCoinData", + "FlowCoin", + "FlowTransactionData", + "FlowTransaction", ) from ._bankblock import BankBlock @@ -12,7 +17,4 @@ from ._flowblock import FlowBlock, FlowBlockFactory, FlowBlockVerification from ._flowcheque import FlowCheque from ._flowiterate import FlowIterate from ._flowstandard import FlowStandard -from ._flowtransaction import ( - FlowCoin, FlowCoinData, FlowTransaction, - FlowTransactionData -) +from ._flowtransaction import FlowCoin, FlowCoinData, FlowTransaction, FlowTransactionData diff --git a/rainbowadn/flow13/_bankblock.py b/rainbowadn/flow13/_bankblock.py index 360ed17..54152ea 100644 --- a/rainbowadn/flow13/_bankblock.py +++ b/rainbowadn/flow13/_bankblock.py @@ -12,7 +12,7 @@ from ._flowblock import * from ._flowcheque import * from ._flowstandard import * -__all__ = ('BankBlock',) +__all__ = ("BankBlock",) Link: TypeAlias = IPair[FlowCheque, FlowBank] Block: TypeAlias = FlowBlock[Link] @@ -25,7 +25,7 @@ class BankBlock: self.reference = reference @classmethod - def flow(cls) -> 'BankFlow': + def flow(cls) -> "BankFlow": return BankFlow(FlowBank.empty()) @classmethod @@ -33,13 +33,8 @@ class BankBlock: return IPair.f(FlowCheque.factory(), FlowBank.factory()) @classmethod - def empty(cls) -> 'BankBlock': - return cls( - NullableReference( - Null(), - FlowBlockFactory(cls.link_factory()).loose() - ) - ) + def empty(cls) -> "BankBlock": + return cls(NullableReference(Null(), FlowBlockFactory(cls.link_factory()).loose())) @classmethod def verification(cls) -> Verification[Index]: @@ -50,14 +45,12 @@ class BankBlock: assert_true(await self.verification().verify(await FlowBlock.outer_of(self.link_factory(), self.reference))) return True - async def add(self, cheque: FlowCheque) -> 'BankBlock': + async def add(self, cheque: FlowCheque) -> "BankBlock": assert isinstance(cheque, FlowCheque) return await AddCheque(cheque).map(self) -class AddCheque( - Mapper[BankBlock, BankBlock] -): +class AddCheque(Mapper[BankBlock, BankBlock]): def __init__(self, cheque: FlowCheque): assert isinstance(cheque, FlowCheque) self.cheque = cheque @@ -65,7 +58,7 @@ class AddCheque( @classmethod async def _bank_for_link(cls, link: Nullable[Link]) -> Nullable[FlowBank]: assert isinstance(link, Nullable) - return Null() if link.null() else NotNull(await (link.resolve()).e1.resolve()) + return Null() if link.null() else NotNull(await link.resolve().e1.resolve()) async def _next_bank_for_bank(self, bank: Nullable[FlowBank]) -> FlowBank: return await BankBlock.flow().add(bank, self.cheque) @@ -74,38 +67,32 @@ class AddCheque( assert isinstance(bank, FlowBank) return HashPoint.of(IPair.of(self.cheque, bank)) - async def _next_link_for_link( - self, link: Nullable[Link] - ) -> HashPoint[Link]: + async def _next_link_for_link(self, link: Nullable[Link]) -> HashPoint[Link]: assert isinstance(link, Nullable) - return await self._link_for_bank( - await self._next_bank_for_bank( - await self._bank_for_link(link) - ) - ) + return await self._link_for_bank(await self._next_bank_for_bank(await self._bank_for_link(link))) @classmethod async def _add_link_to_reference( - cls, - link: HashPoint[Link], - reference: NullableReference[Block], + cls, + link: HashPoint[Link], + reference: NullableReference[Block], ) -> BankBlock: assert isinstance(link, HashPoint) assert isinstance(reference, NullableReference) return BankBlock(NullableReference.off(await FlowBlock.add_to(reference, link))) async def _add_to_link( - self, - previous: Nullable[Link], - reference: NullableReference[Block], + self, + previous: Nullable[Link], + reference: NullableReference[Block], ) -> BankBlock: assert isinstance(previous, Nullable) assert isinstance(reference, NullableReference) return await self._add_link_to_reference(await self._next_link_for_link(previous), reference) async def _add_to_reference( - self, - reference: NullableReference[Block], + self, + reference: NullableReference[Block], ) -> BankBlock: assert isinstance(reference, NullableReference) return await self._add_to_link(await FlowBlock.link_of(reference), reference) diff --git a/rainbowadn/flow13/_bankflow.py b/rainbowadn/flow13/_bankflow.py index a1faeb1..f716339 100644 --- a/rainbowadn/flow13/_bankflow.py +++ b/rainbowadn/flow13/_bankflow.py @@ -15,15 +15,13 @@ from ._flowstandard import * from ._flowtransaction import * from ._flowunion import * -__all__ = ('BankFlow',) +__all__ = ("BankFlow",) Link: TypeAlias = IPair[FlowCheque, FlowBank] class BankFlow( - Verification[ - tuple[Nullable[FlowBank], FlowCheque, FlowBank] - ], + Verification[tuple[Nullable[FlowBank], FlowCheque, FlowBank]], ): def __init__(self, initial: FlowBank): assert isinstance(initial, FlowBank) @@ -31,10 +29,10 @@ class BankFlow( @classmethod async def _verify_disjoint_union( - cls, - per_previous: FlowStandard[FlowCoin], - per_cheque: FlowStandard[FlowCoin], - per_bank: FlowStandard[FlowCoin], + cls, + per_previous: FlowStandard[FlowCoin], + per_cheque: FlowStandard[FlowCoin], + per_bank: FlowStandard[FlowCoin], ) -> bool: assert isinstance(per_previous, FlowStandard) assert isinstance(per_cheque, FlowStandard) @@ -57,10 +55,10 @@ class BankFlow( @classmethod async def _verify( - cls, - previous: FlowBank, - cheque: FlowCheque, - bank: FlowBank, + cls, + previous: FlowBank, + cheque: FlowCheque, + bank: FlowBank, ) -> bool: assert isinstance(previous, FlowBank) assert isinstance(cheque, FlowCheque) @@ -87,9 +85,7 @@ class BankFlow( return True async def verify_used_were_minted(): - assert_true( - await cheque.used.verify_subset(UnitReducer(bank.minted)) - ) + assert_true(await cheque.used.verify_subset(UnitReducer(bank.minted))) return True assert_trues( @@ -102,10 +98,7 @@ class BankFlow( ) return True - async def verify( - self, - element: tuple[Nullable[FlowBank], FlowCheque, FlowBank] - ) -> bool: + async def verify(self, element: tuple[Nullable[FlowBank], FlowCheque, FlowBank]) -> bool: assert isinstance(element, tuple) previous: Nullable[FlowBank] cheque: FlowCheque @@ -140,9 +133,7 @@ class BankFlow( ) return FlowBank(minted, used) - def link_verification(self) -> Verification[ - tuple[Nullable[HashPoint[Link]], HashPoint[Link]] - ]: + def link_verification(self) -> Verification[tuple[Nullable[HashPoint[Link]], HashPoint[Link]]]: class Decomposition(Mapper[HashPoint[Link], tuple[FlowCheque, FlowBank]]): async def map(self, element: HashPoint[Link]) -> tuple[FlowCheque, FlowBank]: assert isinstance(element, HashPoint) @@ -159,12 +150,7 @@ class BankFlow( return cheque, bank svf: SVF[FlowCheque, FlowBank, HashPoint[Link]] = SVF() - return svf.make( - Decomposition(), - self.loose() - ) + return svf.make(Decomposition(), self.loose()) - def loose(self) -> Verification[ - tuple[Nullable[FlowBank], FlowCheque, FlowBank] - ]: + def loose(self) -> Verification[tuple[Nullable[FlowBank], FlowCheque, FlowBank]]: return self diff --git a/rainbowadn/flow13/_binaryflow.py b/rainbowadn/flow13/_binaryflow.py index 2c7e850..aa0c2e8 100644 --- a/rainbowadn/flow13/_binaryflow.py +++ b/rainbowadn/flow13/_binaryflow.py @@ -7,21 +7,22 @@ from rainbowadn.collection.trees.binary.core import BinaryProtocolized from rainbowadn.core import * from rainbowadn.flow.core import * -__all__ = ('BinaryReducer', 'VerifySubsetAction', 'CheckResult',) +__all__ = ( + "BinaryReducer", + "VerifySubsetAction", + "CheckResult", +) -KeyT = TypeVar('KeyT', bound=Mentionable) -MetadataT = TypeVar('MetadataT', bound=Mentionable) -TreeT = TypeVar('TreeT') -Out = TypeVar('Out') +KeyT = TypeVar("KeyT", bound=Mentionable) +MetadataT = TypeVar("MetadataT", bound=Mentionable) +TreeT = TypeVar("TreeT") +Out = TypeVar("Out") BP: TypeAlias = BinaryProtocolized[KeyT, MetadataT, TreeT] PBS: TypeAlias = ProtocolizedBinarySplit[KeyT, MetadataT, TreeT] -class BinaryReducer( - Reducer[HashPoint[KeyT], Out], - Generic[Out, KeyT, MetadataT, TreeT] -): +class BinaryReducer(Reducer[HashPoint[KeyT], Out], Generic[Out, KeyT, MetadataT, TreeT]): def __init__(self, protocolized: BP): assert isinstance(protocolized, BinaryProtocolized) self.protocolized = protocolized @@ -182,14 +183,12 @@ class VerifySubsetAction( ) return True case NotFound(): - raise ValueError('subset check failed') + raise ValueError("subset check failed") case _: raise TypeError -class VerifySubsetReduce( - PureReduce[CheckResult] -): +class VerifySubsetReduce(PureReduce[CheckResult]): def pure(self, left: CheckResult, right: CheckResult) -> CheckResult: return max(left, right) diff --git a/rainbowadn/flow13/_flowbank.py b/rainbowadn/flow13/_flowbank.py index fbd982d..d4fa4da 100644 --- a/rainbowadn/flow13/_flowbank.py +++ b/rainbowadn/flow13/_flowbank.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from typing import Iterable from rainbowadn.collection.comparison import * @@ -6,18 +8,18 @@ from rainbowadn.core import * from ._flowstandard import * from ._flowtransaction import * -__all__ = ('FlowBank',) +__all__ = ("FlowBank",) class FlowBank(StaticMentionable, RecursiveMentionable): @classmethod - def from_bytes(cls, source: bytes, resolver: HashResolver) -> 'FlowBank': + def from_bytes(cls, source: bytes, resolver: HashResolver) -> FlowBank: return FlowBank( FlowStandardFactory.of(FlowCoin.factory(), HashComparator(Fail())).from_bytes( - source[:HashPoint.HASH_LENGTH], resolver + source[: HashPoint.HASH_LENGTH], resolver ), FlowStandardFactory.of(FlowCoin.factory(), HashComparator(Fail())).from_bytes( - source[HashPoint.HASH_LENGTH:], resolver + source[HashPoint.HASH_LENGTH :], resolver ), ) @@ -28,9 +30,9 @@ class FlowBank(StaticMentionable, RecursiveMentionable): return bytes(self.minted) + bytes(self.used) def __init__( - self, - minted: FlowStandard[FlowCoin], - used: FlowStandard[FlowCoin], + self, + minted: FlowStandard[FlowCoin], + used: FlowStandard[FlowCoin], ): assert isinstance(minted, FlowStandard) assert isinstance(used, FlowStandard) @@ -38,7 +40,7 @@ class FlowBank(StaticMentionable, RecursiveMentionable): self.used = used @classmethod - def empty(cls) -> 'FlowBank': + def empty(cls) -> FlowBank: return FlowBank( FlowStandardFactory.empty(FlowCoin.factory(), HashComparator(Fail())), FlowStandardFactory.empty(FlowCoin.factory(), HashComparator(Fail())), @@ -46,8 +48,10 @@ class FlowBank(StaticMentionable, RecursiveMentionable): async def str(self, tab: int) -> str: assert isinstance(tab, int) - return f'(' \ - f'{tabulate(tab + 1)}bank' \ - f'{tabulate(tab + 1)}(minted)' \ - f'{tabulate(tab + 1)}(used)' \ - f'{tabulate(tab)})' + return ( + f"(" + f"{tabulate(tab + 1)}bank" + f"{tabulate(tab + 1)}(minted)" + f"{tabulate(tab + 1)}(used)" + f"{tabulate(tab)})" + ) diff --git a/rainbowadn/flow13/_flowblock.py b/rainbowadn/flow13/_flowblock.py index 4554171..6cfd0de 100644 --- a/rainbowadn/flow13/_flowblock.py +++ b/rainbowadn/flow13/_flowblock.py @@ -1,4 +1,6 @@ -from typing import Callable, Generic, Iterable, TypeAlias, TypeVar +from __future__ import annotations + +from typing import Generic, Iterable, TypeAlias, TypeVar from rainbowadn.collection.comparison import * from rainbowadn.core import * @@ -7,9 +9,14 @@ from rainbowadn.nullability import * from ._flowstandard import * -__all__ = ('FlowBlock', 'FlowBlockFactory', 'FlowBlockVerification', 'FBVF',) +__all__ = ( + "FlowBlock", + "FlowBlockFactory", + "FlowBlockVerification", + "FBVF", +) -LinkT = TypeVar('LinkT', bound=Mentionable) +LinkT = TypeVar("LinkT", bound=Mentionable) class FlowBlock(Generic[LinkT], RecursiveMentionable): @@ -19,14 +26,14 @@ class FlowBlock(Generic[LinkT], RecursiveMentionable): def __bytes__(self): return bytes(self.previous) + bytes(self.index) + bytes(self.link) - def __factory__(self) -> RainbowFactory['FBL']: + def __factory__(self) -> RainbowFactory[FBL]: return FlowBlockFactory(self.link.factory) def __init__( - self, - previous: NullableReference['FBL'], - index: 'Index', - link: HashPoint[LinkT], + self, + previous: NullableReference[FBL], + index: Index, + link: HashPoint[LinkT], ): assert isinstance(previous, NullableReference) assert isinstance(index, FlowStandard) @@ -34,95 +41,73 @@ class FlowBlock(Generic[LinkT], RecursiveMentionable): self.index = index self.link = link - async def outer(self) -> 'Index': - return FlowStandard( - ( - await self.index.protocolized.tree.add( - HashPoint.of(self) - ) - ).protocolized() - ) + async def outer(self) -> Index: + return FlowStandard((await self.index.protocolized.tree.add(HashPoint.of(self))).protocolized()) - async def verify_outer_matches(self, index: 'Index') -> bool: + async def verify_outer_matches(self, index: Index) -> bool: assert_eq(await self.outer(), index) return True @classmethod - async def outer_of(cls, factory: RainbowFactory[LinkT], reference: NullableReference['FBL']) -> 'Index': + async def outer_of(cls, factory: RainbowFactory[LinkT], reference: NullableReference[FBL]) -> Index: if reference.null(): return FlowStandardFactory.empty(FlowBlockFactory(factory), HashComparator(Fail())) else: return await (await reference.resolve()).outer() @classmethod - async def link_of(cls, reference: NullableReference['FBL']) -> Nullable[LinkT]: + async def link_of(cls, reference: NullableReference[FBL]) -> Nullable[LinkT]: if reference.null(): return Null() else: return NotNull(await (await reference.resolve()).link.resolve()) - async def add(self, link: HashPoint[LinkT]) -> 'FBL': - return FlowBlock( - NullableReference.off(self), - await self.outer(), - link - ) + async def add(self, link: HashPoint[LinkT]) -> FBL: + return FlowBlock(NullableReference.off(self), await self.outer(), link) @classmethod - async def add_to(cls, reference: NullableReference['FBL'], link: HashPoint[LinkT]) -> 'FBL': - return FlowBlock( - reference, - await cls.outer_of(link.factory, reference), - link - ) + async def add_to(cls, reference: NullableReference[FBL], link: HashPoint[LinkT]) -> FBL: + return FlowBlock(reference, await cls.outer_of(link.factory, reference), link) async def str(self, tab: int) -> str: assert isinstance(tab, int) previous_str: str link_str: str - previous_str, link_str = await gather( - self.previous.str(tab), - hash_point_format(self.link, tab) - ) + previous_str, link_str = await gather(self.previous.str(tab), hash_point_format(self.link, tab)) assert isinstance(previous_str, str) assert isinstance(link_str, str) - return f'{previous_str}' \ - f'{tabulate(tab)}(index)' \ - f'{tabulate(tab)}{link_str}' + return f"{previous_str}" f"{tabulate(tab)}(index)" f"{tabulate(tab)}{link_str}" -class FlowBlockFactory(RainbowFactory['FBL'], Generic[LinkT]): +class FlowBlockFactory(RainbowFactory["FBL"], Generic[LinkT]): def __init__(self, factory: RainbowFactory[LinkT]): assert isinstance(factory, RainbowFactory) self.factory = factory - def from_bytes(self, source: bytes, resolver: HashResolver) -> 'FBL': + def from_bytes(self, source: bytes, resolver: HashResolver) -> FBL: assert isinstance(source, bytes) assert isinstance(resolver, HashResolver) return FlowBlock( - NullableReference.f(self).from_bytes(source[:HashPoint.HASH_LENGTH], resolver), + NullableReference.f(self).from_bytes(source[: HashPoint.HASH_LENGTH], resolver), FlowStandardFactory.of(self, HashComparator(Fail())).from_bytes( - source[HashPoint.HASH_LENGTH:2 * HashPoint.HASH_LENGTH], resolver + source[HashPoint.HASH_LENGTH : 2 * HashPoint.HASH_LENGTH], resolver ), - ResolverOrigin(self.factory, source[2 * HashPoint.HASH_LENGTH:], resolver).hash_point(), + ResolverOrigin(self.factory, source[2 * HashPoint.HASH_LENGTH :], resolver).hash_point(), ) - def loose(self) -> RainbowFactory['FBL']: + def loose(self) -> RainbowFactory[FBL]: return self -FBL: TypeAlias = 'FlowBlock[LinkT]' +FBL: TypeAlias = FlowBlock[LinkT] Index: TypeAlias = FlowStandard[FBL] -class FlowBlockIndexedVerification( - Verification[HashPoint[FBL]], - Generic[LinkT] -): +class FlowBlockIndexedVerification(Verification[HashPoint[FBL]], Generic[LinkT]): def __init__( - self, - index: Index, - verification: Verification[tuple[Nullable[HashPoint[LinkT]], HashPoint[LinkT]]], + self, + index: Index, + verification: Verification[tuple[Nullable[HashPoint[LinkT]], HashPoint[LinkT]]], ): assert isinstance(index, FlowStandard) assert isinstance(verification, Verification) @@ -133,9 +118,7 @@ class FlowBlockIndexedVerification( assert isinstance(block, FlowBlock) assert_trues( await gather( - self.verification.verify( - (Null(), block.link) - ), + self.verification.verify((Null(), block.link)), block.index.verify_empty(), ) ) @@ -146,9 +129,7 @@ class FlowBlockIndexedVerification( assert isinstance(block, FlowBlock) assert_trues( await gather( - self.verification.verify( - (NotNull(previous.link), block.link) - ), + self.verification.verify((NotNull(previous.link), block.link)), previous.verify_outer_matches(block.index), ) ) @@ -175,22 +156,17 @@ class FlowBlockIndexedVerification( return self -class FlowBlockVerification( - Verification[Index], - Generic[LinkT] -): +class FlowBlockVerification(Verification[Index], Generic[LinkT]): def __init__( - self, - verification: Verification[tuple[Nullable[HashPoint[LinkT]], HashPoint[LinkT]]], + self, + verification: Verification[tuple[Nullable[HashPoint[LinkT]], HashPoint[LinkT]]], ): assert isinstance(verification, Verification) self.verification = verification async def verify(self, element: Index) -> bool: assert_true( - await ReduceVerification( - FlowBlockIndexedVerification(element, self.verification).loose() - ).verify( + await ReduceVerification(FlowBlockIndexedVerification(element, self.verification).loose()).verify( await element.reducer() ) ) @@ -202,7 +178,6 @@ class FlowBlockVerification( class FBVF(Generic[LinkT]): def make( - self, - verification: Verification[tuple[Nullable[HashPoint[LinkT]], HashPoint[LinkT]]] + self, verification: Verification[tuple[Nullable[HashPoint[LinkT]], HashPoint[LinkT]]] ) -> Verification[Index]: return FlowBlockVerification(verification) diff --git a/rainbowadn/flow13/_flowcheque.py b/rainbowadn/flow13/_flowcheque.py index 49f2e47..282d816 100644 --- a/rainbowadn/flow13/_flowcheque.py +++ b/rainbowadn/flow13/_flowcheque.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import itertools from typing import Iterable @@ -13,7 +15,7 @@ from ._flowstandard import * from ._flowtransaction import * from ._resolvemapper import * -__all__ = ('FlowCheque',) +__all__ = ("FlowCheque",) class SumReduce(PureReduce[int]): @@ -29,23 +31,20 @@ class ValueMapper(Mapper[HashPoint[FlowCoin], int]): class FlowCheque(StaticMentionable, RecursiveMentionable): @classmethod - def from_bytes(cls, source: bytes, resolver: HashResolver) -> 'FlowCheque': + def from_bytes(cls, source: bytes, resolver: HashResolver) -> FlowCheque: return FlowCheque( FlowStandardFactory.of(FlowTransaction.factory(), HashComparator(Fail())).from_bytes( - source[:HashPoint.HASH_LENGTH], resolver + source[: HashPoint.HASH_LENGTH], resolver ), FlowStandardFactory.of(FlowCoin.factory(), HashComparator(Fail())).from_bytes( - source[HashPoint.HASH_LENGTH:2 * HashPoint.HASH_LENGTH], resolver + source[HashPoint.HASH_LENGTH : 2 * HashPoint.HASH_LENGTH], resolver ), FlowStandardFactory.of(FlowCoin.factory(), HashComparator(Fail())).from_bytes( - source[2 * HashPoint.HASH_LENGTH:3 * HashPoint.HASH_LENGTH], resolver + source[2 * HashPoint.HASH_LENGTH : 3 * HashPoint.HASH_LENGTH], resolver ), FlowStandardFactory.of( - KeyValue.f(FlowCoin.factory(), FlowTransaction.factory()), - KeyedComparator(HashComparator(Fail())) - ).from_bytes( - source[3 * HashPoint.HASH_LENGTH:], resolver - ), + KeyValue.f(FlowCoin.factory(), FlowTransaction.factory()), KeyedComparator(HashComparator(Fail())) + ).from_bytes(source[3 * HashPoint.HASH_LENGTH :], resolver), ) def points(self) -> Iterable[HashPoint]: @@ -55,11 +54,11 @@ class FlowCheque(StaticMentionable, RecursiveMentionable): return bytes(self.transactions) + bytes(self.minted) + bytes(self.used) + bytes(self.usedx) def __init__( - self, - transactions: FlowStandard[FlowTransaction], - minted: FlowStandard[FlowCoin], - used: FlowStandard[FlowCoin], - usedx: FlowStandard[KeyValue[FlowCoin, FlowTransaction]], + self, + transactions: FlowStandard[FlowTransaction], + minted: FlowStandard[FlowCoin], + used: FlowStandard[FlowCoin], + usedx: FlowStandard[KeyValue[FlowCoin, FlowTransaction]], ): assert isinstance(transactions, FlowStandard) assert isinstance(minted, FlowStandard) @@ -108,27 +107,19 @@ class FlowCheque(StaticMentionable, RecursiveMentionable): return True async def _verify_transactions(self) -> bool: - assert_true( - await self.transactions.verify(TransactionVerification(self).loose()) - ) + assert_true(await self.transactions.verify(TransactionVerification(self).loose())) return True async def _verify_minted(self) -> bool: - assert_true( - await self.minted.verify(MintedVerification(self).loose()) - ) + assert_true(await self.minted.verify(MintedVerification(self).loose())) return True async def _verify_used(self) -> bool: - assert_true( - await self.used.verify(UsedVerification(self).loose()) - ) + assert_true(await self.used.verify(UsedVerification(self).loose())) return True async def _verify_usedx(self) -> bool: - assert_true( - await self.usedx.verify(UsedXVerification(self).loose()) - ) + assert_true(await self.usedx.verify(UsedXVerification(self).loose())) return True async def verify(self) -> bool: @@ -156,22 +147,14 @@ class FlowCheque(StaticMentionable, RecursiveMentionable): @classmethod async def _transaction_usedx(cls, transaction: FlowTransaction) -> Iterable[KeyValue[FlowCoin, FlowTransaction]]: assert isinstance(transaction, FlowTransaction) - return ( - KeyValue.of(coin, transaction) - for - coin - in - await cls._transaction_used(transaction) - ) + return (KeyValue.of(coin, transaction) for coin in await cls._transaction_used(transaction)) @classmethod async def _make_minted(cls, transactions: Iterable[FlowTransaction]) -> FlowStandard[FlowCoin]: return await FlowStandardFactory.off( FlowCoin.factory(), HashComparator(Fail()), - itertools.chain( - *(await gather(*(cls._transaction_minted(transaction) for transaction in transactions))) - ) + itertools.chain(*(await gather(*(cls._transaction_minted(transaction) for transaction in transactions)))), ) @classmethod @@ -179,26 +162,21 @@ class FlowCheque(StaticMentionable, RecursiveMentionable): return await FlowStandardFactory.off( FlowCoin.factory(), HashComparator(Fail()), - itertools.chain( - *(await gather(*(cls._transaction_used(transaction) for transaction in transactions))) - ), + itertools.chain(*(await gather(*(cls._transaction_used(transaction) for transaction in transactions)))), ) @classmethod async def _make_usedx( - cls, - transactions: Iterable[FlowTransaction] + cls, transactions: Iterable[FlowTransaction] ) -> FlowStandard[KeyValue[FlowCoin, FlowTransaction]]: return await FlowStandardFactory.off( KeyValue.f(FlowCoin.factory(), FlowTransaction.factory()), KeyedComparator(HashComparator(Fail())), - itertools.chain( - *(await gather(*(cls._transaction_usedx(transaction) for transaction in transactions))) - ) + itertools.chain(*(await gather(*(cls._transaction_usedx(transaction) for transaction in transactions)))), ) @classmethod - async def make(cls, transactions: Iterable[FlowTransaction]) -> 'FlowCheque': + async def make(cls, transactions: Iterable[FlowTransaction]) -> FlowCheque: transactions_standard: FlowStandard[FlowTransaction] minted: FlowStandard[FlowCoin] used: FlowStandard[FlowCoin] @@ -222,13 +200,15 @@ class FlowCheque(StaticMentionable, RecursiveMentionable): async def str(self, tab: int) -> str: assert isinstance(tab, int) - return f'(' \ - f'{tabulate(tab + 1)}cheque' \ - f'{tabulate(tab + 1)}{await self.transactions.str(tab + 1)}' \ - f'{tabulate(tab + 1)}(minted)' \ - f'{tabulate(tab + 1)}(used)' \ - f'{tabulate(tab + 1)}(usedx)' \ - f'{tabulate(tab)})' + return ( + f"(" + f"{tabulate(tab + 1)}cheque" + f"{tabulate(tab + 1)}{await self.transactions.str(tab + 1)}" + f"{tabulate(tab + 1)}(minted)" + f"{tabulate(tab + 1)}(used)" + f"{tabulate(tab + 1)}(usedx)" + f"{tabulate(tab)})" + ) class UsedxMapper(Mapper[HashPoint[FlowCoin], HashPoint[KeyValue[FlowCoin, FlowTransaction]]]): @@ -237,53 +217,35 @@ class UsedxMapper(Mapper[HashPoint[FlowCoin], HashPoint[KeyValue[FlowCoin, FlowT self.transaction = transaction async def map(self, element: HashPoint[FlowCoin]) -> HashPoint[KeyValue[FlowCoin, FlowTransaction]]: - return HashPoint.of( - await KeyValue.off( - element, - self.transaction - ) - ) + return HashPoint.of(await KeyValue.off(element, self.transaction)) -class TransactionVerification( - Verification[HashPoint[FlowTransaction]] -): +class TransactionVerification(Verification[HashPoint[FlowTransaction]]): def __init__(self, cheque: FlowCheque): assert isinstance(cheque, FlowCheque) self.cheque = cheque @classmethod def _usedx_reducer( - cls, - reducer: Reducer[HashPoint[FlowCoin], bool], - transaction: HashPoint[FlowTransaction] + cls, reducer: Reducer[HashPoint[FlowCoin], bool], transaction: HashPoint[FlowTransaction] ) -> Reducer[HashPoint[KeyValue[FlowCoin, FlowTransaction]], bool]: assert isinstance(reducer, Reducer) assert isinstance(transaction, HashPoint) usedx_reducer: Reducer[HashPoint[KeyValue[FlowCoin, FlowTransaction]], bool] = MapReducer( - UsedxMapper(transaction), - reducer + UsedxMapper(transaction), reducer ) assert isinstance(usedx_reducer, Reducer) return usedx_reducer async def _verify_transaction_minted(self, transaction: FlowTransaction) -> bool: assert isinstance(transaction, FlowTransaction) - assert_true( - await self.cheque.minted.verify_contains_all( - await transaction.minted_reducer() - ) - ) + assert_true(await self.cheque.minted.verify_contains_all(await transaction.minted_reducer())) return True async def _verify_transaction_used(self, transaction: FlowTransaction) -> bool: assert isinstance(transaction, FlowTransaction) - assert_true( - await self.cheque.used.verify_contains_all( - await transaction.used_reducer() - ) - ) + assert_true(await self.cheque.used.verify_contains_all(await transaction.used_reducer())) return True async def _verify_transaction_usedx(self, transaction: FlowTransaction) -> bool: @@ -313,30 +275,21 @@ class TransactionVerification( return self -class MintedVerification( - Verification[HashPoint[FlowCoin]] -): +class MintedVerification(Verification[HashPoint[FlowCoin]]): def __init__(self, cheque: FlowCheque): assert isinstance(cheque, FlowCheque) self.cheque = cheque async def verify(self, element: HashPoint[FlowCoin]) -> bool: assert isinstance(element, HashPoint) - assert_true( - await self.cheque.transactions.contains( - (await element.resolve()).transaction, - exact=True - ) - ) + assert_true(await self.cheque.transactions.contains((await element.resolve()).transaction, exact=True)) return True def loose(self) -> Verification[HashPoint[FlowCoin]]: return self -class UsedVerification( - Verification[HashPoint[FlowCoin]] -): +class UsedVerification(Verification[HashPoint[FlowCoin]]): def __init__(self, cheque: FlowCheque): assert isinstance(cheque, FlowCheque) self.cheque = cheque @@ -345,8 +298,7 @@ class UsedVerification( assert isinstance(element, HashPoint) assert_true( await self.cheque.usedx.contains( - HashPoint.of(await KeyValue.off(element, HashPoint.of(FlowTransaction.empty()))), - exact=False + HashPoint.of(await KeyValue.off(element, HashPoint.of(FlowTransaction.empty()))), exact=False ) ) return True @@ -355,45 +307,28 @@ class UsedVerification( return self -class UsedXVerification( - Verification[HashPoint[KeyValue[FlowCoin, FlowTransaction]]] -): +class UsedXVerification(Verification[HashPoint[KeyValue[FlowCoin, FlowTransaction]]]): def __init__(self, cheque: FlowCheque): assert isinstance(cheque, FlowCheque) self.cheque = cheque async def _verify_transaction_registred(self, transaction: HashPoint[FlowTransaction]) -> bool: assert isinstance(transaction, HashPoint) - assert_true( - await self.cheque.transactions.contains( - transaction, - exact=True - ) - ) + assert_true(await self.cheque.transactions.contains(transaction, exact=True)) return True @classmethod async def _verify_coin_contained_in_transaction( - cls, transaction: HashPoint[FlowTransaction], coin: HashPoint[FlowCoin] + cls, transaction: HashPoint[FlowTransaction], coin: HashPoint[FlowCoin] ) -> bool: assert isinstance(transaction, HashPoint) assert isinstance(coin, HashPoint) - assert_true( - await (await transaction.resolve()).data.in_coins.contains( - coin, - exact=True - ) - ) + assert_true(await (await transaction.resolve()).data.in_coins.contains(coin, exact=True)) return True async def _verify_coin_registred_as_used(self, coin: HashPoint[FlowCoin]) -> bool: assert isinstance(coin, HashPoint) - assert_true( - await self.cheque.used.contains( - coin, - exact=True - ) - ) + assert_true(await self.cheque.used.contains(coin, exact=True)) return True async def _verify(self, pair: KeyValue[FlowCoin, FlowTransaction]): diff --git a/rainbowadn/flow13/_flowiterate.py b/rainbowadn/flow13/_flowiterate.py index 9922e73..094db1f 100644 --- a/rainbowadn/flow13/_flowiterate.py +++ b/rainbowadn/flow13/_flowiterate.py @@ -2,15 +2,12 @@ from typing import Generic, Iterable, TypeVar from rainbowadn.flow.core import * -__all__ = ('FlowIterate',) +__all__ = ("FlowIterate",) -Element = TypeVar('Element') +Element = TypeVar("Element") -class FlowIterate( - Reduce[Element, Iterable[Element]], - Generic[Element] -): +class FlowIterate(Reduce[Element, Iterable[Element]], Generic[Element]): def __init__(self): super().__init__(()) @@ -32,8 +29,5 @@ class FlowIterate( return self @classmethod - async def iterate( - cls, - reducer: Reducer[Element, Iterable[Element]] - ) -> Iterable[Element]: + async def iterate(cls, reducer: Reducer[Element, Iterable[Element]]) -> Iterable[Element]: return await reducer.reduce(cls()) diff --git a/rainbowadn/flow13/_flowstandard.py b/rainbowadn/flow13/_flowstandard.py index 0099e6e..9557967 100644 --- a/rainbowadn/flow13/_flowstandard.py +++ b/rainbowadn/flow13/_flowstandard.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from typing import Any, Generic, Iterable, Optional, TypeAlias, TypeVar from rainbowadn.atomic import * @@ -15,29 +17,25 @@ from rainbowadn.nullability import * from ._binaryflow import * from ._flowtree import * -__all__ = ('FlowStandard', 'FlowStandardFactory',) +__all__ = ( + "FlowStandard", + "FlowStandardFactory", +) -KeyT = TypeVar('KeyT', bound=Mentionable) -ABT: TypeAlias = 'ActiveBinaryTree[KeyT, Integer]' -BP: TypeAlias = 'BinaryProtocolized[KeyT, Integer, ABT]' +KeyT = TypeVar("KeyT", bound=Mentionable) +ABT: TypeAlias = "ActiveBinaryTree[KeyT, Integer]" +BP: TypeAlias = "BinaryProtocolized[KeyT, Integer, ABT]" -class FlowStandard( - RecursiveMentionable, - FlowTree[HashPoint[KeyT], 'FS'], - Generic[KeyT] -): +class FlowStandard(RecursiveMentionable, FlowTree[HashPoint[KeyT], "FS"], Generic[KeyT]): def points(self) -> Iterable[HashPoint]: return self.protocolized.tree.reference.points() def __bytes__(self): return bytes(self.protocolized.tree.reference) - def __factory__(self) -> RainbowFactory['FlowStandard[KeyT]']: - return FlowStandardFactory( - self.protocolized.tree.reference.factory, - self.protocolized.creation.comparator - ) + def __factory__(self) -> RainbowFactory[FlowStandard[KeyT]]: + return FlowStandardFactory(self.protocolized.tree.reference.factory, self.protocolized.creation.comparator) def __init__(self, protocolized: BP): assert isinstance(protocolized, BinaryProtocolized) @@ -46,27 +44,21 @@ class FlowStandard( async def contains(self, key: HashPoint[KeyT], *, exact: bool) -> bool: return await self.protocolized.tree.contains(key, exact=exact) - def _protocolized(self: 'FS') -> BP: + def _protocolized(self: FS) -> BP: return self.protocolized @classmethod - def _protocolized_mapper(cls) -> Mapper['FS', BP]: + def _protocolized_mapper(cls) -> Mapper[FS, BP]: return CallableMapper(FlowStandard._protocolized) - async def verify_subset(self, trees: Reducer['FS', CheckResult]) -> bool: + async def verify_subset(self, trees: Reducer[FS, CheckResult]) -> bool: assert isinstance(trees, Reducer) reducer: Reducer[BP, CheckResult] = MapReducer(self._protocolized_mapper(), trees) assert_true(await VerifySubsetAction(reducer).on(self.protocolized)) return True async def verify_empty(self) -> bool: - assert_true( - await ReduceVerification( - MapperVerification(ConstMapper(False)) - ).verify( - await self.reducer() - ) - ) + assert_true(await ReduceVerification(MapperVerification(ConstMapper(False))).verify(await self.reducer())) return True async def reducer(self) -> Reducer[HashPoint[KeyT], Any]: @@ -83,37 +75,30 @@ class FlowStandard( return await self.protocolized.tree.reference.str(tab) -FS: TypeAlias = 'FlowStandard[KeyT]' +FS: TypeAlias = "FlowStandard[KeyT]" class FlowStandardFactory(Inlining[FlowStandard[KeyT]], Generic[KeyT]): - def __init__( - self, - factory: RainbowFactory[BinaryTree[KeyMetadata[KeyT, Integer]]], - comparator: Comparator[KeyT] - ): + def __init__(self, factory: RainbowFactory[BinaryTree[KeyMetadata[KeyT, Integer]]], comparator: Comparator[KeyT]): assert isinstance(factory, RainbowFactory) assert isinstance(comparator, Comparator) - self.factory: RainbowFactory[ - NullableReference[BinaryTree[KeyMetadata[KeyT, Integer]]] - ] = NullableReference.f(factory) + self.factory: RainbowFactory[NullableReference[BinaryTree[KeyMetadata[KeyT, Integer]]]] = NullableReference.f( + factory + ) self.comparator = comparator def size(self) -> Optional[int]: return Inlining.factory_size(self.factory) @classmethod - def of(cls, factory: RainbowFactory[KeyT], comparator: Comparator[KeyT]) -> 'FlowStandardFactory[KeyT]': + def of(cls, factory: RainbowFactory[KeyT], comparator: Comparator[KeyT]) -> FlowStandardFactory[KeyT]: assert isinstance(factory, RainbowFactory) - return FlowStandardFactory( - BinaryTreeFactory(KeyMetadataFactory(factory, Integer.factory())), - comparator - ) + return FlowStandardFactory(BinaryTreeFactory(KeyMetadataFactory(factory, Integer.factory())), comparator) @classmethod async def off( - cls, factory: RainbowFactory[KeyT], comparator: Comparator[KeyT], keys: Iterable[KeyT] - ) -> 'FlowStandard[KeyT]': + cls, factory: RainbowFactory[KeyT], comparator: Comparator[KeyT], keys: Iterable[KeyT] + ) -> FlowStandard[KeyT]: assert isinstance(factory, RainbowFactory) abt: ActiveBinaryTree[KeyT, Integer] = cls.empty(factory, comparator).protocolized.tree for key in keys: @@ -125,18 +110,13 @@ class FlowStandardFactory(Inlining[FlowStandard[KeyT]], Generic[KeyT]): return AVL(comparator) @classmethod - def empty(cls, factory: RainbowFactory[KeyT], comparator: Comparator[KeyT]) -> 'FlowStandard[KeyT]': + def empty(cls, factory: RainbowFactory[KeyT], comparator: Comparator[KeyT]) -> FlowStandard[KeyT]: assert isinstance(factory, RainbowFactory) - return FlowStandard( - ActiveBinaryTree.empty(cls.protocol(comparator), factory).protocolized() - ) + return FlowStandard(ActiveBinaryTree.empty(cls.protocol(comparator), factory).protocolized()) def from_bytes(self, source: bytes, resolver: HashResolver) -> FlowStandard[KeyT]: assert isinstance(source, bytes) assert isinstance(resolver, HashResolver) return FlowStandard( - ActiveBinaryTree( - self.protocol(self.comparator), - self.factory.from_bytes(source, resolver) - ).protocolized() + ActiveBinaryTree(self.protocol(self.comparator), self.factory.from_bytes(source, resolver)).protocolized() ) diff --git a/rainbowadn/flow13/_flowtransaction.py b/rainbowadn/flow13/_flowtransaction.py index 4187320..c245ca7 100644 --- a/rainbowadn/flow13/_flowtransaction.py +++ b/rainbowadn/flow13/_flowtransaction.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from typing import Any, Iterable from nacl.signing import SigningKey @@ -13,15 +15,16 @@ from rainbowadn.v13 import * from ._flowstandard import * from ._resolvemapper import * -__all__ = ('FlowCoinData', 'FlowCoin', 'FlowTransactionData', 'FlowTransaction',) +__all__ = ( + "FlowCoinData", + "FlowCoin", + "FlowTransactionData", + "FlowTransaction", +) class FlowCoinData(RecursiveMentionable, StaticMentionable): - def __init__( - self, - owner: Subject, - value: HashPoint[Integer] - ): + def __init__(self, owner: Subject, value: HashPoint[Integer]): assert isinstance(owner, Subject) assert isinstance(value, HashPoint) self.owner = owner @@ -35,7 +38,7 @@ class FlowCoinData(RecursiveMentionable, StaticMentionable): return (await self.value.resolve()).integer @classmethod - def of(cls, owner: Subject, value: int) -> 'FlowCoinData': + def of(cls, owner: Subject, value: int) -> FlowCoinData: assert isinstance(owner, Subject) assert isinstance(value, int) return cls(owner, HashPoint.of(Integer(value))) @@ -47,7 +50,7 @@ class FlowCoinData(RecursiveMentionable, StaticMentionable): return bytes(self.owner) + bytes(self.value) @classmethod - def from_bytes(cls, source: bytes, resolver: HashResolver) -> 'FlowCoinData': + def from_bytes(cls, source: bytes, resolver: HashResolver) -> FlowCoinData: assert isinstance(source, bytes) assert isinstance(resolver, HashResolver) separation = Subject.size() @@ -58,16 +61,11 @@ class FlowCoinData(RecursiveMentionable, StaticMentionable): async def str(self, tab: int) -> str: assert isinstance(tab, int) - return f'{self.owner}' \ - f'{tabulate(tab)}{await hash_point_format(self.value, tab)}' + return f"{self.owner}" f"{tabulate(tab)}{await hash_point_format(self.value, tab)}" class FlowCoin(RecursiveMentionable, StaticMentionable): - def __init__( - self, - data: HashPoint[FlowCoinData], - transaction: HashPoint['FlowTransaction'] - ): + def __init__(self, data: HashPoint[FlowCoinData], transaction: HashPoint[FlowTransaction]): assert isinstance(data, HashPoint) assert isinstance(transaction, HashPoint) self.data = data @@ -87,23 +85,25 @@ class FlowCoin(RecursiveMentionable, StaticMentionable): return bytes(self.data) + bytes(self.transaction) @classmethod - def from_bytes(cls, source: bytes, resolver: HashResolver) -> 'FlowCoin': + def from_bytes(cls, source: bytes, resolver: HashResolver) -> FlowCoin: assert isinstance(source, bytes) assert isinstance(resolver, HashResolver) return cls( - ResolverOrigin(FlowCoinData.factory(), source[:HashPoint.HASH_LENGTH], resolver).hash_point(), + ResolverOrigin(FlowCoinData.factory(), source[: HashPoint.HASH_LENGTH], resolver).hash_point(), ResolverOrigin( - FlowTransaction.factory(), source[HashPoint.HASH_LENGTH:2 * HashPoint.HASH_LENGTH], resolver + FlowTransaction.factory(), source[HashPoint.HASH_LENGTH : 2 * HashPoint.HASH_LENGTH], resolver ).hash_point(), ) async def str(self, tab: int) -> str: assert isinstance(tab, int) - return f'(' \ - f'{tabulate(tab + 1)}coin' \ - f'{tabulate(tab + 1)}{await hash_point_format(self.data, tab + 1)}' \ - f'{tabulate(tab + 1)}(origin)' \ - f'{tabulate(tab)})' + return ( + f"(" + f"{tabulate(tab + 1)}coin" + f"{tabulate(tab + 1)}{await hash_point_format(self.data, tab + 1)}" + f"{tabulate(tab + 1)}(origin)" + f"{tabulate(tab)})" + ) async def int_value(self) -> int: return await (await self.data_resolved()).int_value() @@ -114,9 +114,9 @@ class FlowCoin(RecursiveMentionable, StaticMentionable): class FlowTransactionData(RecursiveMentionable, StaticMentionable): def __init__( - self, - in_coins: FlowStandard[FlowCoin], - out_coins: FlowStandard[FlowCoinData], + self, + in_coins: FlowStandard[FlowCoin], + out_coins: FlowStandard[FlowCoinData], ): assert isinstance(in_coins, FlowStandard) assert isinstance(out_coins, FlowStandard) @@ -132,78 +132,63 @@ class FlowTransactionData(RecursiveMentionable, StaticMentionable): return bytes(self.in_coins) + bytes(self.out_coins) @classmethod - def from_bytes(cls, source: bytes, resolver: HashResolver) -> 'FlowTransactionData': + def from_bytes(cls, source: bytes, resolver: HashResolver) -> FlowTransactionData: assert isinstance(source, bytes) assert isinstance(resolver, HashResolver) return cls( - FlowStandardFactory.of( - FlowCoin.factory(), HashComparator(Fail()) - ).from_bytes(source[:HashPoint.HASH_LENGTH], resolver), - FlowStandardFactory.of( - FlowCoinData.factory(), HashComparator(Fail()) - ).from_bytes(source[HashPoint.HASH_LENGTH:], resolver), + FlowStandardFactory.of(FlowCoin.factory(), HashComparator(Fail())).from_bytes( + source[: HashPoint.HASH_LENGTH], resolver + ), + FlowStandardFactory.of(FlowCoinData.factory(), HashComparator(Fail())).from_bytes( + source[HashPoint.HASH_LENGTH :], resolver + ), ) async def _signature_verify(self, coin: FlowCoin, signature: Signature) -> bool: assert isinstance(coin, FlowCoin) assert isinstance(signature, Signature) - assert_true( - signature.verify( - await coin.owner(), - self.hash_point - ) - ) + assert_true(signature.verify(await coin.owner(), self.hash_point)) return True @classmethod def _coin_verification_mapper( - cls, - signatures: FlowStandard[KeyValue[Subject, Signature]], - ) -> Mapper[ - HashPoint[FlowCoin], - bool - ]: + cls, + signatures: FlowStandard[KeyValue[Subject, Signature]], + ) -> Mapper[HashPoint[FlowCoin], bool]: assert isinstance(signatures, FlowStandard) return ResolveMapper.wrap_mapper(CVMapper(signatures).loose()) - def _signature_pair_verification_mapper(self) -> Mapper[ - HashPoint[KeyValue[Subject, Signature]], - bool - ]: + def _signature_pair_verification_mapper(self) -> Mapper[HashPoint[KeyValue[Subject, Signature]], bool]: return ResolveMapper.wrap_mapper(SPVMapper(self.hash_point).loose()) async def _verify_coin_signatures( - self, - signatures: FlowStandard[KeyValue[Subject, Signature]], + self, + signatures: FlowStandard[KeyValue[Subject, Signature]], ) -> bool: assert isinstance(signatures, FlowStandard) assert_true( - await ReduceVerification( - MapperVerification(self._coin_verification_mapper(signatures)) - ).loose().verify( - await self.in_coins.reducer() - ) + await ReduceVerification(MapperVerification(self._coin_verification_mapper(signatures))) + .loose() + .verify(await self.in_coins.reducer()) ) return True async def _verify_signature_pairs( - self, - signatures: FlowStandard[KeyValue[Subject, Signature]], + self, + signatures: FlowStandard[KeyValue[Subject, Signature]], ): assert isinstance(signatures, FlowStandard) assert_true( - await ReduceVerification( - MapperVerification(self._signature_pair_verification_mapper()) - ).loose().verify( - await signatures.reducer() - ) + await ReduceVerification(MapperVerification(self._signature_pair_verification_mapper())) + .loose() + .verify(await signatures.reducer()) ) return True async def _verify_signatures( - self, - signatures: FlowStandard[KeyValue[Subject, Signature]], + self, + signatures: FlowStandard[KeyValue[Subject, Signature]], ) -> bool: assert isinstance(signatures, FlowStandard) assert_trues( @@ -214,10 +199,7 @@ class FlowTransactionData(RecursiveMentionable, StaticMentionable): ) return True - async def verify( - self, - signatures: FlowStandard[KeyValue[Subject, Signature]] - ) -> bool: + async def verify(self, signatures: FlowStandard[KeyValue[Subject, Signature]]) -> bool: assert isinstance(signatures, FlowStandard) assert_true(await self._verify_signatures(signatures)) return True @@ -230,13 +212,10 @@ class FlowTransactionData(RecursiveMentionable, StaticMentionable): ) assert isinstance(in_str, str) assert isinstance(out_str, str) - return f'(in)' \ - f'{tabulate(tab)}{in_str}' \ - f'{tabulate(tab)}(out)' \ - f'{tabulate(tab)}{out_str}' + return f"(in)" f"{tabulate(tab)}{in_str}" f"{tabulate(tab)}(out)" f"{tabulate(tab)}{out_str}" @classmethod - def empty(cls) -> 'FlowTransactionData': + def empty(cls) -> FlowTransactionData: return cls( FlowStandardFactory.empty(FlowCoin.factory(), HashComparator(Fail())), FlowStandardFactory.empty(FlowCoinData.factory(), HashComparator(Fail())), @@ -252,8 +231,7 @@ class CVMapper(Mapper[FlowCoin, bool]): assert isinstance(element, FlowCoin) assert_true( await self.signatures.contains( - HashPoint.of(KeyValue.of(await element.owner(), Signature.empty())), - exact=False + HashPoint.of(KeyValue.of(await element.owner(), Signature.empty())), exact=False ) ) return True @@ -285,11 +263,7 @@ class SPVMapper(Mapper[KeyValue[Subject, Signature], bool]): class FlowTransaction(RecursiveMentionable, StaticMentionable): - def __init__( - self, - data: FlowTransactionData, - signatures: FlowStandard[KeyValue[Subject, Signature]] - ): + def __init__(self, data: FlowTransactionData, signatures: FlowStandard[KeyValue[Subject, Signature]]): assert isinstance(data, FlowTransactionData) assert isinstance(signatures, FlowStandard) self.data = data @@ -308,17 +282,14 @@ class FlowTransaction(RecursiveMentionable, StaticMentionable): return bytes(self.data) + bytes(self.signatures) @classmethod - def from_bytes(cls, source: bytes, resolver: HashResolver) -> 'FlowTransaction': + def from_bytes(cls, source: bytes, resolver: HashResolver) -> FlowTransaction: assert isinstance(source, bytes) assert isinstance(resolver, HashResolver) return cls( - FlowTransactionData.from_bytes(source[:-HashPoint.HASH_LENGTH], resolver), + FlowTransactionData.from_bytes(source[: -HashPoint.HASH_LENGTH], resolver), FlowStandardFactory.of( - KeyValue.f(Subject.factory(), Signature.factory()), - KeyedComparator(HashComparator(Fail())) - ).from_bytes( - source[-HashPoint.HASH_LENGTH:], resolver - ), + KeyValue.f(Subject.factory(), Signature.factory()), KeyedComparator(HashComparator(Fail())) + ).from_bytes(source[-HashPoint.HASH_LENGTH :], resolver), ) def _coin(self, data: HashPoint[FlowCoinData]) -> HashPoint[FlowCoin]: @@ -337,11 +308,13 @@ class FlowTransaction(RecursiveMentionable, StaticMentionable): async def str(self, tab: int) -> str: assert isinstance(tab, int) - return f'(' \ - f'{tabulate(tab + 1)}transaction' \ - f'{tabulate(tab + 1)}{await self.data.str(tab + 1)}' \ - f'{tabulate(tab + 1)}(signatures)' \ - f'{tabulate(tab)})' + return ( + f"(" + f"{tabulate(tab + 1)}transaction" + f"{tabulate(tab + 1)}{await self.data.str(tab + 1)}" + f"{tabulate(tab + 1)}(signatures)" + f"{tabulate(tab)})" + ) @classmethod def empty(cls): @@ -354,11 +327,11 @@ class FlowTransaction(RecursiveMentionable, StaticMentionable): @classmethod async def make( - cls, - used: Iterable[FlowCoin], - minted: Iterable[FlowCoinData], - keys: Iterable[SigningKey], - ) -> 'FlowTransaction': + cls, + used: Iterable[FlowCoin], + minted: Iterable[FlowCoinData], + keys: Iterable[SigningKey], + ) -> FlowTransaction: used_std: FlowStandard[FlowCoin] minted_std: FlowStandard[FlowCoinData] used_std, minted_std = await gather( @@ -376,14 +349,11 @@ class FlowTransaction(RecursiveMentionable, StaticMentionable): Subject(signing_key.verify_key), Signature.sign(signing_key, transaction_data.hash_point), ) - for - signing_key - in - keys + for signing_key in keys ] return cls( transaction_data, await FlowStandardFactory.off( KeyValue.f(Subject.factory(), Signature.factory()), KeyedComparator(HashComparator(Fail())), signatures - ) + ), ) diff --git a/rainbowadn/flow13/_flowtree.py b/rainbowadn/flow13/_flowtree.py index 01e9f9e..1f61136 100644 --- a/rainbowadn/flow13/_flowtree.py +++ b/rainbowadn/flow13/_flowtree.py @@ -1,13 +1,15 @@ +from __future__ import annotations + from typing import Any, Generic, TypeVar from rainbowadn.core import * from rainbowadn.flow.core import * from rainbowadn.flow.verification.core import * -__all__ = ('FlowTree',) +__all__ = ("FlowTree",) -Key = TypeVar('Key') -Tree = TypeVar('Tree') +Key = TypeVar("Key") +Tree = TypeVar("Tree") class FlowTree(Generic[Key, Tree]): @@ -28,7 +30,7 @@ class FlowTree(Generic[Key, Tree]): assert_true(await ReduceVerification(key_verification).loose().verify(keys)) return True - async def verify_subset(self: Tree, trees: Reducer['FlowTree[Key, Tree]', Any]) -> bool: + async def verify_subset(self: Tree, trees: Reducer[FlowTree[Key, Tree], Any]) -> bool: raise NotImplementedError async def reducer(self) -> Reducer[Key, Any]: @@ -36,13 +38,7 @@ class FlowTree(Generic[Key, Tree]): async def verify(self, verification: Verification[Key]) -> bool: assert isinstance(verification, Verification) - assert_true( - await ReduceVerification( - verification - ).loose().verify( - await self.reducer() - ) - ) + assert_true(await ReduceVerification(verification).loose().verify(await self.reducer())) return True diff --git a/rainbowadn/flow13/_flowunion.py b/rainbowadn/flow13/_flowunion.py index 96d539b..55f3a50 100644 --- a/rainbowadn/flow13/_flowunion.py +++ b/rainbowadn/flow13/_flowunion.py @@ -4,9 +4,9 @@ from rainbowadn.core import * from ._flowstandard import * -__all__ = ('flow_union',) +__all__ = ("flow_union",) -KeyT = TypeVar('KeyT', bound=Mentionable) +KeyT = TypeVar("KeyT", bound=Mentionable) async def flow_union(left: FlowStandard[KeyT], right: FlowStandard[KeyT]) -> FlowStandard[KeyT]: diff --git a/rainbowadn/flow13/_resolvemapper.py b/rainbowadn/flow13/_resolvemapper.py index 4d81eed..de8d27b 100644 --- a/rainbowadn/flow13/_resolvemapper.py +++ b/rainbowadn/flow13/_resolvemapper.py @@ -3,10 +3,10 @@ from typing import Generic, TypeVar from rainbowadn.core import * from rainbowadn.flow.core import * -__all__ = ('ResolveMapper',) +__all__ = ("ResolveMapper",) -MentionedT = TypeVar('MentionedT', bound=Mentionable) -Out = TypeVar('Out') +MentionedT = TypeVar("MentionedT", bound=Mentionable) +Out = TypeVar("Out") class ResolveMapper(Mapper[HashPoint[MentionedT], MentionedT], Generic[MentionedT]): diff --git a/rainbowadn/inlining/__init__.py b/rainbowadn/inlining/__init__.py index 659b5bf..e8c352a 100644 --- a/rainbowadn/inlining/__init__.py +++ b/rainbowadn/inlining/__init__.py @@ -1,12 +1,15 @@ __all__ = ( - 'IAtomic', - 'IAuto', 'Auto', 'IAutoFactory', - 'IByte', - 'Inlining', - 'IPair', - 'IRef', - 'IStatic', 'IStaticFactory', - 'IUnit', + "IAtomic", + "IAuto", + "Auto", + "IAutoFactory", + "IByte", + "Inlining", + "IPair", + "IRef", + "IStatic", + "IStaticFactory", + "IUnit", ) from .iatomic import IAtomic diff --git a/rainbowadn/inlining/iatomic.py b/rainbowadn/inlining/iatomic.py index bfed36d..417115d 100644 --- a/rainbowadn/inlining/iatomic.py +++ b/rainbowadn/inlining/iatomic.py @@ -5,14 +5,14 @@ from rainbowadn.core import * from .istatic import * -__all__ = ('IAtomic',) +__all__ = ("IAtomic",) -InlinedAtomic = TypeVar('InlinedAtomic') +InlinedAtomic = TypeVar("InlinedAtomic") class IAtomic(IStatic, abc.ABC): def __topology_hash__(self) -> bytes: - return HashPoint.hash(b'') + return HashPoint.hash(b"") @classmethod def from_bytes(cls: Type[InlinedAtomic], source: bytes, resolver: HashResolver) -> InlinedAtomic: diff --git a/rainbowadn/inlining/iauto.py b/rainbowadn/inlining/iauto.py index b1052ff..67c11de 100644 --- a/rainbowadn/inlining/iauto.py +++ b/rainbowadn/inlining/iauto.py @@ -1,30 +1,38 @@ +from __future__ import annotations + import heapq from typing import ( - Callable, Generic, Iterable, Optional, Type, TypeAlias, - TypeVar, overload + Callable, + Generic, + Iterable, + Optional, + Type, + TypeAlias, + TypeVar, + overload, ) from rainbowadn.core import * from .inlining import * -__all__ = ('IAuto', 'Auto', 'IAutoFactory',) +__all__ = ( + "IAuto", + "Auto", + "IAutoFactory", +) _IList: TypeAlias = list[tuple[int, Mentionable]] _UList: TypeAlias = list[tuple[int, HashPoint]] _SList: TypeAlias = list[tuple[int, RainbowFactory, int]] _VList: TypeAlias = list[tuple[int, RainbowFactory]] -_MCall: TypeAlias = Callable[['Auto', _IList, _UList], None] +_MCall: TypeAlias = Callable[["Auto", _IList, _UList], None] _MTuple: TypeAlias = tuple[int, _MCall, int] -_IAuto = TypeVar('_IAuto', bound='IAuto') +_IAuto = TypeVar("_IAuto", bound="IAuto") class IAuto(RecursiveMentionable): - def __init__( - self, - inlined: _IList, - uninlined: _UList - ): + def __init__(self, inlined: _IList, uninlined: _UList): assert isinstance(inlined, list) assert isinstance(uninlined, list) for index, mentionable in inlined: @@ -59,7 +67,7 @@ class IAuto(RecursiveMentionable): for index, uninlined in self.uninlined: uninlined_bytes.append((index, bytes(uninlined))) merged_bytes: Iterable[tuple[int, bytes]] = heapq.merge(inlined_bytes, uninlined_bytes) - return b''.join(source for _, source in merged_bytes) + return b"".join(source for _, source in merged_bytes) def __factory__(self: _IAuto) -> RainbowFactory[_IAuto]: sized: _SList = [] @@ -76,11 +84,7 @@ class IAuto(RecursiveMentionable): for index, uninlined in self.uninlined: uninlined_unsized.append((index, uninlined.factory)) merged_unsized: Iterable[tuple[int, RainbowFactory]] = heapq.merge(inlined_unsized, uninlined_unsized) - return IAutoFactory( - type(self), - sized, - list(merged_unsized) - ) + return IAutoFactory(type(self), sized, list(merged_unsized)) def hashpoints(self) -> Iterable[HashPoint]: inlined_hashpoints: list[tuple[int, HashPoint]] = [] @@ -156,15 +160,15 @@ class IAuto(RecursiveMentionable): async def str(self, tab: int) -> str: assert isinstance(tab, int) formatted = await gather(*(hash_point_format(hashpoint, tab) for hashpoint in self.hashpoints())) - return f'{tabulate(tab)}'.join(formatted) + return f"{tabulate(tab)}".join(formatted) -T = TypeVar('T', bound=Mentionable) -T0 = TypeVar('T0', bound=Mentionable) -T1 = TypeVar('T1', bound=Mentionable) -T2 = TypeVar('T2', bound=Mentionable) -T3 = TypeVar('T3', bound=Mentionable) -T4 = TypeVar('T4', bound=Mentionable) +T = TypeVar("T", bound=Mentionable) +T0 = TypeVar("T0", bound=Mentionable) +T1 = TypeVar("T1", bound=Mentionable) +T2 = TypeVar("T2", bound=Mentionable) +T3 = TypeVar("T3", bound=Mentionable) +T4 = TypeVar("T4", bound=Mentionable) class Auto: @@ -185,7 +189,7 @@ class Auto: def as_mentionable(self, factory: RainbowFactory) -> Mentionable: return self.as_value(factory) - def sub(self, start: Optional[int], stop: Optional[int]) -> 'Auto': + def sub(self, start: Optional[int], stop: Optional[int]) -> Auto: return Auto(self.source[start:stop], self.resolver) def __enter__(self): @@ -194,7 +198,7 @@ class Auto: def __exit__(self, exc_type, exc_val, exc_tb): assert_eq(len(self.source), self.__index) - def next(self, size: int) -> 'Auto': + def next(self, size: int) -> Auto: assert isinstance(size, int) index = self.__index self.__index += size @@ -220,7 +224,7 @@ class Auto: def _static_separate(self, infix_position: int, *factories: RainbowFactory) -> Iterable[Mentionable]: prefix = factories[:infix_position] - postfix = factories[infix_position + 1:] + postfix = factories[infix_position + 1 :] prefix_size = self._static_size(*prefix) postfix_size = self._static_size(*postfix) postfix_start = len(self.source) - postfix_size @@ -236,40 +240,39 @@ class Auto: if infix_position is None: infix_position = index else: - raise ValueError('static auto parse does not allow uninlineable values (two or more unsized)') + raise ValueError("static auto parse does not allow uninlineable values (two or more unsized)") if infix_position is None: yield from self._static_simple(*factories) else: yield from self._static_separate(infix_position, *factories) @overload - def static( - self, t0: RainbowFactory[T0], / - ) -> tuple[T0]: + def static(self, t0: RainbowFactory[T0], /) -> tuple[T0]: + ... + + @overload + def static(self, t0: RainbowFactory[T0], t1: RainbowFactory[T1], /) -> tuple[T0, T1]: + ... + + @overload + def static(self, t0: RainbowFactory[T0], t1: RainbowFactory[T1], t2: RainbowFactory[T2], /) -> tuple[T0, T1, T2]: ... @overload def static( - self, t0: RainbowFactory[T0], t1: RainbowFactory[T1], / - ) -> tuple[T0, T1]: - ... - - @overload - def static( - self, t0: RainbowFactory[T0], t1: RainbowFactory[T1], t2: RainbowFactory[T2], / - ) -> tuple[T0, T1, T2]: - ... - - @overload - def static( - self, t0: RainbowFactory[T0], t1: RainbowFactory[T1], t2: RainbowFactory[T2], t3: RainbowFactory[T3], / + self, t0: RainbowFactory[T0], t1: RainbowFactory[T1], t2: RainbowFactory[T2], t3: RainbowFactory[T3], / ) -> tuple[T0, T1, T2, T3]: ... @overload def static( - self, t0: RainbowFactory[T0], t1: RainbowFactory[T1], t2: RainbowFactory[T2], t3: RainbowFactory[T3], - t4: RainbowFactory[T4], / + self, + t0: RainbowFactory[T0], + t1: RainbowFactory[T1], + t2: RainbowFactory[T2], + t3: RainbowFactory[T3], + t4: RainbowFactory[T4], + /, ) -> tuple[T0, T1, T2, T3, T4]: ... @@ -278,12 +281,7 @@ class Auto: class IAutoFactory(Inlining[_IAuto], Generic[_IAuto]): - def __init__( - self, - typed: Type[_IAuto], - sized: _SList, - unsized: _VList - ): + def __init__(self, typed: Type[_IAuto], sized: _SList, unsized: _VList): assert issubclass(typed, IAuto) assert isinstance(sized, list) assert isinstance(unsized, list) @@ -369,13 +367,9 @@ class IAutoFactory(Inlining[_IAuto], Generic[_IAuto]): unsized_mergeable: list[_MTuple] = [] sized_mergeable: list[_MTuple] = [] for index, factory in self.unsized: - unsized_mergeable.append( - self._unsized_mtuple(index, factory) - ) + unsized_mergeable.append(self._unsized_mtuple(index, factory)) for index, factory, size in self.sized: - sized_mergeable.append( - self._sized_mtuple(index, factory, size) - ) + sized_mergeable.append(self._sized_mtuple(index, factory, size)) merged: Iterable[_MTuple] = heapq.merge(unsized_mergeable, sized_mergeable) return [(method, size) for _, method, size in merged] @@ -386,9 +380,7 @@ class IAutoFactory(Inlining[_IAuto], Generic[_IAuto]): return sum(size for _, size in self.merged) @classmethod - def _parse_affix( - cls, auto: Auto, affix: _SList - ) -> Iterable[tuple[int, Mentionable]]: + def _parse_affix(cls, auto: Auto, affix: _SList) -> Iterable[tuple[int, Mentionable]]: assert isinstance(auto, Auto) assert isinstance(affix, list) with auto: diff --git a/rainbowadn/inlining/ibyte.py b/rainbowadn/inlining/ibyte.py index c02d9f3..eadfcc9 100644 --- a/rainbowadn/inlining/ibyte.py +++ b/rainbowadn/inlining/ibyte.py @@ -1,6 +1,8 @@ +from __future__ import annotations + from .iatomic import * -__all__ = ('IByte',) +__all__ = ("IByte",) class IByte(IAtomic): @@ -14,7 +16,7 @@ class IByte(IAtomic): return 1 @classmethod - def _from_bytes(cls, source: bytes) -> 'IByte': + def _from_bytes(cls, source: bytes) -> IByte: assert isinstance(source, bytes) [value] = source return IByte(value) @@ -23,4 +25,4 @@ class IByte(IAtomic): return bytes([self.value]) def __str__(self): - return f'{self.value:02x}' + return f"{self.value:02x}" diff --git a/rainbowadn/inlining/inlining.py b/rainbowadn/inlining/inlining.py index 2acc084..9539d1e 100644 --- a/rainbowadn/inlining/inlining.py +++ b/rainbowadn/inlining/inlining.py @@ -3,9 +3,9 @@ from typing import Any, Callable, Coroutine, Optional, TypeAlias, TypeVar from rainbowadn.core import * -__all__ = ('Inlining',) +__all__ = ("Inlining",) -Inlined = TypeVar('Inlined', bound=Mentionable, covariant=True) +Inlined = TypeVar("Inlined", bound=Mentionable, covariant=True) _FTuple: TypeAlias = tuple[int, Callable[[bytes, HashResolver], HashPoint], int] _HTuple: TypeAlias = tuple[int, Callable[[], Coroutine[Any, Any, bytes]]] diff --git a/rainbowadn/inlining/ipair.py b/rainbowadn/inlining/ipair.py index c78ab0b..e483c21 100644 --- a/rainbowadn/inlining/ipair.py +++ b/rainbowadn/inlining/ipair.py @@ -1,13 +1,15 @@ +from __future__ import annotations + from typing import Generic, TypeVar from rainbowadn.core import * from .iauto import * -__all__ = ('IPair',) +__all__ = ("IPair",) -E0 = TypeVar('E0', bound=Mentionable) -E1 = TypeVar('E1', bound=Mentionable) +E0 = TypeVar("E0", bound=Mentionable) +E1 = TypeVar("E1", bound=Mentionable) class IPair(IAuto, Generic[E0, E1]): @@ -19,19 +21,19 @@ class IPair(IAuto, Generic[E0, E1]): self.e0, self.e1 = self.hashpoints() @classmethod - async def off(cls, e0: HashPoint[E0], e1: HashPoint[E1]) -> 'IPair[E0, E1]': + async def off(cls, e0: HashPoint[E0], e1: HashPoint[E1]) -> IPair[E0, E1]: assert isinstance(e0, HashPoint) assert isinstance(e1, HashPoint) return await cls.auto_off(e0, e1) @classmethod - def of(cls, v0: E0, v1: E1) -> 'IPair[E0, E1]': + def of(cls, v0: E0, v1: E1) -> IPair[E0, E1]: assert isinstance(v0, Mentionable) assert isinstance(v1, Mentionable) return cls.auto_of(v0, v1) @classmethod - def f(cls, f0: RainbowFactory[E0], f1: RainbowFactory[E1]) -> RainbowFactory['IPair[E0, E1]']: + def f(cls, f0: RainbowFactory[E0], f1: RainbowFactory[E1]) -> RainbowFactory[IPair[E0, E1]]: assert isinstance(f0, RainbowFactory) assert isinstance(f1, RainbowFactory) return cls.auto_f(f0, f1) diff --git a/rainbowadn/inlining/iref.py b/rainbowadn/inlining/iref.py index 3f2a70b..f703569 100644 --- a/rainbowadn/inlining/iref.py +++ b/rainbowadn/inlining/iref.py @@ -1,12 +1,14 @@ +from __future__ import annotations + from typing import Generic, Iterable, Optional, TypeVar from rainbowadn.core import * from .inlining import * -__all__ = ('IRef',) +__all__ = ("IRef",) -TRef = TypeVar('TRef', bound=Mentionable) +TRef = TypeVar("TRef", bound=Mentionable) class IRef(RecursiveMentionable, Generic[TRef]): @@ -16,7 +18,7 @@ class IRef(RecursiveMentionable, Generic[TRef]): def __bytes__(self): return bytes(self.hashpoint) - def __factory__(self) -> RainbowFactory['IRef[TRef]']: + def __factory__(self) -> RainbowFactory[IRef[TRef]]: return IReff(self.hashpoint.factory) def __init__(self, hashpoint: HashPoint[TRef]): @@ -34,6 +36,4 @@ class IReff(Inlining[IRef[TRef]], Generic[TRef]): def from_bytes(self, source: bytes, resolver: HashResolver) -> IRef[TRef]: assert_eq(len(source), HashPoint.HASH_LENGTH) - return IRef( - ResolverMetaOrigin(resolver).hash_point(self.factory, source) - ) + return IRef(ResolverMetaOrigin(resolver).hash_point(self.factory, source)) diff --git a/rainbowadn/inlining/istatic.py b/rainbowadn/inlining/istatic.py index 66f14fd..41dd579 100644 --- a/rainbowadn/inlining/istatic.py +++ b/rainbowadn/inlining/istatic.py @@ -5,9 +5,12 @@ from rainbowadn.core import * from .inlining import * -__all__ = ('IStatic', 'IStaticFactory',) +__all__ = ( + "IStatic", + "IStaticFactory", +) -StaticInlined = TypeVar('StaticInlined', bound='IStatic') +StaticInlined = TypeVar("StaticInlined", bound="IStatic") class IStatic(Mentionable, abc.ABC): diff --git a/rainbowadn/inlining/iunit.py b/rainbowadn/inlining/iunit.py index 37a8a56..0a1cf53 100644 --- a/rainbowadn/inlining/iunit.py +++ b/rainbowadn/inlining/iunit.py @@ -1,8 +1,10 @@ +from __future__ import annotations + from rainbowadn.core import * from .iatomic import * -__all__ = ('IUnit',) +__all__ = ("IUnit",) class IUnit(IAtomic): @@ -11,13 +13,13 @@ class IUnit(IAtomic): return 0 @classmethod - def _from_bytes(cls, source: bytes) -> 'IUnit': + def _from_bytes(cls, source: bytes) -> IUnit: assert isinstance(source, bytes) assert_eq(len(source), 0) return IUnit() def __bytes__(self): - return b'' + return b"" def __str__(self): - return f'()' + return f"()" diff --git a/rainbowadn/instrument/__init__.py b/rainbowadn/instrument/__init__.py index c55f897..12039a2 100644 --- a/rainbowadn/instrument/__init__.py +++ b/rainbowadn/instrument/__init__.py @@ -1,11 +1,12 @@ __all__ = ( - 'Measure', - 'Terminated', 'Terminate', - 'ClassReport', - 'Concurrency', - 'Counter', - 'EntryExit', - 'Instrumentation', + "Measure", + "Terminated", + "Terminate", + "ClassReport", + "Concurrency", + "Counter", + "EntryExit", + "Instrumentation", ) from ._measure import Measure diff --git a/rainbowadn/instrument/_measure.py b/rainbowadn/instrument/_measure.py index a7b6901..1660e3d 100644 --- a/rainbowadn/instrument/_measure.py +++ b/rainbowadn/instrument/_measure.py @@ -2,7 +2,7 @@ import time from .instrumentation import Instrumentation -__all__ = ('Measure',) +__all__ = ("Measure",) class Measure(Instrumentation): diff --git a/rainbowadn/instrument/_terminate.py b/rainbowadn/instrument/_terminate.py index c145804..73dd521 100644 --- a/rainbowadn/instrument/_terminate.py +++ b/rainbowadn/instrument/_terminate.py @@ -1,6 +1,6 @@ from .instrumentation import * -__all__ = ('Terminated', 'Terminate') +__all__ = ("Terminated", "Terminate") class Terminated(Exception): diff --git a/rainbowadn/instrument/classreport.py b/rainbowadn/instrument/classreport.py index 4503aa3..5025cd4 100644 --- a/rainbowadn/instrument/classreport.py +++ b/rainbowadn/instrument/classreport.py @@ -2,7 +2,7 @@ from io import StringIO from rainbowadn.core import * -__all__ = ('ClassReport',) +__all__ = ("ClassReport",) class ClassReport: @@ -35,10 +35,10 @@ class ClassReport: @classmethod def format_key(cls, key: tuple[str, bytes, bytes]) -> str: - return f'{key[0]:<32}:{key[1].hex()}:{key[2].hex()}' + return f"{key[0]:<32}:{key[1].hex()}:{key[2].hex()}" def format(self) -> str: s = StringIO() for key in sorted(self.report): - s.write(f'{self.format_key(key)}\n') + s.write(f"{self.format_key(key)}\n") return s.getvalue() diff --git a/rainbowadn/instrument/concurrency.py b/rainbowadn/instrument/concurrency.py index a57ba18..aa89c90 100644 --- a/rainbowadn/instrument/concurrency.py +++ b/rainbowadn/instrument/concurrency.py @@ -2,7 +2,7 @@ import time from .instrumentation import * -__all__ = ('Concurrency',) +__all__ = ("Concurrency",) class Concurrency(Instrumentation): diff --git a/rainbowadn/instrument/counter.py b/rainbowadn/instrument/counter.py index 2e51d2c..271679b 100644 --- a/rainbowadn/instrument/counter.py +++ b/rainbowadn/instrument/counter.py @@ -1,6 +1,6 @@ from .instrumentation import * -__all__ = ('Counter',) +__all__ = ("Counter",) class Counter(Instrumentation): diff --git a/rainbowadn/instrument/entryexit.py b/rainbowadn/instrument/entryexit.py index 9d7738d..109b7e1 100644 --- a/rainbowadn/instrument/entryexit.py +++ b/rainbowadn/instrument/entryexit.py @@ -2,7 +2,7 @@ from typing import Callable from .instrumentation import * -__all__ = ('EntryExit',) +__all__ = ("EntryExit",) class EntryExit(Instrumentation): diff --git a/rainbowadn/instrument/instrumentation.py b/rainbowadn/instrument/instrumentation.py index 8297ec4..09996bd 100644 --- a/rainbowadn/instrument/instrumentation.py +++ b/rainbowadn/instrument/instrumentation.py @@ -2,9 +2,9 @@ import functools from contextlib import ExitStack from typing import Callable, TypeVar -__all__ = ('Instrumentation',) +__all__ = ("Instrumentation",) -IType = TypeVar('IType', bound='Instrumentation') +IType = TypeVar("IType", bound="Instrumentation") class Instrumentation: @@ -14,9 +14,9 @@ class Instrumentation: def __init__(self, target, methodname: str): if not isinstance(methodname, str): - raise TypeError('methodname must be str') + raise TypeError("methodname must be str") if not callable(getattr(target, methodname)): - raise TypeError('target.methodname must be callable') + raise TypeError("target.methodname must be callable") self.target = target self.methodname = methodname @@ -24,7 +24,7 @@ class Instrumentation: return method(*args, **kwargs) def __enter__(self: IType) -> IType: - if hasattr(self, '_method') or hasattr(self, '_wrap'): + if hasattr(self, "_method") or hasattr(self, "_wrap"): raise RuntimeError method = getattr(self.target, self.methodname) if not callable(method): @@ -61,7 +61,7 @@ class Instrumentation: if not isinstance(self, Instrumentation): raise TypeError return stack.enter_context(self) - + def enter_conditional(self: IType, stack: ExitStack) -> IType | None: if not isinstance(self, Instrumentation): raise TypeError diff --git a/rainbowadn/nullability/__init__.py b/rainbowadn/nullability/__init__.py index 33bd0e2..3e47419 100644 --- a/rainbowadn/nullability/__init__.py +++ b/rainbowadn/nullability/__init__.py @@ -1,8 +1,9 @@ __all__ = ( - 'NotNull', - 'Null', - 'Nullable', - 'NullableReference', 'NullableReferenceFactory', + "NotNull", + "Null", + "Nullable", + "NullableReference", + "NullableReferenceFactory", ) from .notnull import NotNull diff --git a/rainbowadn/nullability/notnull.py b/rainbowadn/nullability/notnull.py index f4cdeee..7b9c416 100644 --- a/rainbowadn/nullability/notnull.py +++ b/rainbowadn/nullability/notnull.py @@ -2,9 +2,9 @@ from typing import Generic, TypeVar from .nullable import * -__all__ = ('NotNull',) +__all__ = ("NotNull",) -NullableType = TypeVar('NullableType', covariant=True) +NullableType = TypeVar("NullableType", covariant=True) class NotNull(Nullable[NullableType], Generic[NullableType]): diff --git a/rainbowadn/nullability/null.py b/rainbowadn/nullability/null.py index 9f3b4af..d23b0c5 100644 --- a/rainbowadn/nullability/null.py +++ b/rainbowadn/nullability/null.py @@ -2,9 +2,9 @@ from typing import Generic, TypeVar from .nullable import * -__all__ = ('Null',) +__all__ = ("Null",) -NullableType = TypeVar('NullableType', covariant=True) +NullableType = TypeVar("NullableType", covariant=True) class Null(Nullable[NullableType], Generic[NullableType]): @@ -12,7 +12,7 @@ class Null(Nullable[NullableType], Generic[NullableType]): return True def _resolve(self) -> NullableType: - raise TypeError('null') + raise TypeError("null") def __eq__(self, other): if isinstance(other, Null): diff --git a/rainbowadn/nullability/nullable.py b/rainbowadn/nullability/nullable.py index 515091b..2b11fde 100644 --- a/rainbowadn/nullability/nullable.py +++ b/rainbowadn/nullability/nullable.py @@ -1,9 +1,9 @@ import abc from typing import Generic, TypeVar -__all__ = ('Nullable',) +__all__ = ("Nullable",) -NullableType = TypeVar('NullableType', covariant=True) +NullableType = TypeVar("NullableType", covariant=True) class Nullable(Generic[NullableType], abc.ABC): diff --git a/rainbowadn/nullability/nullablereference.py b/rainbowadn/nullability/nullablereference.py index 8404a53..470b637 100644 --- a/rainbowadn/nullability/nullablereference.py +++ b/rainbowadn/nullability/nullablereference.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from typing import Generic, Iterable, Optional, TypeVar from rainbowadn.core import * @@ -7,14 +9,17 @@ from .notnull import * from .null import * from .nullable import * -__all__ = ('NullableReference', 'NullableReferenceFactory',) +__all__ = ( + "NullableReference", + "NullableReferenceFactory", +) -Referenced = TypeVar('Referenced', bound=Mentionable, covariant=True) -ReferencedI = TypeVar('ReferencedI', bound=Mentionable) +Referenced = TypeVar("Referenced", bound=Mentionable, covariant=True) +ReferencedI = TypeVar("ReferencedI", bound=Mentionable) class NullableReference(RecursiveMentionable, Generic[Referenced]): - def __factory__(self) -> RainbowFactory['NullableReference[Referenced]']: + def __factory__(self) -> RainbowFactory[NullableReference[Referenced]]: return NullableReferenceFactory(self.factory) def points(self) -> Iterable[HashPoint]: @@ -29,30 +34,28 @@ class NullableReference(RecursiveMentionable, Generic[Referenced]): else: return self.hashpoint().point - def __init__( - self, reference: Nullable[HashPoint[Referenced]], factory: RainbowFactory[Referenced] - ): + def __init__(self, reference: Nullable[HashPoint[Referenced]], factory: RainbowFactory[Referenced]): assert isinstance(reference, Nullable) assert isinstance(factory, RainbowFactory) self.reference = reference self.factory = factory @classmethod - def of(cls, hash_point: HashPoint[Referenced]) -> 'NullableReference[Referenced]': + def of(cls, hash_point: HashPoint[Referenced]) -> NullableReference[Referenced]: assert isinstance(hash_point, HashPoint) return cls(NotNull(hash_point), hash_point.factory) @classmethod - def off(cls, value: ReferencedI) -> 'NullableReference[ReferencedI]': + def off(cls, value: ReferencedI) -> NullableReference[ReferencedI]: assert isinstance(value, Mentionable) return cls.of(HashPoint.of(value)) async def str(self, tab: int) -> str: assert isinstance(tab, int) if self.null(): - return f'-' + return f"-" else: - return f'{await hash_point_format(self.hashpoint(), tab)}' + return f"{await hash_point_format(self.hashpoint(), tab)}" def __eq__(self, other): if isinstance(other, NullableReference): @@ -72,7 +75,7 @@ class NullableReference(RecursiveMentionable, Generic[Referenced]): return await self.hashpoint().resolve() @classmethod - def f(cls, factory: RainbowFactory[Referenced]) -> RainbowFactory['NullableReference[Referenced]']: + def f(cls, factory: RainbowFactory[Referenced]) -> RainbowFactory[NullableReference[Referenced]]: return NullableReferenceFactory(factory) @@ -90,6 +93,4 @@ class NullableReferenceFactory(Inlining[NullableReference[Referenced]], Generic[ if source == HashPoint.NULL_HASH: return NullableReference(Null(), self.factory) else: - return NullableReference.of( - ResolverMetaOrigin(resolver).hash_point(self.factory, source) - ) + return NullableReference.of(ResolverMetaOrigin(resolver).hash_point(self.factory, source)) diff --git a/rainbowadn/testing/resolvers/__init__.py b/rainbowadn/testing/resolvers/__init__.py index dab4b59..898e5de 100644 --- a/rainbowadn/testing/resolvers/__init__.py +++ b/rainbowadn/testing/resolvers/__init__.py @@ -1,9 +1,9 @@ __all__ = ( - 'CachingResolver', - 'default_resolver', - 'DelayedResolver', - 'DictResolver', - 'FailResolver', + "CachingResolver", + "default_resolver", + "DelayedResolver", + "DictResolver", + "FailResolver", ) from .cachingresolver import CachingResolver diff --git a/rainbowadn/testing/resolvers/cachingresolver.py b/rainbowadn/testing/resolvers/cachingresolver.py index dbc5843..989866b 100644 --- a/rainbowadn/testing/resolvers/cachingresolver.py +++ b/rainbowadn/testing/resolvers/cachingresolver.py @@ -2,9 +2,9 @@ from typing import TypeVar from rainbowadn.core import * -__all__ = ('CachingResolver',) +__all__ = ("CachingResolver",) -Mentioned = TypeVar('Mentioned', bound=Mentionable) +Mentioned = TypeVar("Mentioned", bound=Mentionable) class CachingResolver(ExtendableResolver): diff --git a/rainbowadn/testing/resolvers/defaultresolver.py b/rainbowadn/testing/resolvers/defaultresolver.py index 1dfeb81..1fb0331 100644 --- a/rainbowadn/testing/resolvers/defaultresolver.py +++ b/rainbowadn/testing/resolvers/defaultresolver.py @@ -1,6 +1,6 @@ from .dictresolver import * -__all__ = ('default_resolver',) +__all__ = ("default_resolver",) def default_resolver(): diff --git a/rainbowadn/testing/resolvers/delayedresolver.py b/rainbowadn/testing/resolvers/delayedresolver.py index 4d0479d..4fd21ce 100644 --- a/rainbowadn/testing/resolvers/delayedresolver.py +++ b/rainbowadn/testing/resolvers/delayedresolver.py @@ -3,9 +3,9 @@ from typing import Callable, TypeVar from rainbowadn.core import * -__all__ = ('DelayedResolver',) +__all__ = ("DelayedResolver",) -Mentioned = TypeVar('Mentioned', bound=Mentionable) +Mentioned = TypeVar("Mentioned", bound=Mentionable) class DelayedResolver(ExtendableResolver): @@ -18,7 +18,7 @@ class DelayedResolver(ExtendableResolver): async def sleep(self): await asyncio.sleep(self.delay()) - async def resolve(self, point: bytes) -> tuple[bytes, 'HashResolver']: + async def resolve(self, point: bytes) -> tuple[bytes, HashResolver]: assert isinstance(point, bytes) await self.sleep() resolved, resolver = await self.resolver.resolve(point) diff --git a/rainbowadn/testing/resolvers/dictresolver.py b/rainbowadn/testing/resolvers/dictresolver.py index 9ea977c..4ac7653 100644 --- a/rainbowadn/testing/resolvers/dictresolver.py +++ b/rainbowadn/testing/resolvers/dictresolver.py @@ -3,16 +3,16 @@ from typing import MutableMapping, TypeVar from rainbowadn.core import * -__all__ = ('DictResolver',) +__all__ = ("DictResolver",) -Mentioned = TypeVar('Mentioned', bound=Mentionable) +Mentioned = TypeVar("Mentioned", bound=Mentionable) class DictResolver(ExtendableResolver): def __init__(self): self.table: MutableMapping[bytes, bytes] = OrderedDict() - async def resolve(self, point: bytes) -> tuple[bytes, 'HashResolver']: + async def resolve(self, point: bytes) -> tuple[bytes, HashResolver]: assert isinstance(point, bytes) return self.table[point], self @@ -25,11 +25,9 @@ class DictResolver(ExtendableResolver): assert isinstance(value, Mentionable) self.table[hash_point.point] = HashPoint.bytes_of_mentioned(value) if isinstance(value, RecursiveMentionable): - await gather( - *(self.save(hp) for hp in value.points()) - ) + await gather(*(self.save(hp) for hp in value.points())) - async def extend(self, hash_point: HashPoint[Mentioned]) -> 'ExtendableResolver': + async def extend(self, hash_point: HashPoint[Mentioned]) -> ExtendableResolver: assert isinstance(hash_point, HashPoint) await self.save(hash_point) return self diff --git a/rainbowadn/testing/resolvers/failresolver.py b/rainbowadn/testing/resolvers/failresolver.py index 39514b5..30a9dcb 100644 --- a/rainbowadn/testing/resolvers/failresolver.py +++ b/rainbowadn/testing/resolvers/failresolver.py @@ -1,8 +1,8 @@ from rainbowadn.core import * -__all__ = ('FailResolver',) +__all__ = ("FailResolver",) class FailResolver(HashResolver): - async def resolve(self, point: bytes) -> tuple[bytes, 'HashResolver']: - raise TypeError('fail-resolver always fails') + async def resolve(self, point: bytes) -> tuple[bytes, HashResolver]: + raise TypeError("fail-resolver always fails") diff --git a/rainbowadn/testing/test_bridge.py b/rainbowadn/testing/test_bridge.py index 77df220..1b252ce 100644 --- a/rainbowadn/testing/test_bridge.py +++ b/rainbowadn/testing/test_bridge.py @@ -44,7 +44,7 @@ class TestBridge(unittest.IsolatedAsyncioTestCase): for _ in range(16): with self.assertRaises(ValueError): await fs1.verify_subset(UnitReducer(fs0)) - print('verification time', time.process_time() - _t) + print("verification time", time.process_time() - _t) async def test_flow13(self): set_gather_linear() @@ -77,7 +77,7 @@ class TestBridge(unittest.IsolatedAsyncioTestCase): FlowCoinData.of(Subject(SigningKey.generate().verify_key), 0) for _ in range(random.randint(4, 7)) ], - [] + [], ) for _ in range(random.randint(4, 7)) ] diff --git a/rainbowadn/testing/test_encryption.py b/rainbowadn/testing/test_encryption.py index 2ec618c..960a4af 100644 --- a/rainbowadn/testing/test_encryption.py +++ b/rainbowadn/testing/test_encryption.py @@ -13,36 +13,36 @@ from rainbowadn.testing.resolvers import * class TestEncryption(unittest.IsolatedAsyncioTestCase): async def test_encryption(self): set_gather_linear() - encrypt_ctr = Counter(Encrypted, 'encrypt') - with self.subTest('setup'): - key = b'a' * 32 - with self.subTest('create empty'): + encrypt_ctr = Counter(Encrypted, "encrypt") + with self.subTest("setup"): + key = b"a" * 32 + with self.subTest("create empty"): tree: ActiveBinaryTree[Plain, Integer] = ActiveBinaryTree.empty( AVL(PlainComparator(Replace())), Plain.factory() ) - with self.subTest('fill'): + with self.subTest("fill"): for char in string.ascii_uppercase: tree = await tree.add(HashPoint.of(Plain(char.encode()))) print(await tree.reference.str(0)) - with self.subTest('encrypt'): + with self.subTest("encrypt"): target = tree.reference with encrypt_ctr: target = (await Encrypted.encrypt(target, key)).decrypted print(encrypt_ctr.counter) tree = tree.create(target) print(await tree.reference.str(0)) - with self.subTest('alter'): - tree = await tree.add(HashPoint.of(Plain(b'NEWKEY'))) - tree = await tree.remove(HashPoint.of(Plain(b'F'))) + with self.subTest("alter"): + tree = await tree.add(HashPoint.of(Plain(b"NEWKEY"))) + tree = await tree.remove(HashPoint.of(Plain(b"F"))) print(await tree.reference.str(0)) - with self.subTest('encrypt and migrate'): + with self.subTest("encrypt and migrate"): target = tree.reference with encrypt_ctr: eeed = await Encrypted.encrypt(target, key) print(encrypt_ctr.counter) print(await (await default_resolver().migrate_resolved(eeed)).decrypted.str(0)) - with self.subTest('re-encrypt'): - new_key = b'b' * 32 + with self.subTest("re-encrypt"): + new_key = b"b" * 32 target = eeed.decrypted with encrypt_ctr: await Encrypted.encrypt(target, new_key) diff --git a/rainbowadn/testing/test_inlining.py b/rainbowadn/testing/test_inlining.py index bb69d71..08c53e3 100644 --- a/rainbowadn/testing/test_inlining.py +++ b/rainbowadn/testing/test_inlining.py @@ -16,24 +16,22 @@ class TestInlining(unittest.IsolatedAsyncioTestCase): return result async def test_unit(self): - print(await (IAuto.auto_f(IUnit.factory(), IUnit.factory()).from_bytes(b'', FailResolver())).str(0)) + print(await IAuto.auto_f(IUnit.factory(), IUnit.factory()).from_bytes(b"", FailResolver()).str(0)) print(bytes(IAuto.auto_of(IUnit(), IUnit()))) async def test_byte(self): # iB short for IByte - print(await (IAuto.auto_f(IByte.factory(), IByte.factory()).from_bytes(b'iB', FailResolver())).str(0)) + print(await IAuto.auto_f(IByte.factory(), IByte.factory()).from_bytes(b"iB", FailResolver()).str(0)) print(bytes(IAuto.auto_of(IByte(0x69), IByte(0x42)))) async def test_mixed(self): - print(await (IAuto.auto_f(IByte.factory(), IUnit.factory()).from_bytes(b'!', FailResolver())).str(0)) + print(await IAuto.auto_f(IByte.factory(), IUnit.factory()).from_bytes(b"!", FailResolver()).str(0)) print(bytes(IAuto.auto_of(IByte(0x21), IUnit()))) async def test_complex_infix(self): print(b := bytes(IAuto.auto_of(IByte(0x21), Integer(0x21), IByte(0x21)))) print( - await IAuto.auto_f( - IByte.factory(), Integer.factory(), IByte.factory() - ).from_bytes(b, FailResolver()).str(0) + await IAuto.auto_f(IByte.factory(), Integer.factory(), IByte.factory()).from_bytes(b, FailResolver()).str(0) ) async def test_complex_reference(self): @@ -41,32 +39,30 @@ class TestInlining(unittest.IsolatedAsyncioTestCase): print( ( b := bytes( - await dr.migrate_resolved( - IAuto.auto_of(IByte(0x21), Integer(0x21), Integer(0x21), IByte(0x21)) - ) + await dr.migrate_resolved(IAuto.auto_of(IByte(0x21), Integer(0x21), Integer(0x21), IByte(0x21))) ) ).hex() ) print( - await IAuto.auto_f( - IByte.factory(), Integer.factory(), Integer.factory(), IByte.factory() - ).from_bytes(b, dr).str(0) + await IAuto.auto_f(IByte.factory(), Integer.factory(), Integer.factory(), IByte.factory()) + .from_bytes(b, dr) + .str(0) ) async def test_pair(self): - with self.subTest('of'): + with self.subTest("of"): pair = IPair.of(IUnit(), IUnit()) print(await pair.str(0)) print(bytes(pair).hex()) - with self.subTest('off'): + with self.subTest("off"): pair = await IPair.off(HashPoint.of(IUnit()), HashPoint.of(IUnit())) print(await pair.str(0)) print(bytes(pair).hex()) - with self.subTest('integer'): + with self.subTest("integer"): pair = IPair.of(Integer(0x21), IUnit()) print(await pair.str(0)) print(bytes(pair).hex()) - with self.subTest('integer 2'): + with self.subTest("integer 2"): pair = IPair.of(Integer(0x21), Integer(0x21)) print(await pair.str(0)) print(bytes(pair).hex()) diff --git a/rainbowadn/testing/test_trees.py b/rainbowadn/testing/test_trees.py index e561831..f2e6d39 100644 --- a/rainbowadn/testing/test_trees.py +++ b/rainbowadn/testing/test_trees.py @@ -13,7 +13,7 @@ from rainbowadn.wrisbt import * class TestTrees(unittest.IsolatedAsyncioTestCase): async def test_wrisbt(self): set_gather_linear() - with self.subTest('setup'): + with self.subTest("setup"): stoptime = time.process_time() def measure(message: str) -> float: @@ -26,32 +26,32 @@ class TestTrees(unittest.IsolatedAsyncioTestCase): n = 5000 keysize = 7 - with self.subTest('create empty'): + with self.subTest("create empty"): btree: WrisbtRoot = WrisbtRoot.empty(WrisbtParametres(5, keysize)) - measure('init') - with self.subTest('add keys', n=n): + measure("init") + with self.subTest("add keys", n=n): for _ in range(n): key = os.urandom(keysize) assert_false(await btree.contains(key)) btree = await btree.add(key) assert_true(await btree.contains(key)) - measure('add') - with self.subTest('save'): + measure("add") + with self.subTest("save"): btree = await default_resolver().migrate_resolved(btree) - measure('save') + measure("save") set_gather_asyncio() - with self.subTest('resolve and iterate'): + with self.subTest("resolve and iterate"): assert_eq(len(await btree.keys()), n) print(btree.height) - measure('resolve and iterate') - with self.subTest('resolve and add', n=n): + measure("resolve and iterate") + with self.subTest("resolve and add", n=n): for _ in range(n): key = os.urandom(keysize) assert_false(await btree.contains(key)) btree = await btree.add(key) assert_true(await btree.contains(key)) print(btree.height) - measure('resolve and add') + measure("resolve and add") async def test_avl(self): set_gather_linear() @@ -59,15 +59,13 @@ class TestTrees(unittest.IsolatedAsyncioTestCase): AVL(PlainComparator(Replace())), Plain.factory() ) for i in range(26): - tree = await tree.add(HashPoint.of(Plain(bytes([ord('A') + i])))) + tree = await tree.add(HashPoint.of(Plain(bytes([ord("A") + i])))) print(await tree.reference.str(0)) async def test_avl_stress(self): set_gather_linear() protocol = AVL(PlainComparator(Replace())) - tree: ActiveBinaryTree[Plain, Integer] = ActiveBinaryTree.empty( - protocol, Plain.factory() - ) + tree: ActiveBinaryTree[Plain, Integer] = ActiveBinaryTree.empty(protocol, Plain.factory()) for i in range(250): tree = await tree.add(HashPoint.of(Plain(os.urandom(16)))) print(await AVL.height(tree.protocolized())) @@ -75,13 +73,11 @@ class TestTrees(unittest.IsolatedAsyncioTestCase): async def test_split(self): set_gather_linear() protocol = AVL(PlainComparator(Replace())) - tree: ActiveBinaryTree[Plain, Integer] = ActiveBinaryTree.empty( - protocol, Plain.factory() - ) + tree: ActiveBinaryTree[Plain, Integer] = ActiveBinaryTree.empty(protocol, Plain.factory()) for i in range(26): - tree = await tree.add(HashPoint.of(Plain(bytes([ord('A') + i])))) - treel, treer = await tree.split(HashPoint.of(Plain(b'J'))) - print(await treel.reference.str(0), ' << split >> ', await treer.reference.str(0)) + tree = await tree.add(HashPoint.of(Plain(bytes([ord("A") + i])))) + treel, treer = await tree.split(HashPoint.of(Plain(b"J"))) + print(await treel.reference.str(0), " << split >> ", await treer.reference.str(0)) async def test_union(self): set_gather_linear() diff --git a/rainbowadn/toplevel/__init__.py b/rainbowadn/toplevel/__init__.py index 6616f5b..5869612 100644 --- a/rainbowadn/toplevel/__init__.py +++ b/rainbowadn/toplevel/__init__.py @@ -1,6 +1,7 @@ __all__ = ( - 'ThresholdProtocol', - 'ValidReference', 'ValidReferenceFactory', + "ThresholdProtocol", + "ValidReference", + "ValidReferenceFactory", ) from .thresholdprotocol import ThresholdProtocol diff --git a/rainbowadn/toplevel/thresholdprotocol.py b/rainbowadn/toplevel/thresholdprotocol.py index e59eb22..f164c9e 100644 --- a/rainbowadn/toplevel/thresholdprotocol.py +++ b/rainbowadn/toplevel/thresholdprotocol.py @@ -1,8 +1,8 @@ from typing import Generic, TypeVar -__all__ = ('ThresholdProtocol',) +__all__ = ("ThresholdProtocol",) -Referenced = TypeVar('Referenced') +Referenced = TypeVar("Referenced") class ThresholdProtocol(Generic[Referenced]): diff --git a/rainbowadn/toplevel/validreference.py b/rainbowadn/toplevel/validreference.py index a1e75da..881a83e 100644 --- a/rainbowadn/toplevel/validreference.py +++ b/rainbowadn/toplevel/validreference.py @@ -1,12 +1,14 @@ +from __future__ import annotations + from typing import Generic, Iterable, TypeVar from rainbowadn.core import * from .thresholdprotocol import * -__all__ = ('ValidReference', 'ValidReferenceFactory') +__all__ = ("ValidReference", "ValidReferenceFactory") -Referenced = TypeVar('Referenced', bound=Mentionable) +Referenced = TypeVar("Referenced", bound=Mentionable) class ValidReference(RecursiveMentionable, Generic[Referenced]): @@ -28,7 +30,7 @@ class ValidReference(RecursiveMentionable, Generic[Referenced]): def __bytes__(self): return bytes(self.reference) - def __factory__(self) -> RainbowFactory['ValidReference[Referenced]']: + def __factory__(self) -> RainbowFactory[ValidReference[Referenced]]: return ValidReferenceFactory(self.reference.factory, self.protocol) diff --git a/rainbowadn/v13/__init__.py b/rainbowadn/v13/__init__.py index cc9f05c..a444a75 100644 --- a/rainbowadn/v13/__init__.py +++ b/rainbowadn/v13/__init__.py @@ -1,7 +1,8 @@ __all__ = ( - 'MINT_CONST', - 'BadSignature', 'Signature', - 'Subject', + "MINT_CONST", + "BadSignature", + "Signature", + "Subject", ) from .algo import MINT_CONST diff --git a/rainbowadn/v13/algo.py b/rainbowadn/v13/algo.py index 128e22c..6caa6e2 100644 --- a/rainbowadn/v13/algo.py +++ b/rainbowadn/v13/algo.py @@ -1,4 +1,4 @@ -__all__ = ('MINT_CONST',) +__all__ = ("MINT_CONST",) MINT_ORDER = 20 MINT_CONST = 1 << MINT_ORDER diff --git a/rainbowadn/v13/signature.py b/rainbowadn/v13/signature.py index 458e874..10b00de 100644 --- a/rainbowadn/v13/signature.py +++ b/rainbowadn/v13/signature.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import nacl.bindings import nacl.exceptions import nacl.signing @@ -7,7 +9,10 @@ from rainbowadn.inlining import * from .subject import * -__all__ = ('BadSignature', 'Signature',) +__all__ = ( + "BadSignature", + "Signature", +) class BadSignature(nacl.exceptions.BadSignatureError): @@ -25,19 +30,17 @@ class Signature(IAtomic): return nacl.bindings.crypto_sign_BYTES @classmethod - def empty(cls) -> 'Signature': + def empty(cls) -> Signature: return Signature(bytes(nacl.bindings.crypto_sign_BYTES)) @classmethod - def sign(cls, key: nacl.signing.SigningKey, hash_point: HashPoint) -> 'Signature': + def sign(cls, key: nacl.signing.SigningKey, hash_point: HashPoint) -> Signature: assert isinstance(key, nacl.signing.SigningKey) assert isinstance(hash_point, HashPoint) - return cls( - key.sign(hash_point.point).signature - ) + return cls(key.sign(hash_point.point).signature) @classmethod - def _from_bytes(cls, source: bytes) -> 'Signature': + def _from_bytes(cls, source: bytes) -> Signature: assert isinstance(source, bytes) return cls(source) @@ -54,4 +57,4 @@ class Signature(IAtomic): raise BadSignature def __str__(self): - return f'(signature)' + return f"(signature)" diff --git a/rainbowadn/v13/subject.py b/rainbowadn/v13/subject.py index 42dd6a1..e7b6388 100644 --- a/rainbowadn/v13/subject.py +++ b/rainbowadn/v13/subject.py @@ -4,7 +4,7 @@ from nacl.signing import VerifyKey from rainbowadn.inlining import * -__all__ = ('Subject',) +__all__ = ("Subject",) class Subject(IAtomic): @@ -19,7 +19,7 @@ class Subject(IAtomic): return nacl.bindings.crypto_sign_PUBLICKEYBYTES @classmethod - def _from_bytes(cls, source: bytes) -> 'Subject': + def _from_bytes(cls, source: bytes) -> "Subject": assert isinstance(source, bytes) return cls(VerifyKey(source)) @@ -27,4 +27,4 @@ class Subject(IAtomic): return bytes(self.verify_key) def __str__(self): - return f'(subject)' + return f"(subject)" diff --git a/rainbowadn/wrisbt/__init__.py b/rainbowadn/wrisbt/__init__.py index ea0544a..5b8508f 100644 --- a/rainbowadn/wrisbt/__init__.py +++ b/rainbowadn/wrisbt/__init__.py @@ -1,6 +1,7 @@ __all__ = ( - 'WrisbtParametres', - 'WrisbtRoot', 'WrisbtRootFactory', + "WrisbtParametres", + "WrisbtRoot", + "WrisbtRootFactory", ) from .wrisbtparametres import WrisbtParametres diff --git a/rainbowadn/wrisbt/weakreferenceindexsetbtree.py b/rainbowadn/wrisbt/weakreferenceindexsetbtree.py index 616592d..721b32f 100644 --- a/rainbowadn/wrisbt/weakreferenceindexsetbtree.py +++ b/rainbowadn/wrisbt/weakreferenceindexsetbtree.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import bisect from typing import AsyncIterable, Iterable, Sequence @@ -5,17 +7,20 @@ from rainbowadn.core import * from .wrisbtparametres import * -__all__ = ('WeakReferenceIndexSetBTree', 'WrisbtFactory',) +__all__ = ( + "WeakReferenceIndexSetBTree", + "WrisbtFactory", +) class WeakReferenceIndexSetBTree(RecursiveMentionable): def __init__( - self, - source: bytes, - height: int, - parametres: WrisbtParametres, - root: bool, - cache: tuple[MetaOrigin['WeakReferenceIndexSetBTree'], ...] + self, + source: bytes, + height: int, + parametres: WrisbtParametres, + root: bool, + cache: tuple[MetaOrigin["WeakReferenceIndexSetBTree"], ...], ): assert isinstance(source, bytes) assert isinstance(height, int) @@ -64,14 +69,14 @@ class WeakReferenceIndexSetBTree(RecursiveMentionable): assert isinstance(start, int) assert isinstance(size, int) assert 0 <= index < self.length - return self.source[start + size * index:start + size * (index + 1)] + return self.source[start + size * index : start + size * (index + 1)] def key_no(self, index: int) -> bytes: assert isinstance(index, int) assert 0 <= index < self.keys return self.bytes_no(index, 0, self.keysize) - def cached_no(self, index: int) -> MetaOrigin['WeakReferenceIndexSetBTree']: + def cached_no(self, index: int) -> MetaOrigin[WeakReferenceIndexSetBTree]: assert isinstance(index, int) assert 0 <= index < self.children assert not self.leaf @@ -79,16 +84,16 @@ class WeakReferenceIndexSetBTree(RecursiveMentionable): assert isinstance(cached, MetaOrigin) return cached - def child_no(self, index: int) -> HashPoint['WeakReferenceIndexSetBTree']: + def child_no(self, index: int) -> HashPoint[WeakReferenceIndexSetBTree]: assert isinstance(index, int) assert 0 <= index < self.children assert not self.leaf return self.cached_no(index).hash_point( WrisbtFactory(self.height - 1, self.parametres, False), - self.bytes_no(index, self.keyend, HashPoint.HASH_LENGTH) + self.bytes_no(index, self.keyend, HashPoint.HASH_LENGTH), ) - async def child_resolved_no(self, index: int) -> 'WeakReferenceIndexSetBTree': + async def child_resolved_no(self, index: int) -> WeakReferenceIndexSetBTree: assert isinstance(index, int) assert 0 <= index < self.children assert not self.leaf @@ -109,13 +114,13 @@ class WeakReferenceIndexSetBTree(RecursiveMentionable): return self.source def __topology_hash__(self) -> bytes: - return HashPoint.hash(self.source[self.keyend:]) + return HashPoint.hash(self.source[self.keyend :]) - def __factory__(self) -> RainbowFactory['WeakReferenceIndexSetBTree']: + def __factory__(self) -> RainbowFactory[WeakReferenceIndexSetBTree]: assert self.balanced() return WrisbtFactory(self.height, self.parametres, self.root) - def range(self, left: int, right: int) -> 'WeakReferenceIndexSetBTree': + def range(self, left: int, right: int) -> WeakReferenceIndexSetBTree: assert isinstance(left, int) assert isinstance(right, int) assert 0 <= left < right <= self.keys @@ -123,26 +128,22 @@ class WeakReferenceIndexSetBTree(RecursiveMentionable): assert isinstance(hl, int) if self.leaf: return WeakReferenceIndexSetBTree( - self.source[self.keysize * left:self.keysize * right], - 0, - self.parametres, - False, - () + self.source[self.keysize * left : self.keysize * right], 0, self.parametres, False, () ) else: - keybytes: bytes = self.source[self.keysize * left:self.keysize * right] + keybytes: bytes = self.source[self.keysize * left : self.keysize * right] assert isinstance(keybytes, bytes) - childbytes: bytes = self.source[self.keyend + hl * left:self.keyend + hl * (right + 1)] + childbytes: bytes = self.source[self.keyend + hl * left : self.keyend + hl * (right + 1)] assert isinstance(childbytes, bytes) return WeakReferenceIndexSetBTree( keybytes + childbytes, self.height, self.parametres, False, - self.cache[left:right + 1], + self.cache[left : right + 1], ) - def split(self) -> tuple['WeakReferenceIndexSetBTree', bytes, 'WeakReferenceIndexSetBTree']: + def split(self) -> tuple[WeakReferenceIndexSetBTree, bytes, WeakReferenceIndexSetBTree]: assert self.full() return ( self.range(0, self.keymin), @@ -153,20 +154,19 @@ class WeakReferenceIndexSetBTree(RecursiveMentionable): async def str(self, tab: int) -> str: assert isinstance(tab, int) - formatted = f'{self.height}' \ - f'{tabulate(tab)}(' + formatted = f"{self.height}" f"{tabulate(tab)}(" for key_index in range(self.keys): - formatted += f'{tabulate(tab + 1)}{self.key_no(key_index).hex()}' - formatted += ''.join( - f'{tabulate(tab + 1)}{child_formatted}' for child_formatted in ( + formatted += f"{tabulate(tab + 1)}{self.key_no(key_index).hex()}" + formatted += "".join( + f"{tabulate(tab + 1)}{child_formatted}" + for child_formatted in ( await gather( *(hash_point_format(self.child_no(child_index), tab + 1) for child_index in range(self.children)) ) ) ) - return f'{formatted}' \ - f'{tabulate(tab)})' + return f"{formatted}" f"{tabulate(tab)})" async def contains(self, key: bytes) -> bool: assert isinstance(key, bytes) @@ -189,7 +189,7 @@ class WeakReferenceIndexSetBTree(RecursiveMentionable): assert isinstance(child, WeakReferenceIndexSetBTree) return await child.contains(key) - async def add(self, key: bytes) -> 'WeakReferenceIndexSetBTree': + async def add(self, key: bytes) -> WeakReferenceIndexSetBTree: assert isinstance(key, bytes) assert_eq(len(key), self.keysize) @@ -206,11 +206,11 @@ class WeakReferenceIndexSetBTree(RecursiveMentionable): assert key > self.key_no(index - 1) if self.leaf: return WeakReferenceIndexSetBTree( - self.source[:self.keysize * index] + key + self.source[self.keysize * index:], + self.source[: self.keysize * index] + key + self.source[self.keysize * index :], self.height, self.parametres, self.root, - () + (), ) child: WeakReferenceIndexSetBTree = await self.child_resolved_no(index) assert isinstance(child, WeakReferenceIndexSetBTree) @@ -223,48 +223,33 @@ class WeakReferenceIndexSetBTree(RecursiveMentionable): assert isinstance(right, WeakReferenceIndexSetBTree) return WeakReferenceIndexSetBTree( ( - self.source[:self.keysize * index] - + - middle - + - self.source[self.keysize * index:self.keyend + HashPoint.HASH_LENGTH * index] - + - bytes(HashPoint.of(left)) - + - bytes(HashPoint.of(right)) - + - self.source[self.keyend + HashPoint.HASH_LENGTH * (index + 1):] + self.source[: self.keysize * index] + + middle + + self.source[self.keysize * index : self.keyend + HashPoint.HASH_LENGTH * index] + + bytes(HashPoint.of(left)) + + bytes(HashPoint.of(right)) + + self.source[self.keyend + HashPoint.HASH_LENGTH * (index + 1) :] ), self.height, self.parametres, self.root, ( self.cache[:index] - + - (LocalMetaOrigin(LocalOrigin(left)), LocalMetaOrigin(LocalOrigin(right))) - + - self.cache[index + 1:] - ) + + (LocalMetaOrigin(LocalOrigin(left)), LocalMetaOrigin(LocalOrigin(right))) + + self.cache[index + 1 :] + ), ) else: return WeakReferenceIndexSetBTree( ( - self.source[:self.keyend + HashPoint.HASH_LENGTH * index] - + - bytes(HashPoint.of(child)) - + - self.source[self.keyend + HashPoint.HASH_LENGTH * (index + 1):] + self.source[: self.keyend + HashPoint.HASH_LENGTH * index] + + bytes(HashPoint.of(child)) + + self.source[self.keyend + HashPoint.HASH_LENGTH * (index + 1) :] ), self.height, self.parametres, self.root, - ( - self.cache[:index] - + - (LocalMetaOrigin(LocalOrigin(child)),) - + - self.cache[index + 1:] - ) + (self.cache[:index] + (LocalMetaOrigin(LocalOrigin(child)),) + self.cache[index + 1 :]), ) async def iter_keys(self) -> AsyncIterable[bytes]: @@ -273,11 +258,7 @@ class WeakReferenceIndexSetBTree(RecursiveMentionable): yield self.key_no(key_index) else: children: list[WeakReferenceIndexSetBTree] = list( - await gather( - *( - self.child_resolved_no(child) for child in range(self.children) - ) - ) + await gather(*(self.child_resolved_no(child) for child in range(self.children))) ) for index in range(self.keys * 2 + 1): real_index, mode = divmod(index, 2) @@ -318,7 +299,7 @@ class WrisbtFactory(RainbowFactory[WeakReferenceIndexSetBTree]): self.height, self.parametres, self.root, - ( - ResolverMetaOrigin(resolver), - ) * (len(source) // (HashPoint.HASH_LENGTH + self.parametres.keysize) + 1) if self.height else () + (ResolverMetaOrigin(resolver),) * (len(source) // (HashPoint.HASH_LENGTH + self.parametres.keysize) + 1) + if self.height + else (), ) diff --git a/rainbowadn/wrisbt/wrisbtindex.py b/rainbowadn/wrisbt/wrisbtindex.py index c94c189..0cc16da 100644 --- a/rainbowadn/wrisbt/wrisbtindex.py +++ b/rainbowadn/wrisbt/wrisbtindex.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from typing import Iterable from rainbowadn.core import * @@ -5,16 +7,14 @@ from rainbowadn.core import * from .wrisbtparametres import * from .wrisbtroot import * -__all__ = ('WrisbtIndex', 'WrisbtIndexFactory',) +__all__ = ( + "WrisbtIndex", + "WrisbtIndexFactory", +) class WrisbtIndex(RecursiveMentionable): - def __init__( - self, - total: HashPoint[WrisbtRoot], - delta: HashPoint[WrisbtRoot], - keymin: int - ): + def __init__(self, total: HashPoint[WrisbtRoot], delta: HashPoint[WrisbtRoot], keymin: int): assert isinstance(total, HashPoint) assert isinstance(delta, HashPoint) assert isinstance(keymin, int) @@ -29,7 +29,7 @@ class WrisbtIndex(RecursiveMentionable): def __bytes__(self): return bytes(self.total) + bytes(self.delta) - def __factory__(self) -> RainbowFactory['WrisbtIndex']: + def __factory__(self) -> RainbowFactory[WrisbtIndex]: return WrisbtIndexFactory(self.keymin) async def str(self, tab: int) -> str: @@ -38,9 +38,7 @@ class WrisbtIndex(RecursiveMentionable): hash_point_format(self.total, tab), hash_point_format(self.delta, tab), ) - return f'(index)' \ - f'{tabulate(tab)}{total_str}' \ - f'{tabulate(tab)}{delta_str}' + return f"(index)" f"{tabulate(tab)}{total_str}" f"{tabulate(tab)}{delta_str}" class WrisbtIndexFactory(RainbowFactory[WrisbtIndex]): @@ -57,7 +55,7 @@ class WrisbtIndexFactory(RainbowFactory[WrisbtIndex]): assert isinstance(source, bytes) assert isinstance(resolver, HashResolver) return WrisbtIndex( - ResolverOrigin(self.root_factory, source[:HashPoint.HASH_LENGTH], resolver).hash_point(), - ResolverOrigin(self.root_factory, source[HashPoint.HASH_LENGTH:], resolver).hash_point(), - self.keymin + ResolverOrigin(self.root_factory, source[: HashPoint.HASH_LENGTH], resolver).hash_point(), + ResolverOrigin(self.root_factory, source[HashPoint.HASH_LENGTH :], resolver).hash_point(), + self.keymin, ) diff --git a/rainbowadn/wrisbt/wrisbtparametres.py b/rainbowadn/wrisbt/wrisbtparametres.py index 1d9c6db..56d1fe4 100644 --- a/rainbowadn/wrisbt/wrisbtparametres.py +++ b/rainbowadn/wrisbt/wrisbtparametres.py @@ -1,4 +1,4 @@ -__all__ = ('WrisbtParametres',) +__all__ = ("WrisbtParametres",) class WrisbtParametres: diff --git a/rainbowadn/wrisbt/wrisbtroot.py b/rainbowadn/wrisbt/wrisbtroot.py index 0f20eef..c054a88 100644 --- a/rainbowadn/wrisbt/wrisbtroot.py +++ b/rainbowadn/wrisbt/wrisbtroot.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from typing import Iterable from rainbowadn.atomic import * @@ -6,7 +8,10 @@ from rainbowadn.core import * from .weakreferenceindexsetbtree import * from .wrisbtparametres import * -__all__ = ('WrisbtRoot', 'WrisbtRootFactory',) +__all__ = ( + "WrisbtRoot", + "WrisbtRootFactory", +) class WrisbtRoot(RecursiveMentionable): @@ -18,7 +23,7 @@ class WrisbtRoot(RecursiveMentionable): self.height = height self.parametres = parametres - async def root_resolved(self) -> 'WeakReferenceIndexSetBTree': + async def root_resolved(self) -> WeakReferenceIndexSetBTree: return await self.root.resolve() def points(self) -> Iterable[HashPoint]: @@ -27,19 +32,17 @@ class WrisbtRoot(RecursiveMentionable): def __bytes__(self): return bytes(self.root) + bytes(Integer(self.height)) - def __factory__(self) -> RainbowFactory['WrisbtRoot']: + def __factory__(self) -> RainbowFactory[WrisbtRoot]: return WrisbtRootFactory(self.parametres) @classmethod - def empty(cls, parametres: WrisbtParametres) -> 'WrisbtRoot': + def empty(cls, parametres: WrisbtParametres) -> WrisbtRoot: assert isinstance(parametres, WrisbtParametres) - return WrisbtRoot(HashPoint.of(WeakReferenceIndexSetBTree(b'', 0, parametres, True, ())), 0, parametres) + return WrisbtRoot(HashPoint.of(WeakReferenceIndexSetBTree(b"", 0, parametres, True, ())), 0, parametres) async def str(self, tab: int) -> str: assert isinstance(tab, int) - return f'(root)' \ - f'{tabulate(tab)}{self.height}' \ - f'{tabulate(tab)}{await hash_point_format(self.root, tab)}' + return f"(root)" f"{tabulate(tab)}{self.height}" f"{tabulate(tab)}{await hash_point_format(self.root, tab)}" async def contains(self, key: bytes) -> bool: assert isinstance(key, bytes) @@ -50,7 +53,7 @@ class WrisbtRoot(RecursiveMentionable): return await root.contains(key) - async def add(self, key: bytes) -> 'WrisbtRoot': + async def add(self, key: bytes) -> WrisbtRoot: assert isinstance(key, bytes) assert_eq(len(key), self.parametres.keysize) @@ -67,22 +70,20 @@ class WrisbtRoot(RecursiveMentionable): root.height + 1, root.parametres, True, - (LocalMetaOrigin(LocalOrigin(left)), LocalMetaOrigin(LocalOrigin(right))) + (LocalMetaOrigin(LocalOrigin(left)), LocalMetaOrigin(LocalOrigin(right))), ) assert isinstance(root, WeakReferenceIndexSetBTree) return self.of(root) @classmethod - def of(cls, root: WeakReferenceIndexSetBTree) -> 'WrisbtRoot': + def of(cls, root: WeakReferenceIndexSetBTree) -> WrisbtRoot: assert isinstance(root, WeakReferenceIndexSetBTree) return cls(HashPoint.of(root), root.height, root.parametres) async def keys(self) -> list[bytes]: return list([x async for x in (await self.root_resolved()).iter_keys()]) - async def index( - self, target: HashPoint, exclude: 'WrisbtRoot' - ) -> 'WrisbtRoot': + async def index(self, target: HashPoint, exclude: WrisbtRoot) -> WrisbtRoot: assert isinstance(target, HashPoint) assert isinstance(exclude, WrisbtRoot) key: bytes = target.point @@ -111,12 +112,12 @@ class WrisbtRootFactory(RainbowFactory[WrisbtRoot]): def from_bytes(self, source: bytes, resolver: HashResolver) -> WrisbtRoot: assert isinstance(source, bytes) assert isinstance(resolver, HashResolver) - height: int = Integer.from_bytes(source[HashPoint.HASH_LENGTH:], resolver).integer + height: int = Integer.from_bytes(source[HashPoint.HASH_LENGTH :], resolver).integer assert isinstance(height, int) return WrisbtRoot( ResolverOrigin( - WrisbtFactory(height, self.parametres, True), source[:HashPoint.HASH_LENGTH], resolver + WrisbtFactory(height, self.parametres, True), source[: HashPoint.HASH_LENGTH], resolver ).hash_point(), height, - self.parametres + self.parametres, ) diff --git a/setup.py b/setup.py index 65a7b7f..8be06f3 100644 --- a/setup.py +++ b/setup.py @@ -1,15 +1,15 @@ from setuptools import setup setup( - name='rainbowadn', - version='', + name="rainbowadn", + version="", packages=[ - 'rainbowadn.core', - 'rainbowadn.instrument', + "rainbowadn.core", + "rainbowadn.instrument", ], - url='https://gitea.parrrate.ru/PTV/rainbowadn', - license='', - author='PARRRATE TNV', - author_email='', - description='' + url="https://gitea.parrrate.ru/PTV/rainbowadn", + license="", + author="PARRRATE TNV", + author_email="", + description="", ) diff --git a/trace_common.py b/trace_common.py index ad2d371..69091a7 100644 --- a/trace_common.py +++ b/trace_common.py @@ -11,7 +11,15 @@ from rainbowadn.instrument import * from rainbowadn.testing.resolvers import * __all__ = ( - 'get_dr', 'target_str', 'jsonify', 'get_fn', 'jsonify_list', 'dump', 'copy', 'DeintrumentationSize', 'Resolution' + "get_dr", + "target_str", + "jsonify", + "get_fn", + "jsonify_list", + "dump", + "copy", + "DeintrumentationSize", + "Resolution", ) @@ -34,24 +42,24 @@ def target_str(target) -> str: def jsonify(dumped: Instrumentation) -> dict: - prefix = f'{target_str(dumped.target)}:{dumped.methodname}' + prefix = f"{target_str(dumped.target)}:{dumped.methodname}" match dumped: case Counter(counter=ctr): - return {f'{prefix}:counter': ctr} + return {f"{prefix}:counter": ctr} case Concurrency(log=log): - return {f'{prefix}:concurrency': log} + return {f"{prefix}:concurrency": log} case EntryExit(entry_log=entry_log, exit_log=exit_log): return { - f'{prefix}:entry': entry_log, - f'{prefix}:exit': exit_log, + f"{prefix}:entry": entry_log, + f"{prefix}:exit": exit_log, } case _: return {} def get_fn() -> str: - Path('trace').mkdir(exist_ok=True) - return f'trace/{int(time.time())}-{os.urandom(2).hex()}.json' + Path("trace").mkdir(exist_ok=True) + return f"trace/{int(time.time())}-{os.urandom(2).hex()}.json" def jsonify_list(instrumentations: list[Instrumentation]) -> dict: @@ -62,32 +70,26 @@ def jsonify_list(instrumentations: list[Instrumentation]) -> dict: def dump(fn: str, jsonified: dict) -> None: - with open(fn, 'w') as file: - json.dump( - jsonified, - file - ) - print('dumped') + with open(fn, "w") as file: + json.dump(jsonified, file) + print("dumped") def copy(fn: str) -> None: - shutil.copy(fn, f'trace/latest.json') - print('copied') + shutil.copy(fn, f"trace/latest.json") + print("copied") class DeintrumentationSize(Instrumentation): def instrument(self, method, *args, **kwargs): - print( - f'deinstrumentation size @ {target_str(self.target)}:{self.methodname}', - len(self.deinstrumentation) - ) + print(f"deinstrumentation size @ {target_str(self.target)}:{self.methodname}", len(self.deinstrumentation)) return method(*args, **kwargs) class Resolution(Instrumentation): def __init__(self): self.report: dict[tuple[str, bytes, bytes], int] = {} - super().__init__(HashPoint, 'resolve') + super().__init__(HashPoint, "resolve") def increment(self, key: tuple[str, bytes, bytes]): self.report[key] = self.report.get(key, 0) + 1 @@ -100,5 +102,5 @@ class Resolution(Instrumentation): def format(self) -> str: s = StringIO() for key, count in sorted(self.report.items(), key=lambda t: (-t[1], t[0])): - s.write(f'{count: 6d}:{ClassReport.format_key(key)}\n') + s.write(f"{count: 6d}:{ClassReport.format_key(key)}\n") return s.getvalue() diff --git a/trace_flow.py b/trace_flow.py index 962ebf3..c35e3b7 100644 --- a/trace_flow.py +++ b/trace_flow.py @@ -17,12 +17,12 @@ from rainbowadn.v13 import * def get_instrumentations() -> list[Instrumentation]: - sleep_cc = Concurrency(DelayedResolver, 'sleep') + sleep_cc = Concurrency(DelayedResolver, "sleep") return [ sleep_cc, - Concurrency(ActiveBinaryTree, 'add'), - Concurrency(ActiveBinaryTree, 'contains'), - Concurrency(FlowStandard, 'verify_subset'), + Concurrency(ActiveBinaryTree, "add"), + Concurrency(ActiveBinaryTree, "contains"), + Concurrency(FlowStandard, "verify_subset"), ] @@ -38,8 +38,8 @@ def _generate_subject() -> Subject: async def _generate_transaction( - subjects_min: int, - subjects_max: int, + subjects_min: int, + subjects_max: int, ): in_coins: list[FlowCoin] = [] keys: list[SigningKey] = [] @@ -51,11 +51,8 @@ async def _generate_transaction( keys.append(reverse[(await coin.owner()).verify_key]) transaction = await FlowTransaction.make( in_coins, - [ - FlowCoinData.of(_generate_subject(), 0) - for _ in range(random.randint(subjects_min, subjects_max)) - ], - keys + [FlowCoinData.of(_generate_subject(), 0) for _ in range(random.randint(subjects_min, subjects_max))], + keys, ) for coinhp in await (await transaction.minted_reducer()).reduce(FlowIterate()): minted.add(coinhp) @@ -63,11 +60,11 @@ async def _generate_transaction( async def _generate( - blocks: int, - subjects_min: int, - subjects_max: int, - transactions_min: int, - transactions_max: int, + blocks: int, + subjects_min: int, + subjects_max: int, + transactions_min: int, + transactions_max: int, ) -> BankBlock: bank: BankBlock = BankBlock.empty() for _ in range(blocks): @@ -79,14 +76,14 @@ async def _generate( ] ) ) - print('generated') + print("generated") return bank async def _migrate(bank: BankBlock, params) -> BankBlock: assert_true(await bank.verify()) - bank = BankBlock(await get_dr(params['delay'], params['caching']).migrate_resolved(bank.reference)) - print('migrated') + bank = BankBlock(await get_dr(params["delay"], params["caching"]).migrate_resolved(bank.reference)) + print("migrated") return bank @@ -99,51 +96,51 @@ async def _instrument(process: Callable[[], Coroutine[Any, Any, None]]) -> list[ await process() except Terminated: pass - print('deinstrumentation (should be empty):', Instrumentation.deinstrumentation) - print('instrumented') + print("deinstrumentation (should be empty):", Instrumentation.deinstrumentation) + print("instrumented") return instrumentations async def _process(bank: BankBlock) -> None: - with Measure(bank, 'verify') as measurement: + with Measure(bank, "verify") as measurement: assert_true(await bank.verify()) - print('measured', *(f'{t:.3f}' for t in measurement.log)) + print("measured", *(f"{t:.3f}" for t in measurement.log)) async def _report(bank: BankBlock): - with open('trace/latest-report.txt', 'w') as file: + with open("trace/latest-report.txt", "w") as file: report = ClassReport() await report.walk(bank.reference) file.write(report.format()) - print('reported') + print("reported") async def _preprocess(bank: BankBlock): with Resolution() as resolution: await _process(bank) - with open('trace/latest-resolution.txt', 'w') as file: + with open("trace/latest-resolution.txt", "w") as file: file.write(resolution.format()) - print('preprocessed') + print("preprocessed") async def _trace(params): set_gather_linear() bank = await _generate( - params['blocks'], - *params['subjects'], - *params['transactions'], + params["blocks"], + *params["subjects"], + *params["transactions"], ) - if params['meta']: + if params["meta"]: await _report(bank) await _process(bank) await _preprocess(bank) bank = await _migrate(bank, params) set_gather_asyncio() - with DeintrumentationSize(Instrumentation, 'deinstrument'): - with Counter(DeintrumentationSize, 'instrument') as de_ctr: + with DeintrumentationSize(Instrumentation, "deinstrument"): + with Counter(DeintrumentationSize, "instrument") as de_ctr: instrumentations = await _instrument(lambda: _process(bank)) print(jsonify(de_ctr)) - print('traced') + print("traced") return instrumentations @@ -151,24 +148,20 @@ async def trace(params): instrumentations = await _trace(params) fn = get_fn() jsonified = jsonify_list(instrumentations) - dump(fn, jsonified | {'params': params}) + dump(fn, jsonified | {"params": params}) copy(fn) plot(fn) - print('plotted') + print("plotted") -preset_default = dict(caching=True, delay=.5, meta=False, subjects=(4, 8), transactions=(8, 16)) +preset_default = dict(caching=True, delay=0.5, meta=False, subjects=(4, 8), transactions=(8, 16)) preset_extra = preset_default | dict(blocks=256) preset_long = preset_default | dict(blocks=64) preset_short = preset_default | dict(blocks=16) -if __name__ == '__main__': +if __name__ == "__main__": random.seed(659918) try: - asyncio.run( - trace( - preset_short - ) - ) + asyncio.run(trace(preset_short)) except KeyboardInterrupt: - print('interrupted') + print("interrupted")