neco-quotient-encoding 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- neco_quotient_encoding/__init__.py +71 -0
- neco_quotient_encoding/canonical.py +190 -0
- neco_quotient_encoding/certificate.py +312 -0
- neco_quotient_encoding/digest.py +5 -0
- neco_quotient_encoding/failure.py +123 -0
- neco_quotient_encoding/parser.py +220 -0
- neco_quotient_encoding/value.py +34 -0
- neco_quotient_encoding-0.1.0.dist-info/METADATA +140 -0
- neco_quotient_encoding-0.1.0.dist-info/RECORD +11 -0
- neco_quotient_encoding-0.1.0.dist-info/WHEEL +5 -0
- neco_quotient_encoding-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
from .canonical import canonical_bytes, decode_canonical, normalize_residuals
|
|
2
|
+
from .certificate import (
|
|
3
|
+
CertificateWire,
|
|
4
|
+
CrossLanguage,
|
|
5
|
+
DigestScope,
|
|
6
|
+
ProjectionDigestWire,
|
|
7
|
+
SourceRefWire,
|
|
8
|
+
WithinRuntime,
|
|
9
|
+
)
|
|
10
|
+
from .digest import sha256_hex
|
|
11
|
+
from .failure import (
|
|
12
|
+
DuplicateKey,
|
|
13
|
+
EncodingCondition,
|
|
14
|
+
EncodingFailure,
|
|
15
|
+
EncodingResult,
|
|
16
|
+
Err,
|
|
17
|
+
MessageTooLong,
|
|
18
|
+
MissingField,
|
|
19
|
+
NotCanonical,
|
|
20
|
+
NumberNotCanonical,
|
|
21
|
+
Ok,
|
|
22
|
+
Parse,
|
|
23
|
+
ResidualsNotNormalized,
|
|
24
|
+
UnexpectedShape,
|
|
25
|
+
UnknownField,
|
|
26
|
+
condition_name,
|
|
27
|
+
)
|
|
28
|
+
from .value import (
|
|
29
|
+
JsonArray,
|
|
30
|
+
JsonBool,
|
|
31
|
+
JsonNull,
|
|
32
|
+
JsonNumber,
|
|
33
|
+
JsonObject,
|
|
34
|
+
JsonString,
|
|
35
|
+
JsonValue,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"CertificateWire",
|
|
40
|
+
"CrossLanguage",
|
|
41
|
+
"DigestScope",
|
|
42
|
+
"DuplicateKey",
|
|
43
|
+
"EncodingCondition",
|
|
44
|
+
"EncodingFailure",
|
|
45
|
+
"EncodingResult",
|
|
46
|
+
"Err",
|
|
47
|
+
"JsonArray",
|
|
48
|
+
"JsonBool",
|
|
49
|
+
"JsonNull",
|
|
50
|
+
"JsonNumber",
|
|
51
|
+
"JsonObject",
|
|
52
|
+
"JsonString",
|
|
53
|
+
"JsonValue",
|
|
54
|
+
"MessageTooLong",
|
|
55
|
+
"MissingField",
|
|
56
|
+
"NotCanonical",
|
|
57
|
+
"NumberNotCanonical",
|
|
58
|
+
"Ok",
|
|
59
|
+
"Parse",
|
|
60
|
+
"ProjectionDigestWire",
|
|
61
|
+
"ResidualsNotNormalized",
|
|
62
|
+
"SourceRefWire",
|
|
63
|
+
"UnexpectedShape",
|
|
64
|
+
"UnknownField",
|
|
65
|
+
"WithinRuntime",
|
|
66
|
+
"canonical_bytes",
|
|
67
|
+
"condition_name",
|
|
68
|
+
"decode_canonical",
|
|
69
|
+
"normalize_residuals",
|
|
70
|
+
"sha256_hex",
|
|
71
|
+
]
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
from collections.abc import Sequence
|
|
2
|
+
|
|
3
|
+
from .failure import (
|
|
4
|
+
DuplicateKey,
|
|
5
|
+
EncodingFailure,
|
|
6
|
+
EncodingResult,
|
|
7
|
+
Err,
|
|
8
|
+
NotCanonical,
|
|
9
|
+
NumberNotCanonical,
|
|
10
|
+
Ok,
|
|
11
|
+
Parse,
|
|
12
|
+
_Raised,
|
|
13
|
+
_RaisedCondition,
|
|
14
|
+
_wrap,
|
|
15
|
+
)
|
|
16
|
+
from .parser import ParseError, parse
|
|
17
|
+
from .value import (
|
|
18
|
+
JsonArray,
|
|
19
|
+
JsonBool,
|
|
20
|
+
JsonNull,
|
|
21
|
+
JsonNumber,
|
|
22
|
+
JsonObject,
|
|
23
|
+
JsonString,
|
|
24
|
+
JsonValue,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
_ESCAPES = {
|
|
28
|
+
'"': '\\"',
|
|
29
|
+
"\\": "\\\\",
|
|
30
|
+
"\b": "\\b",
|
|
31
|
+
"\f": "\\f",
|
|
32
|
+
"\n": "\\n",
|
|
33
|
+
"\r": "\\r",
|
|
34
|
+
"\t": "\\t",
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def canonical_bytes(value: JsonValue) -> EncodingResult[bytes]:
|
|
39
|
+
try:
|
|
40
|
+
return Ok(_canonical(value))
|
|
41
|
+
except _RaisedCondition as raised:
|
|
42
|
+
return Err(EncodingFailure("canonical_bytes", raised.condition))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def decode_canonical(data: bytes) -> EncodingResult[JsonValue]:
|
|
46
|
+
try:
|
|
47
|
+
parsed = parse(data)
|
|
48
|
+
except ParseError as error:
|
|
49
|
+
return Err(EncodingFailure("decode_canonical", Parse(str(error))))
|
|
50
|
+
encoded = canonical_bytes(parsed)
|
|
51
|
+
if isinstance(encoded, Err):
|
|
52
|
+
return Err(_wrap("decode_canonical", encoded.failure))
|
|
53
|
+
if encoded.value != data:
|
|
54
|
+
return Err(
|
|
55
|
+
EncodingFailure("decode_canonical", NotCanonical(encoded.value, bytes(data)))
|
|
56
|
+
)
|
|
57
|
+
return Ok(parsed)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _canonical(value: JsonValue) -> bytes:
|
|
61
|
+
_require_text(value)
|
|
62
|
+
out = bytearray()
|
|
63
|
+
_write(value, "$", out)
|
|
64
|
+
return bytes(out)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _normalize_value(value: JsonValue) -> JsonValue:
|
|
68
|
+
_require_text(value)
|
|
69
|
+
return _normalize_at(value, "$")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _unpaired(text: str) -> bool:
|
|
73
|
+
try:
|
|
74
|
+
text.encode("utf-8")
|
|
75
|
+
except UnicodeEncodeError:
|
|
76
|
+
return True
|
|
77
|
+
return False
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _require_text(value: JsonValue) -> None:
|
|
81
|
+
match value:
|
|
82
|
+
case JsonString(text):
|
|
83
|
+
if _unpaired(text):
|
|
84
|
+
raise _RaisedCondition(Parse("string contains an unpaired surrogate"))
|
|
85
|
+
case JsonArray(items):
|
|
86
|
+
for item in items:
|
|
87
|
+
_require_text(item)
|
|
88
|
+
case JsonObject(fields):
|
|
89
|
+
for key, child in fields:
|
|
90
|
+
if _unpaired(key):
|
|
91
|
+
raise _RaisedCondition(Parse("key contains an unpaired surrogate"))
|
|
92
|
+
_require_text(child)
|
|
93
|
+
case _:
|
|
94
|
+
pass
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _normalize_at(value: JsonValue, path: str) -> JsonValue:
|
|
98
|
+
match value:
|
|
99
|
+
case JsonNull() | JsonBool() | JsonString():
|
|
100
|
+
return value
|
|
101
|
+
case JsonNumber():
|
|
102
|
+
raise _RaisedCondition(NumberNotCanonical(path))
|
|
103
|
+
case JsonArray(items):
|
|
104
|
+
return JsonArray(
|
|
105
|
+
tuple(_normalize_at(item, f"{path}[{index}]") for index, item in enumerate(items))
|
|
106
|
+
)
|
|
107
|
+
case JsonObject(fields):
|
|
108
|
+
return JsonObject(
|
|
109
|
+
tuple(
|
|
110
|
+
(key, _normalize_at(child, f"{path}.{key}"))
|
|
111
|
+
for key, child in _sorted_fields(fields, path)
|
|
112
|
+
)
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _write(value: JsonValue, path: str, out: bytearray) -> None:
|
|
117
|
+
match value:
|
|
118
|
+
case JsonNull():
|
|
119
|
+
out += b"null"
|
|
120
|
+
case JsonBool(flag):
|
|
121
|
+
out += b"true" if flag else b"false"
|
|
122
|
+
case JsonNumber():
|
|
123
|
+
raise _RaisedCondition(NumberNotCanonical(path))
|
|
124
|
+
case JsonString(text):
|
|
125
|
+
_write_string(text, out)
|
|
126
|
+
case JsonArray(items):
|
|
127
|
+
out += b"["
|
|
128
|
+
for index, item in enumerate(items):
|
|
129
|
+
if index > 0:
|
|
130
|
+
out += b","
|
|
131
|
+
_write(item, f"{path}[{index}]", out)
|
|
132
|
+
out += b"]"
|
|
133
|
+
case JsonObject(fields):
|
|
134
|
+
out += b"{"
|
|
135
|
+
for index, (key, child) in enumerate(_sorted_fields(fields, path)):
|
|
136
|
+
if index > 0:
|
|
137
|
+
out += b","
|
|
138
|
+
_write_string(key, out)
|
|
139
|
+
out += b":"
|
|
140
|
+
_write(child, f"{path}.{key}", out)
|
|
141
|
+
out += b"}"
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _sorted_fields(
|
|
145
|
+
fields: tuple[tuple[str, JsonValue], ...], path: str
|
|
146
|
+
) -> list[tuple[str, JsonValue]]:
|
|
147
|
+
keyed = sorted(((key.encode("utf-8"), key, child) for key, child in fields), key=lambda entry: entry[0])
|
|
148
|
+
for index in range(1, len(keyed)):
|
|
149
|
+
if keyed[index - 1][0] == keyed[index][0]:
|
|
150
|
+
raise _RaisedCondition(DuplicateKey(path, keyed[index - 1][1]))
|
|
151
|
+
return [(key, child) for _, key, child in keyed]
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _write_string(text: str, out: bytearray) -> None:
|
|
155
|
+
pieces: list[str] = ['"']
|
|
156
|
+
for character in text:
|
|
157
|
+
escaped = _ESCAPES.get(character)
|
|
158
|
+
if escaped is not None:
|
|
159
|
+
pieces.append(escaped)
|
|
160
|
+
elif ord(character) < 0x20:
|
|
161
|
+
pieces.append(f"\\u{ord(character):04x}")
|
|
162
|
+
else:
|
|
163
|
+
pieces.append(character)
|
|
164
|
+
pieces.append('"')
|
|
165
|
+
out += "".join(pieces).encode("utf-8")
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _canonical_of(value: JsonValue) -> bytes:
|
|
169
|
+
result = canonical_bytes(value)
|
|
170
|
+
if isinstance(result, Err):
|
|
171
|
+
raise _Raised(result.failure)
|
|
172
|
+
return result.value
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def normalize_residuals(values: Sequence[JsonValue]) -> EncodingResult[tuple[JsonValue, ...]]:
|
|
176
|
+
keyed: list[tuple[bytes, JsonValue]] = []
|
|
177
|
+
try:
|
|
178
|
+
for residual in values:
|
|
179
|
+
normalized = _normalize_value(residual)
|
|
180
|
+
keyed.append((_canonical_of(normalized), normalized))
|
|
181
|
+
except _RaisedCondition as raised:
|
|
182
|
+
return Err(EncodingFailure("normalize_residuals", raised.condition))
|
|
183
|
+
except _Raised as raised:
|
|
184
|
+
return Err(_wrap("normalize_residuals", raised.failure))
|
|
185
|
+
keyed.sort(key=lambda entry: entry[0])
|
|
186
|
+
kept: list[tuple[bytes, JsonValue]] = []
|
|
187
|
+
for entry in keyed:
|
|
188
|
+
if not kept or kept[-1][0] != entry[0]:
|
|
189
|
+
kept.append(entry)
|
|
190
|
+
return Ok(tuple(value for _, value in kept))
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
from collections.abc import Sequence
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
|
|
4
|
+
from .canonical import _unpaired, canonical_bytes, normalize_residuals
|
|
5
|
+
from .digest import sha256_hex
|
|
6
|
+
from .failure import (
|
|
7
|
+
DuplicateKey,
|
|
8
|
+
EncodingCondition,
|
|
9
|
+
EncodingFailure,
|
|
10
|
+
EncodingResult,
|
|
11
|
+
Err,
|
|
12
|
+
MissingField,
|
|
13
|
+
Ok,
|
|
14
|
+
Parse,
|
|
15
|
+
ResidualsNotNormalized,
|
|
16
|
+
UnexpectedShape,
|
|
17
|
+
UnknownField,
|
|
18
|
+
_Raised,
|
|
19
|
+
_wrap,
|
|
20
|
+
)
|
|
21
|
+
from .value import (
|
|
22
|
+
JsonArray,
|
|
23
|
+
JsonBool,
|
|
24
|
+
JsonNull,
|
|
25
|
+
JsonNumber,
|
|
26
|
+
JsonObject,
|
|
27
|
+
JsonString,
|
|
28
|
+
JsonValue,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
RULE_REVISION = "rule_revision"
|
|
32
|
+
SOURCE = "source"
|
|
33
|
+
IDENTITY = "identity"
|
|
34
|
+
REVISION = "revision"
|
|
35
|
+
COORDINATE = "coordinate"
|
|
36
|
+
DIGESTS = "digests"
|
|
37
|
+
DIGEST = "digest"
|
|
38
|
+
SCOPE = "scope"
|
|
39
|
+
WITHIN_RUNTIME = "within_runtime"
|
|
40
|
+
CROSS_LANGUAGE = "cross_language"
|
|
41
|
+
RESIDUALS = "residuals"
|
|
42
|
+
OBSERVATIONS = "observations"
|
|
43
|
+
EVIDENCE = "evidence"
|
|
44
|
+
|
|
45
|
+
_FROM_VALUE = "from_value"
|
|
46
|
+
_TO_VALUE = "to_value"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class WithinRuntime:
|
|
51
|
+
name: str
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class CrossLanguage:
|
|
56
|
+
name: str
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
type DigestScope = WithinRuntime | CrossLanguage
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class ProjectionDigestWire:
|
|
64
|
+
digest: str
|
|
65
|
+
scope: DigestScope
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class SourceRefWire:
|
|
70
|
+
identity: str
|
|
71
|
+
revision: str
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass
|
|
75
|
+
class CertificateWire:
|
|
76
|
+
rule_revision: str
|
|
77
|
+
source: SourceRefWire
|
|
78
|
+
coordinate: JsonValue
|
|
79
|
+
digests: dict[str, ProjectionDigestWire]
|
|
80
|
+
residuals: tuple[JsonValue, ...]
|
|
81
|
+
observations: JsonValue
|
|
82
|
+
evidence: JsonValue
|
|
83
|
+
|
|
84
|
+
def to_value(self) -> EncodingResult[JsonValue]:
|
|
85
|
+
try:
|
|
86
|
+
return Ok(_to_value(self))
|
|
87
|
+
except _Raised as raised:
|
|
88
|
+
return Err(raised.failure)
|
|
89
|
+
|
|
90
|
+
@staticmethod
|
|
91
|
+
def from_value(value: JsonValue) -> EncodingResult[CertificateWire]:
|
|
92
|
+
try:
|
|
93
|
+
return Ok(_from_value(value))
|
|
94
|
+
except _Raised as raised:
|
|
95
|
+
return Err(raised.failure)
|
|
96
|
+
|
|
97
|
+
def canonical_bytes(self) -> EncodingResult[bytes]:
|
|
98
|
+
value = self.to_value()
|
|
99
|
+
if isinstance(value, Err):
|
|
100
|
+
return Err(_wrap("canonical_bytes", value.failure))
|
|
101
|
+
encoded = canonical_bytes(value.value)
|
|
102
|
+
if isinstance(encoded, Err):
|
|
103
|
+
return Err(_wrap("canonical_bytes", encoded.failure))
|
|
104
|
+
return encoded
|
|
105
|
+
|
|
106
|
+
def digest(self) -> EncodingResult[str]:
|
|
107
|
+
encoded = self.canonical_bytes()
|
|
108
|
+
if isinstance(encoded, Err):
|
|
109
|
+
return Err(_wrap("digest", encoded.failure))
|
|
110
|
+
return Ok(sha256_hex(encoded.value))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _fail(operation: str, condition: EncodingCondition) -> _Raised:
|
|
114
|
+
return _Raised(EncodingFailure(operation, condition))
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _json_strings(value: JsonValue) -> list[str]:
|
|
118
|
+
match value:
|
|
119
|
+
case JsonString(text):
|
|
120
|
+
return [text]
|
|
121
|
+
case JsonArray(items):
|
|
122
|
+
return [text for item in items for text in _json_strings(item)]
|
|
123
|
+
case JsonObject(fields):
|
|
124
|
+
return [text for key, child in fields for text in [key, *_json_strings(child)]]
|
|
125
|
+
case _:
|
|
126
|
+
return []
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _wire_strings(wire: CertificateWire) -> list[str]:
|
|
130
|
+
texts = [wire.rule_revision, wire.source.identity, wire.source.revision]
|
|
131
|
+
for name, projection in wire.digests.items():
|
|
132
|
+
texts.append(name)
|
|
133
|
+
texts.append(projection.digest)
|
|
134
|
+
texts.append(projection.scope.name)
|
|
135
|
+
for residual in wire.residuals:
|
|
136
|
+
texts.extend(_json_strings(residual))
|
|
137
|
+
for body in (wire.coordinate, wire.observations, wire.evidence):
|
|
138
|
+
texts.extend(_json_strings(body))
|
|
139
|
+
return texts
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _to_value(wire: CertificateWire) -> JsonValue:
|
|
143
|
+
if any(_unpaired(text) for text in _wire_strings(wire)):
|
|
144
|
+
raise _fail(_TO_VALUE, Parse("string contains an unpaired surrogate"))
|
|
145
|
+
_require_normalized_residuals(wire.residuals, _TO_VALUE)
|
|
146
|
+
return JsonObject(
|
|
147
|
+
(
|
|
148
|
+
(RULE_REVISION, JsonString(wire.rule_revision)),
|
|
149
|
+
(SOURCE, _source_to_value(wire.source)),
|
|
150
|
+
(COORDINATE, wire.coordinate),
|
|
151
|
+
(DIGESTS, _digests_to_value(wire.digests)),
|
|
152
|
+
(RESIDUALS, JsonArray(tuple(wire.residuals))),
|
|
153
|
+
(OBSERVATIONS, wire.observations),
|
|
154
|
+
(EVIDENCE, wire.evidence),
|
|
155
|
+
)
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _from_value(value: JsonValue) -> CertificateWire:
|
|
160
|
+
_ensure_keys(
|
|
161
|
+
value,
|
|
162
|
+
"certificate",
|
|
163
|
+
(RULE_REVISION, SOURCE, COORDINATE, DIGESTS, RESIDUALS, OBSERVATIONS, EVIDENCE),
|
|
164
|
+
)
|
|
165
|
+
digests = _digests_from_value(_field(value, DIGESTS))
|
|
166
|
+
residuals = _array_field(value, RESIDUALS)
|
|
167
|
+
_require_normalized_residuals(residuals, _FROM_VALUE)
|
|
168
|
+
coordinate = _field(value, COORDINATE)
|
|
169
|
+
observations = _field(value, OBSERVATIONS)
|
|
170
|
+
evidence = _field(value, EVIDENCE)
|
|
171
|
+
_require_canonical(coordinate, _FROM_VALUE)
|
|
172
|
+
_require_canonical(observations, _FROM_VALUE)
|
|
173
|
+
_require_canonical(evidence, _FROM_VALUE)
|
|
174
|
+
rule_revision = _string_field(value, RULE_REVISION)
|
|
175
|
+
source = _source_from_value(_field(value, SOURCE))
|
|
176
|
+
return CertificateWire(rule_revision, source, coordinate, digests, residuals, observations, evidence)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _require_normalized_residuals(residuals: Sequence[JsonValue], operation: str) -> None:
|
|
180
|
+
normalized = normalize_residuals(residuals)
|
|
181
|
+
if isinstance(normalized, Err):
|
|
182
|
+
raise _Raised(_wrap(operation, normalized.failure))
|
|
183
|
+
if normalized.value == tuple(residuals):
|
|
184
|
+
return
|
|
185
|
+
expected = canonical_bytes(JsonArray(normalized.value))
|
|
186
|
+
if isinstance(expected, Err):
|
|
187
|
+
raise _Raised(_wrap(operation, expected.failure))
|
|
188
|
+
actual = canonical_bytes(JsonArray(tuple(residuals)))
|
|
189
|
+
if isinstance(actual, Err):
|
|
190
|
+
raise _Raised(_wrap(operation, actual.failure))
|
|
191
|
+
raise _fail(operation, ResidualsNotNormalized(expected.value, actual.value))
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _require_canonical(value: JsonValue, operation: str) -> None:
|
|
195
|
+
encoded = canonical_bytes(value)
|
|
196
|
+
if isinstance(encoded, Err):
|
|
197
|
+
raise _Raised(_wrap(operation, encoded.failure))
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _source_to_value(source: SourceRefWire) -> JsonValue:
|
|
201
|
+
return JsonObject(
|
|
202
|
+
((IDENTITY, JsonString(source.identity)), (REVISION, JsonString(source.revision)))
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _source_from_value(value: JsonValue) -> SourceRefWire:
|
|
207
|
+
_ensure_keys(value, SOURCE, (IDENTITY, REVISION))
|
|
208
|
+
return SourceRefWire(_string_field(value, IDENTITY), _string_field(value, REVISION))
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _digests_to_value(digests: dict[str, ProjectionDigestWire]) -> JsonValue:
|
|
212
|
+
return JsonObject(
|
|
213
|
+
tuple(
|
|
214
|
+
(name, _digest_to_value(digests[name]))
|
|
215
|
+
for name in sorted(digests, key=lambda name: name.encode("utf-8"))
|
|
216
|
+
)
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _digest_to_value(digest: ProjectionDigestWire) -> JsonValue:
|
|
221
|
+
match digest.scope:
|
|
222
|
+
case WithinRuntime(name):
|
|
223
|
+
scope = JsonObject(((WITHIN_RUNTIME, JsonString(name)),))
|
|
224
|
+
case CrossLanguage(name):
|
|
225
|
+
scope = JsonObject(((CROSS_LANGUAGE, JsonString(name)),))
|
|
226
|
+
return JsonObject(((DIGEST, JsonString(digest.digest)), (SCOPE, scope)))
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _digests_from_value(value: JsonValue) -> dict[str, ProjectionDigestWire]:
|
|
230
|
+
if not isinstance(value, JsonObject):
|
|
231
|
+
raise _shape_failure(value, DIGESTS, "object")
|
|
232
|
+
_reject_duplicate_keys(value.fields, DIGESTS)
|
|
233
|
+
return {name: _digest_from_value(digest) for name, digest in value.fields}
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _digest_from_value(value: JsonValue) -> ProjectionDigestWire:
|
|
237
|
+
_ensure_keys(value, DIGEST, (DIGEST, SCOPE))
|
|
238
|
+
digest = _string_field(value, DIGEST)
|
|
239
|
+
return ProjectionDigestWire(digest, _scope_from_value(_field(value, SCOPE)))
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _scope_from_value(value: JsonValue) -> DigestScope:
|
|
243
|
+
_ensure_keys(value, SCOPE, (WITHIN_RUNTIME, CROSS_LANGUAGE))
|
|
244
|
+
if not isinstance(value, JsonObject):
|
|
245
|
+
raise _shape_failure(value, SCOPE, "object")
|
|
246
|
+
match value.fields:
|
|
247
|
+
case ((key, JsonString(name)),) if key == WITHIN_RUNTIME:
|
|
248
|
+
return WithinRuntime(name)
|
|
249
|
+
case ((key, JsonString(name)),) if key == CROSS_LANGUAGE:
|
|
250
|
+
return CrossLanguage(name)
|
|
251
|
+
case _:
|
|
252
|
+
raise _shape_failure(
|
|
253
|
+
value, SCOPE, "object with one of within_runtime or cross_language"
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _kind_name(value: JsonValue) -> str:
|
|
258
|
+
match value:
|
|
259
|
+
case JsonNull():
|
|
260
|
+
return "null"
|
|
261
|
+
case JsonBool():
|
|
262
|
+
return "bool"
|
|
263
|
+
case JsonNumber():
|
|
264
|
+
return "number"
|
|
265
|
+
case JsonString():
|
|
266
|
+
return "string"
|
|
267
|
+
case JsonArray():
|
|
268
|
+
return "array"
|
|
269
|
+
case JsonObject():
|
|
270
|
+
return "object"
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _shape_failure(value: JsonValue, name: str, expected: str) -> _Raised:
|
|
274
|
+
return _fail(_FROM_VALUE, UnexpectedShape(name, expected, _kind_name(value)))
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _reject_duplicate_keys(fields: tuple[tuple[str, JsonValue], ...], path: str) -> None:
|
|
278
|
+
for index, (key, _) in enumerate(fields):
|
|
279
|
+
if any(earlier == key for earlier, _ in fields[:index]):
|
|
280
|
+
raise _fail(_FROM_VALUE, DuplicateKey(path, key))
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _ensure_keys(value: JsonValue, name: str, known: tuple[str, ...]) -> None:
|
|
284
|
+
if not isinstance(value, JsonObject):
|
|
285
|
+
raise _shape_failure(value, name, "object")
|
|
286
|
+
fields = value.fields
|
|
287
|
+
unknown = next((index for index, (key, _) in enumerate(fields) if key not in known), None)
|
|
288
|
+
_reject_duplicate_keys(fields if unknown is None else fields[:unknown], name)
|
|
289
|
+
if unknown is not None:
|
|
290
|
+
raise _fail(_FROM_VALUE, UnknownField(fields[unknown][0]))
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _field(obj: JsonValue, name: str) -> JsonValue:
|
|
294
|
+
if isinstance(obj, JsonObject):
|
|
295
|
+
for key, child in obj.fields:
|
|
296
|
+
if key == name:
|
|
297
|
+
return child
|
|
298
|
+
raise _fail(_FROM_VALUE, MissingField(name))
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _string_field(obj: JsonValue, name: str) -> str:
|
|
302
|
+
value = _field(obj, name)
|
|
303
|
+
if isinstance(value, JsonString):
|
|
304
|
+
return value.value
|
|
305
|
+
raise _shape_failure(value, name, "string")
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _array_field(obj: JsonValue, name: str) -> tuple[JsonValue, ...]:
|
|
309
|
+
value = _field(obj, name)
|
|
310
|
+
if isinstance(value, JsonArray):
|
|
311
|
+
return value.items
|
|
312
|
+
raise _shape_failure(value, name, "array")
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
@dataclass(frozen=True)
|
|
5
|
+
class NumberNotCanonical:
|
|
6
|
+
path: str
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class DuplicateKey:
|
|
11
|
+
path: str
|
|
12
|
+
key: str
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class NotCanonical:
|
|
17
|
+
expected: bytes
|
|
18
|
+
actual: bytes
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class Parse:
|
|
23
|
+
message: str
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class MissingField:
|
|
28
|
+
field: str
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class UnknownField:
|
|
33
|
+
field: str
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class UnexpectedShape:
|
|
38
|
+
field: str
|
|
39
|
+
expected: str
|
|
40
|
+
actual: str
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class ResidualsNotNormalized:
|
|
45
|
+
expected: bytes
|
|
46
|
+
actual: bytes
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class MessageTooLong:
|
|
51
|
+
length: int
|
|
52
|
+
maximum: int
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
type EncodingCondition = (
|
|
56
|
+
NumberNotCanonical
|
|
57
|
+
| DuplicateKey
|
|
58
|
+
| NotCanonical
|
|
59
|
+
| Parse
|
|
60
|
+
| MissingField
|
|
61
|
+
| UnknownField
|
|
62
|
+
| UnexpectedShape
|
|
63
|
+
| ResidualsNotNormalized
|
|
64
|
+
| MessageTooLong
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class EncodingFailure:
|
|
70
|
+
operation: str
|
|
71
|
+
condition: EncodingCondition
|
|
72
|
+
contributing: tuple["EncodingFailure", ...] = ()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True)
|
|
76
|
+
class Ok[T]:
|
|
77
|
+
value: T
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class Err:
|
|
82
|
+
failure: EncodingFailure
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
type EncodingResult[T] = Ok[T] | Err
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def condition_name(failure: EncodingFailure) -> str:
|
|
89
|
+
match failure.condition:
|
|
90
|
+
case NumberNotCanonical():
|
|
91
|
+
return "number_not_canonical"
|
|
92
|
+
case DuplicateKey():
|
|
93
|
+
return "duplicate_key"
|
|
94
|
+
case NotCanonical():
|
|
95
|
+
return "not_canonical"
|
|
96
|
+
case Parse():
|
|
97
|
+
return "parse_failed"
|
|
98
|
+
case MissingField():
|
|
99
|
+
return "missing_field"
|
|
100
|
+
case UnknownField():
|
|
101
|
+
return "unknown_field"
|
|
102
|
+
case UnexpectedShape():
|
|
103
|
+
return "unexpected_shape"
|
|
104
|
+
case ResidualsNotNormalized():
|
|
105
|
+
return "residuals_not_normalized"
|
|
106
|
+
case MessageTooLong():
|
|
107
|
+
return "message_too_long"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class _Raised(Exception):
|
|
111
|
+
def __init__(self, failure: EncodingFailure) -> None:
|
|
112
|
+
super().__init__(failure.operation)
|
|
113
|
+
self.failure = failure
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class _RaisedCondition(Exception):
|
|
117
|
+
def __init__(self, condition: EncodingCondition) -> None:
|
|
118
|
+
super().__init__(type(condition).__name__)
|
|
119
|
+
self.condition = condition
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _wrap(operation: str, inner: EncodingFailure) -> EncodingFailure:
|
|
123
|
+
return EncodingFailure(operation, inner.condition, (inner,))
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
from .value import (
|
|
4
|
+
JsonArray,
|
|
5
|
+
JsonBool,
|
|
6
|
+
JsonNull,
|
|
7
|
+
JsonNumber,
|
|
8
|
+
JsonObject,
|
|
9
|
+
JsonString,
|
|
10
|
+
JsonValue,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
MAX_DEPTH = 128
|
|
14
|
+
|
|
15
|
+
_WHITESPACE = " \t\n\r"
|
|
16
|
+
_HEX_DIGITS = frozenset("0123456789abcdefABCDEF")
|
|
17
|
+
_NUMBER = re.compile(r"-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?")
|
|
18
|
+
_PLAIN = re.compile(r'[^"\\\x00-\x1f]*')
|
|
19
|
+
_SIMPLE_ESCAPES = {
|
|
20
|
+
'"': '"',
|
|
21
|
+
"\\": "\\",
|
|
22
|
+
"/": "/",
|
|
23
|
+
"b": "\b",
|
|
24
|
+
"f": "\f",
|
|
25
|
+
"n": "\n",
|
|
26
|
+
"r": "\r",
|
|
27
|
+
"t": "\t",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ParseError(Exception):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def parse(data: bytes) -> JsonValue:
|
|
36
|
+
try:
|
|
37
|
+
text = data.decode("utf-8")
|
|
38
|
+
except UnicodeDecodeError as error:
|
|
39
|
+
raise ParseError(f"invalid UTF-8 at byte {error.start}") from error
|
|
40
|
+
parser = _Parser(text)
|
|
41
|
+
value = parser.value()
|
|
42
|
+
parser.skip_whitespace()
|
|
43
|
+
if parser.position < len(text):
|
|
44
|
+
raise ParseError(f"trailing content at {parser.position}")
|
|
45
|
+
return value
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _Parser:
|
|
49
|
+
def __init__(self, text: str) -> None:
|
|
50
|
+
self.text = text
|
|
51
|
+
self.position = 0
|
|
52
|
+
self.depth = 0
|
|
53
|
+
|
|
54
|
+
def skip_whitespace(self) -> None:
|
|
55
|
+
text = self.text
|
|
56
|
+
position = self.position
|
|
57
|
+
while position < len(text) and text[position] in _WHITESPACE:
|
|
58
|
+
position += 1
|
|
59
|
+
self.position = position
|
|
60
|
+
|
|
61
|
+
def peek(self) -> str:
|
|
62
|
+
if self.position < len(self.text):
|
|
63
|
+
return self.text[self.position]
|
|
64
|
+
return ""
|
|
65
|
+
|
|
66
|
+
def fail(self, message: str) -> ParseError:
|
|
67
|
+
return ParseError(f"{message} at {self.position}")
|
|
68
|
+
|
|
69
|
+
def expect(self, expected: str) -> None:
|
|
70
|
+
if self.peek() != expected:
|
|
71
|
+
raise self.fail(f"expected {expected!r}")
|
|
72
|
+
self.position += 1
|
|
73
|
+
|
|
74
|
+
def literal(self, word: str) -> None:
|
|
75
|
+
if not self.text.startswith(word, self.position):
|
|
76
|
+
raise self.fail(f"invalid literal, expected {word!r}")
|
|
77
|
+
self.position += len(word)
|
|
78
|
+
|
|
79
|
+
def value(self) -> JsonValue:
|
|
80
|
+
self.skip_whitespace()
|
|
81
|
+
head = self.peek()
|
|
82
|
+
if head == "n":
|
|
83
|
+
self.literal("null")
|
|
84
|
+
return JsonNull()
|
|
85
|
+
if head == "t":
|
|
86
|
+
self.literal("true")
|
|
87
|
+
return JsonBool(True)
|
|
88
|
+
if head == "f":
|
|
89
|
+
self.literal("false")
|
|
90
|
+
return JsonBool(False)
|
|
91
|
+
if head == '"':
|
|
92
|
+
return JsonString(self.string())
|
|
93
|
+
if head == "[":
|
|
94
|
+
return self.array()
|
|
95
|
+
if head == "{":
|
|
96
|
+
return self.object()
|
|
97
|
+
if head == "-" or "0" <= head <= "9":
|
|
98
|
+
return self.number()
|
|
99
|
+
if head == "":
|
|
100
|
+
raise self.fail("unexpected end")
|
|
101
|
+
raise self.fail(f"unexpected character {head!r}")
|
|
102
|
+
|
|
103
|
+
def number(self) -> JsonValue:
|
|
104
|
+
matched = _NUMBER.match(self.text, self.position)
|
|
105
|
+
if matched is None:
|
|
106
|
+
raise self.fail("invalid number")
|
|
107
|
+
self.position = matched.end()
|
|
108
|
+
return JsonNumber(matched.group())
|
|
109
|
+
|
|
110
|
+
def hex4(self) -> int:
|
|
111
|
+
digits = self.text[self.position : self.position + 4]
|
|
112
|
+
if len(digits) != 4 or not all(digit in _HEX_DIGITS for digit in digits):
|
|
113
|
+
raise self.fail("invalid unicode escape")
|
|
114
|
+
self.position += 4
|
|
115
|
+
return int(digits, 16)
|
|
116
|
+
|
|
117
|
+
def escape(self) -> str:
|
|
118
|
+
head = self.peek()
|
|
119
|
+
if head == "":
|
|
120
|
+
raise self.fail("unexpected end")
|
|
121
|
+
self.position += 1
|
|
122
|
+
simple = _SIMPLE_ESCAPES.get(head)
|
|
123
|
+
if simple is not None:
|
|
124
|
+
return simple
|
|
125
|
+
if head != "u":
|
|
126
|
+
raise self.fail("invalid escape")
|
|
127
|
+
high = self.hex4()
|
|
128
|
+
if 0xD800 <= high <= 0xDBFF:
|
|
129
|
+
if not self.text.startswith("\\u", self.position):
|
|
130
|
+
raise self.fail("unpaired surrogate escape")
|
|
131
|
+
self.position += 2
|
|
132
|
+
low = self.hex4()
|
|
133
|
+
if not 0xDC00 <= low <= 0xDFFF:
|
|
134
|
+
raise self.fail("unpaired surrogate escape")
|
|
135
|
+
return chr((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)
|
|
136
|
+
if 0xDC00 <= high <= 0xDFFF:
|
|
137
|
+
raise self.fail("unpaired surrogate escape")
|
|
138
|
+
return chr(high)
|
|
139
|
+
|
|
140
|
+
def string(self) -> str:
|
|
141
|
+
self.expect('"')
|
|
142
|
+
parts: list[str] = []
|
|
143
|
+
while True:
|
|
144
|
+
matched = _PLAIN.match(self.text, self.position)
|
|
145
|
+
if matched is not None:
|
|
146
|
+
parts.append(matched.group())
|
|
147
|
+
self.position = matched.end()
|
|
148
|
+
head = self.peek()
|
|
149
|
+
if head == '"':
|
|
150
|
+
self.position += 1
|
|
151
|
+
return "".join(parts)
|
|
152
|
+
if head == "\\":
|
|
153
|
+
self.position += 1
|
|
154
|
+
parts.append(self.escape())
|
|
155
|
+
elif head == "":
|
|
156
|
+
raise self.fail("unexpected end")
|
|
157
|
+
else:
|
|
158
|
+
raise self.fail("control character in string")
|
|
159
|
+
|
|
160
|
+
def enter(self) -> None:
|
|
161
|
+
self.depth += 1
|
|
162
|
+
if self.depth > MAX_DEPTH:
|
|
163
|
+
raise self.fail("nesting too deep")
|
|
164
|
+
|
|
165
|
+
def array(self) -> JsonValue:
|
|
166
|
+
self.expect("[")
|
|
167
|
+
self.enter()
|
|
168
|
+
self.skip_whitespace()
|
|
169
|
+
items: list[JsonValue] = []
|
|
170
|
+
if self.peek() == "]":
|
|
171
|
+
self.position += 1
|
|
172
|
+
self.depth -= 1
|
|
173
|
+
return JsonArray(())
|
|
174
|
+
while True:
|
|
175
|
+
items.append(self.value())
|
|
176
|
+
self.skip_whitespace()
|
|
177
|
+
head = self.peek()
|
|
178
|
+
if head == ",":
|
|
179
|
+
self.position += 1
|
|
180
|
+
elif head == "]":
|
|
181
|
+
self.position += 1
|
|
182
|
+
self.depth -= 1
|
|
183
|
+
return JsonArray(tuple(items))
|
|
184
|
+
elif head == "":
|
|
185
|
+
raise self.fail("unexpected end")
|
|
186
|
+
else:
|
|
187
|
+
raise self.fail(f"unexpected character {head!r}")
|
|
188
|
+
|
|
189
|
+
def object(self) -> JsonValue:
|
|
190
|
+
self.expect("{")
|
|
191
|
+
self.enter()
|
|
192
|
+
self.skip_whitespace()
|
|
193
|
+
fields: list[tuple[str, JsonValue]] = []
|
|
194
|
+
if self.peek() == "}":
|
|
195
|
+
self.position += 1
|
|
196
|
+
self.depth -= 1
|
|
197
|
+
return JsonObject(())
|
|
198
|
+
while True:
|
|
199
|
+
self.skip_whitespace()
|
|
200
|
+
head = self.peek()
|
|
201
|
+
if head == "":
|
|
202
|
+
raise self.fail("unexpected end")
|
|
203
|
+
if head != '"':
|
|
204
|
+
raise self.fail(f"unexpected character {head!r}")
|
|
205
|
+
key = self.string()
|
|
206
|
+
self.skip_whitespace()
|
|
207
|
+
self.expect(":")
|
|
208
|
+
fields.append((key, self.value()))
|
|
209
|
+
self.skip_whitespace()
|
|
210
|
+
head = self.peek()
|
|
211
|
+
if head == ",":
|
|
212
|
+
self.position += 1
|
|
213
|
+
elif head == "}":
|
|
214
|
+
self.position += 1
|
|
215
|
+
self.depth -= 1
|
|
216
|
+
return JsonObject(tuple(fields))
|
|
217
|
+
elif head == "":
|
|
218
|
+
raise self.fail("unexpected end")
|
|
219
|
+
else:
|
|
220
|
+
raise self.fail(f"unexpected character {head!r}")
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
@dataclass(frozen=True)
|
|
5
|
+
class JsonNull:
|
|
6
|
+
pass
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class JsonBool:
|
|
11
|
+
value: bool
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class JsonNumber:
|
|
16
|
+
notation: str
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class JsonString:
|
|
21
|
+
value: str
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class JsonArray:
|
|
26
|
+
items: tuple["JsonValue", ...]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class JsonObject:
|
|
31
|
+
fields: tuple[tuple[str, "JsonValue"], ...]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
type JsonValue = JsonNull | JsonBool | JsonNumber | JsonString | JsonArray | JsonObject
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: neco-quotient-encoding
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 正規 JSON の符号化・復号と SHA-256 ハッシュ値
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Repository, https://github.com/barineco/neco-quotient
|
|
7
|
+
Requires-Python: >=3.14
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# neco-quotient-encoding ( Python )
|
|
11
|
+
|
|
12
|
+
正規 JSON の符号化・復号と SHA-256 ハッシュ値を扱う Python のパッケージです。依存は標準ライブラリだけで、証明書のパッケージから独立しています。
|
|
13
|
+
|
|
14
|
+
## 導入
|
|
15
|
+
|
|
16
|
+
Python 3.14 以降で動作します。リポジトリの `encoding/python` ディレクトリから導入します。
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install "git+https://github.com/barineco/neco-quotient.git#subdirectory=encoding/python"
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## 公開 API
|
|
23
|
+
|
|
24
|
+
| 名前 | 役割 |
|
|
25
|
+
|---|---|
|
|
26
|
+
| `canonical_bytes` | JSON の値から正規のバイト列を作る |
|
|
27
|
+
| `decode_canonical` | バイト列を JSON として読み、正規のバイト列を作り直して入力と比べる |
|
|
28
|
+
| `normalize_residuals` | 残余の各要素を正規化し、正規のバイト列の昇順に並べ、重複を除く |
|
|
29
|
+
| `sha256_hex` | バイト列の SHA-256 を小文字の 16 進 64 文字で返す |
|
|
30
|
+
| `CertificateWire` | 証明書の 7 つのフィールドを持ち、値とバイト列とダイジェストへ変換する |
|
|
31
|
+
| `DigestScope` | ダイジェストの適用範囲を表す和 |
|
|
32
|
+
| `ProjectionDigestWire` | ダイジェストの文字列と適用範囲 |
|
|
33
|
+
| `SourceRefWire` | 対象の識別子とリビジョン |
|
|
34
|
+
| `JsonValue` | JSON の値を表す和 |
|
|
35
|
+
| `EncodingFailure` | 操作の名前、条件、内側の失敗の列 |
|
|
36
|
+
| `EncodingCondition` | 失敗の条件の和 |
|
|
37
|
+
| `condition_name` | 失敗の条件の名前を返す |
|
|
38
|
+
| `EncodingResult` | 成功と失敗の結果の和 |
|
|
39
|
+
|
|
40
|
+
`CertificateWire` の操作:
|
|
41
|
+
|
|
42
|
+
| 名前 | 役割 |
|
|
43
|
+
|---|---|
|
|
44
|
+
| `to_value` | JSON の値へ変換する |
|
|
45
|
+
| `from_value` | JSON の値から読み出す |
|
|
46
|
+
| `canonical_bytes` | 正規のバイト列を作る |
|
|
47
|
+
| `digest` | 正規のバイト列の SHA-256 を返す |
|
|
48
|
+
|
|
49
|
+
和の構成要素:
|
|
50
|
+
|
|
51
|
+
| 和 | 構成要素 |
|
|
52
|
+
|---|---|
|
|
53
|
+
| `JsonValue` | `JsonNull` |
|
|
54
|
+
| `JsonValue` | `JsonBool` |
|
|
55
|
+
| `JsonValue` | `JsonNumber` |
|
|
56
|
+
| `JsonValue` | `JsonString` |
|
|
57
|
+
| `JsonValue` | `JsonArray` |
|
|
58
|
+
| `JsonValue` | `JsonObject` |
|
|
59
|
+
| `DigestScope` | `WithinRuntime` |
|
|
60
|
+
| `DigestScope` | `CrossLanguage` |
|
|
61
|
+
| `EncodingResult` | `Ok` |
|
|
62
|
+
| `EncodingResult` | `Err` |
|
|
63
|
+
|
|
64
|
+
`JsonNumber` は読み込んだ表記の文字列を持ち、`JsonObject` はキーと値の対の列で順序と重複を保ちます。
|
|
65
|
+
|
|
66
|
+
失敗の条件は 9 種です。`condition_name` が返す名前を併記します。
|
|
67
|
+
|
|
68
|
+
| 条件 | 名前 |
|
|
69
|
+
|---|---|
|
|
70
|
+
| `NumberNotCanonical` | `number_not_canonical` |
|
|
71
|
+
| `DuplicateKey` | `duplicate_key` |
|
|
72
|
+
| `NotCanonical` | `not_canonical` |
|
|
73
|
+
| `Parse` | `parse_failed` |
|
|
74
|
+
| `MissingField` | `missing_field` |
|
|
75
|
+
| `UnknownField` | `unknown_field` |
|
|
76
|
+
| `UnexpectedShape` | `unexpected_shape` |
|
|
77
|
+
| `ResidualsNotNormalized` | `residuals_not_normalized` |
|
|
78
|
+
| `MessageTooLong` | `message_too_long` |
|
|
79
|
+
|
|
80
|
+
## 正規のバイト列の規則
|
|
81
|
+
|
|
82
|
+
- オブジェクトのキーは UTF-8 のバイト列の順に並べる
|
|
83
|
+
- 重複したキーと数値は拒否する
|
|
84
|
+
- 空白を置かずに書く
|
|
85
|
+
- 文字列のエスケープは次の 7 つと、他の U+0020 未満の文字の `\u` と小文字 4 桁とし、他の文字は UTF-8 のまま書く
|
|
86
|
+
|
|
87
|
+
| 文字 | 出力 |
|
|
88
|
+
|---|---|
|
|
89
|
+
| 引用符 | `\"` |
|
|
90
|
+
| 逆斜線 | `\\` |
|
|
91
|
+
| 後退 | `\b` |
|
|
92
|
+
| 改頁 | `\f` |
|
|
93
|
+
| 改行 | `\n` |
|
|
94
|
+
| 復帰 | `\r` |
|
|
95
|
+
| 水平タブ | `\t` |
|
|
96
|
+
|
|
97
|
+
`str.encode("utf-8")` が失敗する文字列は、対の片方だけのサロゲートを持ちます。値の文字列とオブジェクトのキーにその文字列を含む値は、`Parse` の条件 ( `parse_failed` ) の失敗として返ります。この規則が適用される関数は以下の三つです。
|
|
98
|
+
|
|
99
|
+
- `canonical_bytes`
|
|
100
|
+
- `normalize_residuals`
|
|
101
|
+
- `CertificateWire.to_value`
|
|
102
|
+
|
|
103
|
+
## 使用例
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
from neco_quotient_encoding import (
|
|
107
|
+
Err,
|
|
108
|
+
JsonObject,
|
|
109
|
+
JsonString,
|
|
110
|
+
canonical_bytes,
|
|
111
|
+
decode_canonical,
|
|
112
|
+
sha256_hex,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
value = JsonObject((("b", JsonString("2")), ("a", JsonString("1"))))
|
|
116
|
+
encoded = canonical_bytes(value)
|
|
117
|
+
if isinstance(encoded, Err):
|
|
118
|
+
print(encoded.failure.operation)
|
|
119
|
+
else:
|
|
120
|
+
print(encoded.value) # b'{"a":"1","b":"2"}'
|
|
121
|
+
print(sha256_hex(encoded.value))
|
|
122
|
+
print(decode_canonical(encoded.value))
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
失敗は、`Err` の戻り値で返ります。`sha256_hex` は標準の `hashlib` で計算し、任意の長さの入力に対して常に文字列を返します。`MessageTooLong` は条件の型にだけ置かれています。
|
|
126
|
+
|
|
127
|
+
## 検査
|
|
128
|
+
|
|
129
|
+
`encoding/python` のディレクトリで、次のコマンドを実行します。
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
python3 -m unittest discover -s tests -v
|
|
133
|
+
python3 -m mypy neco_quotient_encoding
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
共通の比較は [comparison/canonical-encoding](../../comparison/canonical-encoding) の入力と Rust の結果を使います。
|
|
137
|
+
|
|
138
|
+
## ライセンス
|
|
139
|
+
|
|
140
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
neco_quotient_encoding/__init__.py,sha256=h5tyVbk-34yU0sijN6BvSzp1sjV8hDzUCBIJhFwifsk,1357
|
|
2
|
+
neco_quotient_encoding/canonical.py,sha256=DJqkAmNDFXzUX5x2Rx0G8kZsnKvpikUpJuxd0UWh5pg,5687
|
|
3
|
+
neco_quotient_encoding/certificate.py,sha256=3Zy9DNANYUuSMrE2B0KuOiwS9DDanr1MqwqtGEQS0DM,10018
|
|
4
|
+
neco_quotient_encoding/digest.py,sha256=XKuxN9XiJxJlLQij0wjlgbJB2giU9i4CNQ11cHAzrIo,97
|
|
5
|
+
neco_quotient_encoding/failure.py,sha256=d6LSEP2Ike7R23RX007X1RmHQBAI77JcjFa7JZV3dgs,2413
|
|
6
|
+
neco_quotient_encoding/parser.py,sha256=0WkDn8pHC8e1OAW_poo_ch0r32ED9W3Xdogu0xMt0PU,6780
|
|
7
|
+
neco_quotient_encoding/value.py,sha256=nxrwCSmWkLRHPifvzJUiTvZ4QVdO_-gUYJTMp_vS_H0,524
|
|
8
|
+
neco_quotient_encoding-0.1.0.dist-info/METADATA,sha256=AfjLWY3O0tTFt4yERkaTAZOk95-umq1qYoMerKlpfMg,5037
|
|
9
|
+
neco_quotient_encoding-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
neco_quotient_encoding-0.1.0.dist-info/top_level.txt,sha256=dwugy05M_YJ_L-gn_XEJ4Kk883bwZvTXG9ohyn8A7DU,23
|
|
11
|
+
neco_quotient_encoding-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
neco_quotient_encoding
|