neco-quotient-encoding 0.1.0__tar.gz
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-0.1.0/PKG-INFO +140 -0
- neco_quotient_encoding-0.1.0/README.md +131 -0
- neco_quotient_encoding-0.1.0/neco_quotient_encoding/__init__.py +71 -0
- neco_quotient_encoding-0.1.0/neco_quotient_encoding/canonical.py +190 -0
- neco_quotient_encoding-0.1.0/neco_quotient_encoding/certificate.py +312 -0
- neco_quotient_encoding-0.1.0/neco_quotient_encoding/digest.py +5 -0
- neco_quotient_encoding-0.1.0/neco_quotient_encoding/failure.py +123 -0
- neco_quotient_encoding-0.1.0/neco_quotient_encoding/parser.py +220 -0
- neco_quotient_encoding-0.1.0/neco_quotient_encoding/value.py +34 -0
- neco_quotient_encoding-0.1.0/neco_quotient_encoding.egg-info/PKG-INFO +140 -0
- neco_quotient_encoding-0.1.0/neco_quotient_encoding.egg-info/SOURCES.txt +20 -0
- neco_quotient_encoding-0.1.0/neco_quotient_encoding.egg-info/dependency_links.txt +1 -0
- neco_quotient_encoding-0.1.0/neco_quotient_encoding.egg-info/top_level.txt +1 -0
- neco_quotient_encoding-0.1.0/pyproject.toml +20 -0
- neco_quotient_encoding-0.1.0/setup.cfg +4 -0
- neco_quotient_encoding-0.1.0/tests/test_comparison_encoding.py +197 -0
- neco_quotient_encoding-0.1.0/tests/test_invalid.py +223 -0
- neco_quotient_encoding-0.1.0/tests/test_permutation.py +90 -0
- neco_quotient_encoding-0.1.0/tests/test_preservation.py +86 -0
- neco_quotient_encoding-0.1.0/tests/test_roundtrip.py +69 -0
- neco_quotient_encoding-0.1.0/tests/test_unpaired_surrogate.py +76 -0
- neco_quotient_encoding-0.1.0/tests/test_vector.py +51 -0
|
@@ -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,131 @@
|
|
|
1
|
+
# neco-quotient-encoding ( Python )
|
|
2
|
+
|
|
3
|
+
正規 JSON の符号化・復号と SHA-256 ハッシュ値を扱う Python のパッケージです。依存は標準ライブラリだけで、証明書のパッケージから独立しています。
|
|
4
|
+
|
|
5
|
+
## 導入
|
|
6
|
+
|
|
7
|
+
Python 3.14 以降で動作します。リポジトリの `encoding/python` ディレクトリから導入します。
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install "git+https://github.com/barineco/neco-quotient.git#subdirectory=encoding/python"
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## 公開 API
|
|
14
|
+
|
|
15
|
+
| 名前 | 役割 |
|
|
16
|
+
|---|---|
|
|
17
|
+
| `canonical_bytes` | JSON の値から正規のバイト列を作る |
|
|
18
|
+
| `decode_canonical` | バイト列を JSON として読み、正規のバイト列を作り直して入力と比べる |
|
|
19
|
+
| `normalize_residuals` | 残余の各要素を正規化し、正規のバイト列の昇順に並べ、重複を除く |
|
|
20
|
+
| `sha256_hex` | バイト列の SHA-256 を小文字の 16 進 64 文字で返す |
|
|
21
|
+
| `CertificateWire` | 証明書の 7 つのフィールドを持ち、値とバイト列とダイジェストへ変換する |
|
|
22
|
+
| `DigestScope` | ダイジェストの適用範囲を表す和 |
|
|
23
|
+
| `ProjectionDigestWire` | ダイジェストの文字列と適用範囲 |
|
|
24
|
+
| `SourceRefWire` | 対象の識別子とリビジョン |
|
|
25
|
+
| `JsonValue` | JSON の値を表す和 |
|
|
26
|
+
| `EncodingFailure` | 操作の名前、条件、内側の失敗の列 |
|
|
27
|
+
| `EncodingCondition` | 失敗の条件の和 |
|
|
28
|
+
| `condition_name` | 失敗の条件の名前を返す |
|
|
29
|
+
| `EncodingResult` | 成功と失敗の結果の和 |
|
|
30
|
+
|
|
31
|
+
`CertificateWire` の操作:
|
|
32
|
+
|
|
33
|
+
| 名前 | 役割 |
|
|
34
|
+
|---|---|
|
|
35
|
+
| `to_value` | JSON の値へ変換する |
|
|
36
|
+
| `from_value` | JSON の値から読み出す |
|
|
37
|
+
| `canonical_bytes` | 正規のバイト列を作る |
|
|
38
|
+
| `digest` | 正規のバイト列の SHA-256 を返す |
|
|
39
|
+
|
|
40
|
+
和の構成要素:
|
|
41
|
+
|
|
42
|
+
| 和 | 構成要素 |
|
|
43
|
+
|---|---|
|
|
44
|
+
| `JsonValue` | `JsonNull` |
|
|
45
|
+
| `JsonValue` | `JsonBool` |
|
|
46
|
+
| `JsonValue` | `JsonNumber` |
|
|
47
|
+
| `JsonValue` | `JsonString` |
|
|
48
|
+
| `JsonValue` | `JsonArray` |
|
|
49
|
+
| `JsonValue` | `JsonObject` |
|
|
50
|
+
| `DigestScope` | `WithinRuntime` |
|
|
51
|
+
| `DigestScope` | `CrossLanguage` |
|
|
52
|
+
| `EncodingResult` | `Ok` |
|
|
53
|
+
| `EncodingResult` | `Err` |
|
|
54
|
+
|
|
55
|
+
`JsonNumber` は読み込んだ表記の文字列を持ち、`JsonObject` はキーと値の対の列で順序と重複を保ちます。
|
|
56
|
+
|
|
57
|
+
失敗の条件は 9 種です。`condition_name` が返す名前を併記します。
|
|
58
|
+
|
|
59
|
+
| 条件 | 名前 |
|
|
60
|
+
|---|---|
|
|
61
|
+
| `NumberNotCanonical` | `number_not_canonical` |
|
|
62
|
+
| `DuplicateKey` | `duplicate_key` |
|
|
63
|
+
| `NotCanonical` | `not_canonical` |
|
|
64
|
+
| `Parse` | `parse_failed` |
|
|
65
|
+
| `MissingField` | `missing_field` |
|
|
66
|
+
| `UnknownField` | `unknown_field` |
|
|
67
|
+
| `UnexpectedShape` | `unexpected_shape` |
|
|
68
|
+
| `ResidualsNotNormalized` | `residuals_not_normalized` |
|
|
69
|
+
| `MessageTooLong` | `message_too_long` |
|
|
70
|
+
|
|
71
|
+
## 正規のバイト列の規則
|
|
72
|
+
|
|
73
|
+
- オブジェクトのキーは UTF-8 のバイト列の順に並べる
|
|
74
|
+
- 重複したキーと数値は拒否する
|
|
75
|
+
- 空白を置かずに書く
|
|
76
|
+
- 文字列のエスケープは次の 7 つと、他の U+0020 未満の文字の `\u` と小文字 4 桁とし、他の文字は UTF-8 のまま書く
|
|
77
|
+
|
|
78
|
+
| 文字 | 出力 |
|
|
79
|
+
|---|---|
|
|
80
|
+
| 引用符 | `\"` |
|
|
81
|
+
| 逆斜線 | `\\` |
|
|
82
|
+
| 後退 | `\b` |
|
|
83
|
+
| 改頁 | `\f` |
|
|
84
|
+
| 改行 | `\n` |
|
|
85
|
+
| 復帰 | `\r` |
|
|
86
|
+
| 水平タブ | `\t` |
|
|
87
|
+
|
|
88
|
+
`str.encode("utf-8")` が失敗する文字列は、対の片方だけのサロゲートを持ちます。値の文字列とオブジェクトのキーにその文字列を含む値は、`Parse` の条件 ( `parse_failed` ) の失敗として返ります。この規則が適用される関数は以下の三つです。
|
|
89
|
+
|
|
90
|
+
- `canonical_bytes`
|
|
91
|
+
- `normalize_residuals`
|
|
92
|
+
- `CertificateWire.to_value`
|
|
93
|
+
|
|
94
|
+
## 使用例
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from neco_quotient_encoding import (
|
|
98
|
+
Err,
|
|
99
|
+
JsonObject,
|
|
100
|
+
JsonString,
|
|
101
|
+
canonical_bytes,
|
|
102
|
+
decode_canonical,
|
|
103
|
+
sha256_hex,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
value = JsonObject((("b", JsonString("2")), ("a", JsonString("1"))))
|
|
107
|
+
encoded = canonical_bytes(value)
|
|
108
|
+
if isinstance(encoded, Err):
|
|
109
|
+
print(encoded.failure.operation)
|
|
110
|
+
else:
|
|
111
|
+
print(encoded.value) # b'{"a":"1","b":"2"}'
|
|
112
|
+
print(sha256_hex(encoded.value))
|
|
113
|
+
print(decode_canonical(encoded.value))
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
失敗は、`Err` の戻り値で返ります。`sha256_hex` は標準の `hashlib` で計算し、任意の長さの入力に対して常に文字列を返します。`MessageTooLong` は条件の型にだけ置かれています。
|
|
117
|
+
|
|
118
|
+
## 検査
|
|
119
|
+
|
|
120
|
+
`encoding/python` のディレクトリで、次のコマンドを実行します。
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
python3 -m unittest discover -s tests -v
|
|
124
|
+
python3 -m mypy neco_quotient_encoding
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
共通の比較は [comparison/canonical-encoding](../../comparison/canonical-encoding) の入力と Rust の結果を使います。
|
|
128
|
+
|
|
129
|
+
## ライセンス
|
|
130
|
+
|
|
131
|
+
MIT
|
|
@@ -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))
|