20
20
21
21
"""
22
22
23
+ from typing import Callable , Optional , Union
24
+
23
25
from securesystemslib import exceptions
24
26
25
27
26
- def _canonical_string_encoder (string ) :
28
+ def _canonical_string_encoder (string : str ) -> str :
27
29
"""
28
30
<Purpose>
29
- Encode 'string' to canonical string format.
31
+ Encode 'string' to canonical string format. By using the escape sequence ('\' )
32
+ which is mandatory to use for quote and backslash.
33
+ backslash: \\ translates to \\ \\
34
+ quote: \" translates to \\ ".
30
35
31
36
<Arguments>
32
37
string:
@@ -41,13 +46,14 @@ def _canonical_string_encoder(string):
41
46
<Returns>
42
47
A string with the canonical-encoded 'string' embedded.
43
48
"""
44
-
45
49
string = '"{}"' .format (string .replace ("\\ " , "\\ \\ " ).replace ('"' , '\\ "' ))
46
50
47
51
return string
48
52
49
53
50
- def _encode_canonical (object , output_function ):
54
+ def _encode_canonical (
55
+ object : Union [bool , None , str , int , tuple , list , dict ], output_function : Callable
56
+ ) -> None :
51
57
# Helper for encode_canonical. Older versions of json.encoder don't
52
58
# even let us replace the separators.
53
59
@@ -88,11 +94,15 @@ def _encode_canonical(object, output_function):
88
94
89
95
90
96
def encode_canonical (
91
- object ,
92
- output_function = None ,
93
- ):
97
+ object : Union [ bool , None , str , int , tuple , list , dict ] ,
98
+ output_function : Optional [ Callable ] = None ,
99
+ ) -> Union [ str , None ] :
94
100
"""
95
101
<Purpose>
102
+ Encoding an object so that it is always has the same string format
103
+ independent of the original format. This allows to compute always the same hash
104
+ or signature for that object.
105
+
96
106
Encode 'object' in canonical JSON form, as specified at
97
107
http://wiki.laptop.org/go/Canonical_JSON . It's a restricted
98
108
dialect of JSON in which keys are always lexically sorted,
@@ -140,7 +150,7 @@ def encode_canonical(
140
150
A string representing the 'object' encoded in canonical JSON form.
141
151
"""
142
152
143
- result = None
153
+ result : Union [ None , list ] = None
144
154
# If 'output_function' is unset, treat it as
145
155
# appending to a list.
146
156
if output_function is None :
@@ -151,11 +161,12 @@ def encode_canonical(
151
161
_encode_canonical (object , output_function )
152
162
153
163
except (TypeError , exceptions .FormatError ) as e :
154
- message = "Could not encode " + repr (object ) + ": " + str (e )
164
+ message : str = "Could not encode " + repr (object ) + ": " + str (e )
155
165
raise exceptions .FormatError (message )
156
166
157
167
# Return the encoded 'object' as a string.
158
168
# Note: Implies 'output_function' is None,
159
169
# otherwise results are sent to 'output_function'.
160
170
if result is not None :
161
171
return "" .join (result )
172
+ return None
0 commit comments