1
1
import hashlib
2
- from typing import Any , Generator
2
+ from typing import Any , Generator , Type , Union
3
3
4
- from tarn .cache .storage import key_to_digest
4
+ from tarn .compat import HashAlgorithm
5
+ from tarn .pickler import dumps
5
6
6
7
from ..containers import EdgesBag
7
- from ..engine import Command , Details , Node , NodeHash , NodeHashes , Request , Response , StaticGraph , StaticHash
8
+ from ..engine import (
9
+ Command , Details , Node , NodeHash , NodeHashes , Request , Response , StaticGraph , StaticHash , CustomHash , LeafHash
10
+ )
8
11
from ..utils import StringsLike
9
12
from .base import CallableLayer
10
13
from .cache import to_seq
11
14
12
15
13
16
class HashDigest (CallableLayer ):
14
- def __init__ (self , names : StringsLike , algorithm ):
17
+ def __init__ (self , names : StringsLike , algorithm : Union [Type [HashAlgorithm ], str , None ] = None ,
18
+ return_value : bool = False ):
15
19
if isinstance (algorithm , str ):
16
20
algorithm = getattr (hashlib , algorithm )
17
21
@@ -22,7 +26,7 @@ def __init__(self, names: StringsLike, algorithm):
22
26
inp , out = Node (name , details ), Node (name , details )
23
27
inputs .append (inp )
24
28
outputs .append (out )
25
- edges .append (HashDigestEdge (algorithm ).bind (inp , out ))
29
+ edges .append (HashDigestEdge (algorithm , return_value ).bind (inp , out ))
26
30
27
31
super ().__init__ (EdgesBag (
28
32
inputs , outputs , edges ,
@@ -31,16 +35,27 @@ def __init__(self, names: StringsLike, algorithm):
31
35
32
36
33
37
class HashDigestEdge (StaticGraph , StaticHash ):
34
- def __init__ (self , algorithm ):
38
+ def __init__ (self , algorithm , return_value ):
35
39
super ().__init__ (arity = 1 )
36
40
self .algorithm = algorithm
41
+ self .return_value = return_value
37
42
38
43
def _make_hash (self , inputs : NodeHashes ) -> NodeHash :
39
- return inputs [ 0 ]
44
+ return CustomHash ( 'connectome.HashDigest' , LeafHash ( self . algorithm ), LeafHash ( self . return_value ), * inputs )
40
45
41
46
def evaluate (self ) -> Generator [Request , Response , Any ]:
42
- value = yield Command .ParentValue , 0
43
- output = yield Command .CurrentHash ,
47
+ result = []
48
+ if self .return_value :
49
+ value = yield Command .ParentValue , 0
50
+ result .append (value )
44
51
45
- pickled , digest = key_to_digest (self .algorithm , output .value )
46
- return value , output .value , digest , pickled
52
+ node_hash = yield Command .CurrentHash ,
53
+ node_hash = node_hash .value
54
+ result .append (node_hash )
55
+
56
+ pickled = dumps (node_hash )
57
+ result .append (pickled )
58
+ if self .algorithm is not None :
59
+ result .append (self .algorithm (pickled ).digest ())
60
+
61
+ return tuple (result )
0 commit comments