canonprims 0.2.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.
- canonprims/__init__.py +419 -0
- canonprims/_compose.py +141 -0
- canonprims/_jcs.py +409 -0
- canonprims/py.typed +0 -0
- canonprims-0.2.0.dist-info/METADATA +67 -0
- canonprims-0.2.0.dist-info/RECORD +10 -0
- canonprims-0.2.0.dist-info/WHEEL +4 -0
- canonprims-0.2.0.dist-info/licenses/LICENSE-APACHE +190 -0
- canonprims-0.2.0.dist-info/licenses/LICENSE-MIT +21 -0
- canonprims-0.2.0.dist-info/licenses/NOTICE +25 -0
canonprims/__init__.py
ADDED
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""RFC 8785 JSON canonicalization over a strict I-JSON loader.
|
|
3
|
+
|
|
4
|
+
A pure-Python implementation of the ``jcs/rfc8785`` scheme, with no
|
|
5
|
+
dependencies outside the standard library, gated by the same conformance
|
|
6
|
+
corpus as the Rust crate and the Go package and compared with them byte for
|
|
7
|
+
byte. The same four verbs: :func:`canonicalize`, :func:`check`,
|
|
8
|
+
:func:`digest` and :func:`scheme_info`, and the same composition helpers:
|
|
9
|
+
:func:`vector`, :func:`vector_of_canonical`, :func:`ndjson_elements`,
|
|
10
|
+
:func:`canonicalize_ndjson`, :func:`sort_canonical_set`,
|
|
11
|
+
:func:`check_canonical_set` and :func:`assemble_canonical_set`.
|
|
12
|
+
|
|
13
|
+
Input is bytes from any object that exports a buffer (its raw bytes, in C
|
|
14
|
+
order); a ``str`` is encoded as UTF-8 and nothing else. An input with no
|
|
15
|
+
canonical form raises :class:`Refusal` carrying one normative code; nothing
|
|
16
|
+
is repaired.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import hashlib
|
|
22
|
+
from dataclasses import dataclass
|
|
23
|
+
from typing import Final, Iterable, Optional, Union
|
|
24
|
+
|
|
25
|
+
from . import _compose, _jcs
|
|
26
|
+
from ._jcs import Stop as _Stop
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"CODES",
|
|
30
|
+
"SET_CODES",
|
|
31
|
+
"Limits",
|
|
32
|
+
"Refusal",
|
|
33
|
+
"SchemeInfo",
|
|
34
|
+
"Vector",
|
|
35
|
+
"assemble_canonical_set",
|
|
36
|
+
"canonicalize",
|
|
37
|
+
"canonicalize_ndjson",
|
|
38
|
+
"check",
|
|
39
|
+
"check_canonical_set",
|
|
40
|
+
"digest",
|
|
41
|
+
"ndjson_elements",
|
|
42
|
+
"scheme_info",
|
|
43
|
+
"sort_canonical_set",
|
|
44
|
+
"vector",
|
|
45
|
+
"vector_of_canonical",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
__version__: Final[str] = "0.2.0"
|
|
49
|
+
|
|
50
|
+
Input = Union[bytes, bytearray, memoryview, str] # or any buffer exporter
|
|
51
|
+
|
|
52
|
+
#: Every refusal code of the four verbs, in spec order. ``not_canonical``
|
|
53
|
+
#: comes only from check (and the helpers that require canonical input).
|
|
54
|
+
CODES: Final = (
|
|
55
|
+
"too_large",
|
|
56
|
+
"invalid_utf8",
|
|
57
|
+
"invalid_json",
|
|
58
|
+
"lone_surrogate",
|
|
59
|
+
"noncharacter",
|
|
60
|
+
"duplicate_member",
|
|
61
|
+
"non_finite_number",
|
|
62
|
+
"integer_outside_binary64",
|
|
63
|
+
"too_deep",
|
|
64
|
+
"not_canonical",
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
#: The two refusal codes only the canonical-set helpers produce.
|
|
68
|
+
SET_CODES: Final = (
|
|
69
|
+
"not_an_array",
|
|
70
|
+
"duplicate_set_element",
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
_SCHEME: Final = "jcs/rfc8785"
|
|
74
|
+
# The sha256 of the conformance corpus MANIFEST.json this implementation was
|
|
75
|
+
# gated against (the test suite checks it against the corpus).
|
|
76
|
+
_CORPUS_DIGEST: Final = "sha256:de3ac543580ddb90f7e3a6e72239097274d3635ea783f302a9260b5a7d0c8d90"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class Refusal(ValueError):
|
|
80
|
+
"""The input has no canonical form (or, from :func:`check`, is not in it).
|
|
81
|
+
|
|
82
|
+
``code`` is normative and identical across languages; ``offset`` is the
|
|
83
|
+
informative byte offset in the input where the defect was found.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
def __init__(self, code: str, offset: int) -> None:
|
|
87
|
+
super().__init__(f"{code} at byte {offset}")
|
|
88
|
+
self.code = code
|
|
89
|
+
self.offset = offset
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass(frozen=True)
|
|
93
|
+
class Limits:
|
|
94
|
+
"""Explicit resource limits; every verb takes one.
|
|
95
|
+
|
|
96
|
+
Exceeding a limit is a ``too_large`` or ``too_deep`` refusal. A limit of 0
|
|
97
|
+
allows none of that thing, and a negative limit behaves as 0. Each limit
|
|
98
|
+
must be an ``int`` (not ``bool``). The defaults match every other
|
|
99
|
+
canonprims implementation.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
max_bytes: int = _jcs.DEFAULT_MAX_BYTES
|
|
103
|
+
max_depth: int = _jcs.DEFAULT_MAX_DEPTH
|
|
104
|
+
max_object_members: int = _jcs.DEFAULT_MAX_OBJECT_MEMBERS
|
|
105
|
+
max_string_bytes: int = _jcs.DEFAULT_MAX_STRING_BYTES
|
|
106
|
+
|
|
107
|
+
def __post_init__(self) -> None:
|
|
108
|
+
for name in ("max_bytes", "max_depth", "max_object_members", "max_string_bytes"):
|
|
109
|
+
value = getattr(self, name)
|
|
110
|
+
if type(value) is not int:
|
|
111
|
+
raise TypeError(f"Limits.{name} must be an int, got {value!r}")
|
|
112
|
+
|
|
113
|
+
def _args(self) -> tuple[int, int, int, int]:
|
|
114
|
+
return (
|
|
115
|
+
max(self.max_bytes, 0),
|
|
116
|
+
max(self.max_depth, 0),
|
|
117
|
+
max(self.max_object_members, 0),
|
|
118
|
+
max(self.max_string_bytes, 0),
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@dataclass(frozen=True)
|
|
123
|
+
class SchemeInfo:
|
|
124
|
+
"""What the scheme is and which corpus gated this build."""
|
|
125
|
+
|
|
126
|
+
scheme: str
|
|
127
|
+
spec: str
|
|
128
|
+
corpus: str
|
|
129
|
+
corpus_digest: str
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@dataclass(frozen=True, init=False)
|
|
133
|
+
class Vector:
|
|
134
|
+
"""A golden test vector: canonical bytes with their length and digest.
|
|
135
|
+
|
|
136
|
+
Made only by :func:`vector` (from any input) or
|
|
137
|
+
:func:`vector_of_canonical` (from bytes that must already be canonical),
|
|
138
|
+
so it always holds canonical bytes.
|
|
139
|
+
"""
|
|
140
|
+
|
|
141
|
+
canonical: bytes
|
|
142
|
+
digest: str
|
|
143
|
+
|
|
144
|
+
def __init__(self, *args: object, **kwargs: object) -> None:
|
|
145
|
+
raise TypeError("make a Vector with canonprims.vector or canonprims.vector_of_canonical")
|
|
146
|
+
|
|
147
|
+
@classmethod
|
|
148
|
+
def _of(cls, canonical: bytes) -> "Vector":
|
|
149
|
+
v = object.__new__(cls)
|
|
150
|
+
object.__setattr__(v, "canonical", canonical)
|
|
151
|
+
object.__setattr__(v, "digest", _sha256(canonical))
|
|
152
|
+
return v
|
|
153
|
+
|
|
154
|
+
@property
|
|
155
|
+
def byte_length(self) -> int:
|
|
156
|
+
return len(self.canonical)
|
|
157
|
+
|
|
158
|
+
@property
|
|
159
|
+
def scheme(self) -> str:
|
|
160
|
+
return _SCHEME
|
|
161
|
+
|
|
162
|
+
def to_json(self) -> bytes:
|
|
163
|
+
"""The vector as one canonical JSON object, with no trailing newline:
|
|
164
|
+
``{"byte_length":N,"canonical":"...","digest":"sha256:...","scheme":"jcs/rfc8785"}``."""
|
|
165
|
+
text = _jcs.quote(self.canonical.decode("utf-8"))
|
|
166
|
+
return (
|
|
167
|
+
f'{{"byte_length":{len(self.canonical)},"canonical":{text},'
|
|
168
|
+
f'"digest":"{self.digest}","scheme":"{_SCHEME}"}}'
|
|
169
|
+
).encode("utf-8")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _bytes(data: Input, cap: Optional[int] = None) -> bytes:
|
|
173
|
+
"""The input's bytes. With ``cap`` (the call's ``max_bytes``), an input
|
|
174
|
+
longer than ``cap`` is refused as ``too_large`` before anything is copied
|
|
175
|
+
or encoded: a buffer by its byte length, a ``str`` by its length (its
|
|
176
|
+
UTF-8 form is never shorter). ``bytes`` is used as it is, not copied."""
|
|
177
|
+
if isinstance(data, str):
|
|
178
|
+
if cap is not None and len(data) > cap:
|
|
179
|
+
raise Refusal("too_large", cap)
|
|
180
|
+
return data.encode("utf-8")
|
|
181
|
+
if type(data) is bytes:
|
|
182
|
+
if cap is not None and len(data) > cap:
|
|
183
|
+
raise Refusal("too_large", cap)
|
|
184
|
+
return data
|
|
185
|
+
try:
|
|
186
|
+
view = memoryview(data)
|
|
187
|
+
except TypeError:
|
|
188
|
+
raise TypeError(f"input must be bytes-like or str, not {type(data).__name__}") from None
|
|
189
|
+
with view:
|
|
190
|
+
if cap is not None and view.nbytes > cap:
|
|
191
|
+
raise Refusal("too_large", cap)
|
|
192
|
+
return view.tobytes()
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _prefix(data: Input, n: int) -> bytes:
|
|
196
|
+
"""At most the first ``n`` bytes of the input, converting no more than
|
|
197
|
+
that: an NDJSON reader never looks past ``max_bytes + 1`` bytes (a line
|
|
198
|
+
that ends beyond ``max_bytes`` is ``too_large`` whatever follows), so the
|
|
199
|
+
tail of a longer input is neither copied nor encoded."""
|
|
200
|
+
if isinstance(data, str):
|
|
201
|
+
# Each code point is at least one UTF-8 byte: the first n code points
|
|
202
|
+
# cover the first n bytes.
|
|
203
|
+
return data[:n].encode("utf-8")[:n]
|
|
204
|
+
if type(data) is bytes:
|
|
205
|
+
return data if len(data) <= n else data[:n]
|
|
206
|
+
try:
|
|
207
|
+
view = memoryview(data)
|
|
208
|
+
except TypeError:
|
|
209
|
+
raise TypeError(f"input must be bytes-like or str, not {type(data).__name__}") from None
|
|
210
|
+
with view:
|
|
211
|
+
if view.nbytes <= n:
|
|
212
|
+
return view.tobytes()
|
|
213
|
+
out = bytearray()
|
|
214
|
+
_take(view, n, out)
|
|
215
|
+
return bytes(out)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _take(view: memoryview, budget: int, out: bytearray) -> None:
|
|
219
|
+
"""Append the first ``budget`` bytes of ``view`` (C order) to ``out``.
|
|
220
|
+
|
|
221
|
+
Whole leading rows (along the first dimension) or items are copied while
|
|
222
|
+
they fit, so at most ``budget`` bytes; the remainder comes from the next
|
|
223
|
+
row or item. That row or item is cut at the byte level when it is
|
|
224
|
+
C-contiguous and of a native format. Otherwise (a row that is itself
|
|
225
|
+
strided, or an item of a structured format) Python cannot address part of
|
|
226
|
+
it, and that one row or item is copied whole, which can be most of the
|
|
227
|
+
input (a strided view of shape [1, N]). That is the documented contract of
|
|
228
|
+
the NDJSON helpers: the copy is bounded for str (by characters) and for
|
|
229
|
+
C-contiguous buffers (by bytes), and a non-contiguous buffer may be copied
|
|
230
|
+
in full."""
|
|
231
|
+
if budget <= 0 or view.nbytes == 0:
|
|
232
|
+
return
|
|
233
|
+
if view.ndim == 0:
|
|
234
|
+
try:
|
|
235
|
+
with view.cast("B") as flat:
|
|
236
|
+
out += flat[:budget]
|
|
237
|
+
return
|
|
238
|
+
except TypeError:
|
|
239
|
+
out += view.tobytes()[:budget]
|
|
240
|
+
return
|
|
241
|
+
unit = view.nbytes // view.shape[0] # bytes per row (or per item, in 1-D)
|
|
242
|
+
whole = min(budget // unit, view.shape[0])
|
|
243
|
+
if whole:
|
|
244
|
+
with view[:whole] as lead:
|
|
245
|
+
out += lead.tobytes()
|
|
246
|
+
budget -= whole * unit
|
|
247
|
+
if budget <= 0 or whole >= view.shape[0]:
|
|
248
|
+
return
|
|
249
|
+
with view[whole : whole + 1] as part:
|
|
250
|
+
if part.c_contiguous:
|
|
251
|
+
try:
|
|
252
|
+
with part.cast("B") as flat:
|
|
253
|
+
out += flat[:budget]
|
|
254
|
+
return
|
|
255
|
+
except TypeError:
|
|
256
|
+
pass
|
|
257
|
+
out += part.tobytes()[:budget]
|
|
258
|
+
|
|
259
|
+
def _limits(limits: Limits) -> tuple[int, int, int, int]:
|
|
260
|
+
if not isinstance(limits, Limits):
|
|
261
|
+
raise TypeError(f"limits must be canonprims.Limits, not {type(limits).__name__}")
|
|
262
|
+
return limits._args()
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _head(head: Optional[int]) -> Optional[int]:
|
|
266
|
+
if head is None:
|
|
267
|
+
return None
|
|
268
|
+
if type(head) is not int:
|
|
269
|
+
raise TypeError(f"head must be an int or None, got {head!r}")
|
|
270
|
+
if head < 1:
|
|
271
|
+
raise ValueError(f"head must be at least 1, got {head}")
|
|
272
|
+
return head
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _sha256(data: bytes) -> str:
|
|
276
|
+
return "sha256:" + hashlib.sha256(data).hexdigest()
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def canonicalize(data: Input, limits: Limits) -> bytes:
|
|
280
|
+
"""Return the RFC 8785 canonical form of a strict I-JSON text."""
|
|
281
|
+
args = _limits(limits)
|
|
282
|
+
raw = _bytes(data, args[0])
|
|
283
|
+
try:
|
|
284
|
+
return _jcs.canonicalize(raw, *args)
|
|
285
|
+
except _Stop as s:
|
|
286
|
+
raise Refusal(s.code, s.at) from None
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def check(data: Input, limits: Limits) -> None:
|
|
290
|
+
"""Return if the input is already canonical; raise :class:`Refusal` if not.
|
|
291
|
+
|
|
292
|
+
An input in the domain but not byte-identical to its canonical form is
|
|
293
|
+
refused with ``not_canonical`` at the first differing byte.
|
|
294
|
+
"""
|
|
295
|
+
args = _limits(limits)
|
|
296
|
+
raw = _bytes(data, args[0])
|
|
297
|
+
try:
|
|
298
|
+
_compose.check(raw, args)
|
|
299
|
+
except _Stop as s:
|
|
300
|
+
raise Refusal(s.code, s.at) from None
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def digest(data: Input, limits: Limits, alg: str = "sha256") -> str:
|
|
304
|
+
"""Hash the canonical form, written ``<alg>:<lowercase hex>``.
|
|
305
|
+
|
|
306
|
+
The only algorithm is ``sha256``; any other is a ``ValueError`` (not a
|
|
307
|
+
:class:`Refusal`: it is about the call, not the input).
|
|
308
|
+
"""
|
|
309
|
+
args = _limits(limits)
|
|
310
|
+
if not isinstance(alg, str):
|
|
311
|
+
raise TypeError(f"alg must be a str, not {type(alg).__name__}")
|
|
312
|
+
if alg != "sha256":
|
|
313
|
+
raise ValueError(f"unknown_algorithm: {alg!r}")
|
|
314
|
+
raw = _bytes(data, args[0])
|
|
315
|
+
try:
|
|
316
|
+
return _sha256(_jcs.canonicalize(raw, *args))
|
|
317
|
+
except _Stop as s:
|
|
318
|
+
raise Refusal(s.code, s.at) from None
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def scheme_info() -> SchemeInfo:
|
|
322
|
+
"""The scheme, its specification, and the corpus this build was gated on."""
|
|
323
|
+
return SchemeInfo(_SCHEME, "RFC 8785", "canonical-json/v0", _CORPUS_DIGEST)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def vector(data: Input, limits: Limits) -> Vector:
|
|
327
|
+
"""Canonicalize the input and describe the result (refusals as
|
|
328
|
+
:func:`canonicalize`)."""
|
|
329
|
+
return Vector._of(canonicalize(data, limits))
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def vector_of_canonical(data: Input, limits: Limits) -> Vector:
|
|
333
|
+
"""Wrap bytes that must already be canonical (refusals as :func:`check`,
|
|
334
|
+
``not_canonical`` included)."""
|
|
335
|
+
args = _limits(limits)
|
|
336
|
+
raw = _bytes(data, args[0])
|
|
337
|
+
try:
|
|
338
|
+
_compose.check(raw, args)
|
|
339
|
+
except _Stop as s:
|
|
340
|
+
raise Refusal(s.code, s.at) from None
|
|
341
|
+
return Vector._of(raw)
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def ndjson_elements(data: Input, limits: Limits, head: Optional[int] = None) -> list[bytes]:
|
|
345
|
+
"""The canonical bytes of each line of a strict NDJSON prefix.
|
|
346
|
+
|
|
347
|
+
Every line from the start of the input, or exactly the first ``head``
|
|
348
|
+
(at least 1). Each selected line must end with LF (not CR LF) and hold one
|
|
349
|
+
JSON text, canonicalized one level shallower; together they must fit in
|
|
350
|
+
``max_bytes``, and bytes after them are never examined. Framing defects,
|
|
351
|
+
too few lines and empty input are ``invalid_json``; offsets are into the
|
|
352
|
+
input.
|
|
353
|
+
|
|
354
|
+
Only the first ``max_bytes + 1`` bytes are read. For ``bytes``,
|
|
355
|
+
``bytearray``, ``mmap`` and any other C-contiguous buffer, no more than that
|
|
356
|
+
is copied. For a ``str``, at most ``max_bytes + 1`` characters are encoded
|
|
357
|
+
(up to four UTF-8 bytes each) before the cut. A non-contiguous buffer (a
|
|
358
|
+
strided or indirect view) may be copied in full first; pass its bytes
|
|
359
|
+
instead when the input can be large and untrusted.
|
|
360
|
+
"""
|
|
361
|
+
args = _limits(limits)
|
|
362
|
+
raw = _prefix(data, args[0] + 1)
|
|
363
|
+
n = _head(head)
|
|
364
|
+
try:
|
|
365
|
+
return _compose.ndjson_elements(raw, n, args)
|
|
366
|
+
except _Stop as s:
|
|
367
|
+
raise Refusal(s.code, s.at) from None
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def canonicalize_ndjson(data: Input, limits: Limits, head: Optional[int] = None) -> bytes:
|
|
371
|
+
"""A strict NDJSON prefix (see :func:`ndjson_elements`) as one canonical
|
|
372
|
+
array, lines in input order."""
|
|
373
|
+
return _compose.join(ndjson_elements(data, limits, head))
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def sort_canonical_set(data: Input, limits: Limits) -> bytes:
|
|
377
|
+
"""The input, which must be an array, as a canonical set: its elements
|
|
378
|
+
sorted by their canonical bytes (unsigned, byte by byte) with no two equal.
|
|
379
|
+
|
|
380
|
+
A non-array is ``not_an_array``; a repeated element (including elements
|
|
381
|
+
that differ only in member order, escaping or number spelling) is
|
|
382
|
+
``duplicate_set_element``.
|
|
383
|
+
"""
|
|
384
|
+
args = _limits(limits)
|
|
385
|
+
raw = _bytes(data, args[0])
|
|
386
|
+
try:
|
|
387
|
+
return _compose.sort_canonical_set(raw, args)
|
|
388
|
+
except _Stop as s:
|
|
389
|
+
raise Refusal(s.code, s.at) from None
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def check_canonical_set(data: Input, limits: Limits) -> None:
|
|
393
|
+
"""Return if the input is byte-identical to its canonical set; otherwise
|
|
394
|
+
raise the canonical-set refusal, or ``not_canonical`` at the first
|
|
395
|
+
differing byte."""
|
|
396
|
+
args = _limits(limits)
|
|
397
|
+
raw = _bytes(data, args[0])
|
|
398
|
+
try:
|
|
399
|
+
_compose.check_canonical_set(raw, args)
|
|
400
|
+
except _Stop as s:
|
|
401
|
+
raise Refusal(s.code, s.at) from None
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def assemble_canonical_set(elements: Iterable[Input], limits: Limits) -> bytes:
|
|
405
|
+
"""The canonical set of elements that must each already be canonical one
|
|
406
|
+
level shallower (checked in order, with :func:`check`'s refusals).
|
|
407
|
+
|
|
408
|
+
The elements are the input: before each is examined, the array they make
|
|
409
|
+
so far (brackets, elements and commas) must fit in ``max_bytes``.
|
|
410
|
+
"""
|
|
411
|
+
args = _limits(limits)
|
|
412
|
+
# Lazily: each element is converted (bounded by max_bytes) only after the
|
|
413
|
+
# previous one has been checked, so an earlier refusal wins and an
|
|
414
|
+
# unbounded iterable is never drained.
|
|
415
|
+
parts = (_bytes(e, args[0]) for e in elements)
|
|
416
|
+
try:
|
|
417
|
+
return _compose.assemble_canonical_set(parts, args)
|
|
418
|
+
except _Stop as s:
|
|
419
|
+
raise Refusal(s.code, s.at) from None
|
canonprims/_compose.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Composition helpers over canonicalize (docs/spec/jcs-rfc8785.md,
|
|
3
|
+
"Composition helpers"): a port of canon/compose.go. Limits arrive as
|
|
4
|
+
non-negative ints; refusals are Stop with byte offsets."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
from typing import Iterable
|
|
10
|
+
|
|
11
|
+
from ._jcs import Stop, canonicalize
|
|
12
|
+
|
|
13
|
+
# Top-level structure of canonical bytes: a string (every '"' and '\' inside
|
|
14
|
+
# is escaped) or one structural byte. Numbers and literals are skipped.
|
|
15
|
+
_TOKEN = re.compile(rb'"[^"\\]*(?:\\.[^"\\]*)*"|[\[\]{},]', re.S)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _element_limits(limits: tuple[int, int, int, int]) -> tuple[int, int, int, int]:
|
|
19
|
+
"""One level shallower, so the assembled array stays within max_depth."""
|
|
20
|
+
max_bytes, max_depth, max_members, max_string = limits
|
|
21
|
+
if max_depth == 0:
|
|
22
|
+
raise Stop("too_deep", 0, True)
|
|
23
|
+
return (max_bytes, max_depth - 1, max_members, max_string)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def check(raw: bytes, limits: tuple[int, int, int, int]) -> None:
|
|
27
|
+
out = canonicalize(raw, *limits)
|
|
28
|
+
if out != raw:
|
|
29
|
+
raise Stop("not_canonical", first_difference(out, raw), True)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def first_difference(a: bytes, b: bytes) -> int:
|
|
33
|
+
"""The length of the common prefix: a binary search of C-speed
|
|
34
|
+
comparisons, never a Python loop over the bytes."""
|
|
35
|
+
va, vb = memoryview(a), memoryview(b)
|
|
36
|
+
lo, hi = 0, min(len(a), len(b))
|
|
37
|
+
while lo < hi: # a[:lo] == b[:lo]
|
|
38
|
+
mid = (lo + hi + 1) // 2
|
|
39
|
+
if va[:mid] == vb[:mid]:
|
|
40
|
+
lo = mid
|
|
41
|
+
else:
|
|
42
|
+
hi = mid - 1
|
|
43
|
+
return lo
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def ndjson_elements(raw: bytes, head: int | None, limits: tuple[int, int, int, int]) -> list[bytes]:
|
|
47
|
+
elem = _element_limits(limits)
|
|
48
|
+
max_bytes = limits[0]
|
|
49
|
+
out: list[bytes] = []
|
|
50
|
+
pos = 0
|
|
51
|
+
n = len(raw)
|
|
52
|
+
while (head is None or len(out) < head) and pos < n:
|
|
53
|
+
# Look for the LF only where it may lie: a line ending past max_bytes
|
|
54
|
+
# is refused without scanning the rest of the input.
|
|
55
|
+
window = min(n, max_bytes)
|
|
56
|
+
nl = raw.find(b"\n", pos, window) if pos < window else -1
|
|
57
|
+
if nl < 0:
|
|
58
|
+
if n > max_bytes:
|
|
59
|
+
raise Stop("too_large", max_bytes, True)
|
|
60
|
+
raise Stop("invalid_json", n, True) # the final line has no LF
|
|
61
|
+
body = raw[pos:nl]
|
|
62
|
+
if body.endswith(b"\r"):
|
|
63
|
+
raise Stop("invalid_json", nl - 1, True)
|
|
64
|
+
if not body.strip(b" \t\r"):
|
|
65
|
+
raise Stop("invalid_json", pos, True)
|
|
66
|
+
try:
|
|
67
|
+
out.append(canonicalize(body, *elem))
|
|
68
|
+
except Stop as stop:
|
|
69
|
+
raise Stop(stop.code, pos + stop.at, True) from None
|
|
70
|
+
pos = nl + 1
|
|
71
|
+
if not out or (head is not None and len(out) < head):
|
|
72
|
+
raise Stop("invalid_json", pos, True)
|
|
73
|
+
return out
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def join(elements: list[bytes]) -> bytes:
|
|
77
|
+
return b"[" + b",".join(elements) + b"]"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _split_array(c: bytes) -> list[bytes] | None:
|
|
81
|
+
"""The top-level elements of canonical bytes, or None if not an array."""
|
|
82
|
+
if len(c) < 2 or c[0] != 0x5B or c[-1] != 0x5D:
|
|
83
|
+
return None
|
|
84
|
+
if len(c) == 2:
|
|
85
|
+
return []
|
|
86
|
+
out: list[bytes] = []
|
|
87
|
+
depth = 0
|
|
88
|
+
start = 1
|
|
89
|
+
for m in _TOKEN.finditer(c, 1, len(c) - 1):
|
|
90
|
+
t = m.group()
|
|
91
|
+
if len(t) != 1:
|
|
92
|
+
continue # a string
|
|
93
|
+
if t in b"[{":
|
|
94
|
+
depth += 1
|
|
95
|
+
elif t in b"]}":
|
|
96
|
+
depth -= 1
|
|
97
|
+
elif depth == 0: # a top-level comma
|
|
98
|
+
out.append(c[start : m.start()])
|
|
99
|
+
start = m.end()
|
|
100
|
+
out.append(c[start:-1])
|
|
101
|
+
return out
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _sort_set(elements: list[bytes]) -> bytes:
|
|
105
|
+
elements.sort() # unsigned bytewise; a prefix sorts first
|
|
106
|
+
at = 1 # where the repeat would start in the sorted output
|
|
107
|
+
for i in range(1, len(elements)):
|
|
108
|
+
at += len(elements[i - 1]) + 1
|
|
109
|
+
if elements[i - 1] == elements[i]:
|
|
110
|
+
raise Stop("duplicate_set_element", at, True)
|
|
111
|
+
return join(elements)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def sort_canonical_set(raw: bytes, limits: tuple[int, int, int, int]) -> bytes:
|
|
115
|
+
elements = _split_array(canonicalize(raw, *limits))
|
|
116
|
+
if elements is None:
|
|
117
|
+
raise Stop("not_an_array", 0, True)
|
|
118
|
+
return _sort_set(elements)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def check_canonical_set(raw: bytes, limits: tuple[int, int, int, int]) -> None:
|
|
122
|
+
out = sort_canonical_set(raw, limits)
|
|
123
|
+
if out != raw:
|
|
124
|
+
raise Stop("not_canonical", first_difference(out, raw), True)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def assemble_canonical_set(elements: Iterable[bytes], limits: tuple[int, int, int, int]) -> bytes:
|
|
128
|
+
elem = _element_limits(limits)
|
|
129
|
+
max_bytes = limits[0]
|
|
130
|
+
size = 2
|
|
131
|
+
parts: list[bytes] = []
|
|
132
|
+
for e in elements:
|
|
133
|
+
comma = 1 if parts else 0
|
|
134
|
+
if size > max_bytes or len(e) > max_bytes - size - comma:
|
|
135
|
+
raise Stop("too_large", max_bytes, True)
|
|
136
|
+
size += comma + len(e)
|
|
137
|
+
check(e, elem)
|
|
138
|
+
parts.append(e)
|
|
139
|
+
if size > max_bytes:
|
|
140
|
+
raise Stop("too_large", max_bytes, True)
|
|
141
|
+
return _sort_set(parts)
|
canonprims/_jcs.py
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""The jcs/rfc8785 scheme in pure Python (docs/spec/jcs-rfc8785.md).
|
|
3
|
+
|
|
4
|
+
A port of the Go twin (canon/parse.go, canon/number.go). The input is
|
|
5
|
+
decoded as strict UTF-8 in one call, then parsed left to right with an
|
|
6
|
+
explicit container stack (never the call stack) and compiled patterns for
|
|
7
|
+
whitespace, string runs and number tokens. Output is collected as text
|
|
8
|
+
fragments; an object whose members arrive out of order re-emits its member
|
|
9
|
+
fragments in UTF-16 code-unit order when it closes.
|
|
10
|
+
|
|
11
|
+
Positions inside the parser are indices into the decoded text. A refusal
|
|
12
|
+
carries the index; the public layer converts it to a byte offset.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import re
|
|
18
|
+
|
|
19
|
+
DEFAULT_MAX_BYTES = 16 << 20
|
|
20
|
+
DEFAULT_MAX_DEPTH = 128
|
|
21
|
+
DEFAULT_MAX_OBJECT_MEMBERS = 1 << 20
|
|
22
|
+
DEFAULT_MAX_STRING_BYTES = 16 << 20
|
|
23
|
+
|
|
24
|
+
# The largest finite binary64 has 309 decimal digits: any longer integer
|
|
25
|
+
# token is outside binary64, refused before it is converted.
|
|
26
|
+
_MAX_INT_DIGITS = 309
|
|
27
|
+
|
|
28
|
+
_WS = re.compile(r"[ \t\n\r]*")
|
|
29
|
+
# A run of string data that needs no decoding: no quote, backslash or C0
|
|
30
|
+
# control character.
|
|
31
|
+
_RUN = re.compile(r'[^"\\\x00-\x1f]*')
|
|
32
|
+
_HEX4 = re.compile(r"[0-9A-Fa-f]{4}")
|
|
33
|
+
_NUMBER = re.compile(r"-?(?P<int>0|[1-9][0-9]*)(?P<frac>\.[0-9]+)?(?P<exp>[eE][+-]?[0-9]+)?")
|
|
34
|
+
_DIGITS = frozenset("0123456789")
|
|
35
|
+
# U+FDD0..U+FDEF and every code point ending in FFFE or FFFF (RFC 7493 2.1).
|
|
36
|
+
_NONCHAR = re.compile(
|
|
37
|
+
"[\ufdd0-\ufdef" + "".join(chr(plane << 16 | 0xFFFE) + chr(plane << 16 | 0xFFFF) for plane in range(17)) + "]"
|
|
38
|
+
)
|
|
39
|
+
# What ECMAScript JSON.stringify escapes (RFC 8785 3.2.2.2).
|
|
40
|
+
_ESCAPE = re.compile(r'["\\\x00-\x1f]')
|
|
41
|
+
_ESCAPES = {'"': '\\"', "\\": "\\\\", "\b": "\\b", "\t": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r"}
|
|
42
|
+
for _c in range(0x20):
|
|
43
|
+
_ESCAPES.setdefault(chr(_c), f"\\u{_c:04x}")
|
|
44
|
+
del _c
|
|
45
|
+
_SIMPLE = {'"': 0x22, "\\": 0x5C, "/": 0x2F, "b": 0x08, "f": 0x0C, "n": 0x0A, "r": 0x0D, "t": 0x09}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Stop(Exception):
|
|
49
|
+
"""Internal refusal: ``at`` is an index into the decoded text, or a byte
|
|
50
|
+
offset when ``in_bytes`` is set."""
|
|
51
|
+
|
|
52
|
+
def __init__(self, code: str, at: int, in_bytes: bool = False) -> None:
|
|
53
|
+
super().__init__(code, at)
|
|
54
|
+
self.code = code
|
|
55
|
+
self.at = at
|
|
56
|
+
self.in_bytes = in_bytes
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def is_noncharacter(cp: int) -> bool:
|
|
60
|
+
return 0xFDD0 <= cp <= 0xFDEF or cp & 0xFFFE == 0xFFFE
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def quote(text: str) -> str:
|
|
64
|
+
"""Serialize decoded string data as ECMAScript JSON.stringify does."""
|
|
65
|
+
if _ESCAPE.search(text) is None:
|
|
66
|
+
return '"' + text + '"'
|
|
67
|
+
return '"' + _ESCAPE.sub(lambda m: _ESCAPES[m.group()], text) + '"'
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _utf8_len(cp: int) -> int:
|
|
71
|
+
return 1 if cp < 0x80 else 2 if cp < 0x800 else 3 if cp < 0x10000 else 4
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def format_number(f: float) -> str:
|
|
75
|
+
"""A finite binary64 as ECMAScript Number::toString (RFC 8785 3.2.2.3).
|
|
76
|
+
|
|
77
|
+
The digits are the shortest that round-trip (Python's repr), placed by
|
|
78
|
+
the ECMAScript rules, not by repr's own exponent thresholds.
|
|
79
|
+
"""
|
|
80
|
+
if f == 0:
|
|
81
|
+
return "0" # covers -0
|
|
82
|
+
sign = ""
|
|
83
|
+
if f < 0:
|
|
84
|
+
sign = "-"
|
|
85
|
+
f = -f
|
|
86
|
+
r = repr(f)
|
|
87
|
+
exp = 0
|
|
88
|
+
if "e" in r:
|
|
89
|
+
r, e = r.split("e")
|
|
90
|
+
exp = int(e)
|
|
91
|
+
if "." in r:
|
|
92
|
+
whole, frac = r.split(".")
|
|
93
|
+
else:
|
|
94
|
+
whole, frac = r, ""
|
|
95
|
+
digits = whole + frac
|
|
96
|
+
n = len(whole) + exp # value = 0.digits * 10**n
|
|
97
|
+
stripped = digits.lstrip("0")
|
|
98
|
+
n -= len(digits) - len(stripped)
|
|
99
|
+
digits = stripped.rstrip("0")
|
|
100
|
+
k = len(digits)
|
|
101
|
+
if k <= n <= 21:
|
|
102
|
+
return sign + digits + "0" * (n - k)
|
|
103
|
+
if 0 < n <= 21:
|
|
104
|
+
return sign + digits[:n] + "." + digits[n:]
|
|
105
|
+
if -6 < n <= 0:
|
|
106
|
+
return sign + "0." + "0" * -n + digits
|
|
107
|
+
mantissa = digits[0] + ("." + digits[1:] if k > 1 else "")
|
|
108
|
+
return f"{sign}{mantissa}e{'+' if n - 1 >= 0 else ''}{n - 1}"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class _Object:
|
|
112
|
+
__slots__ = ("keys", "spans", "sorted", "seen")
|
|
113
|
+
|
|
114
|
+
def __init__(self) -> None:
|
|
115
|
+
self.keys: list[bytes] = [] # member names as UTF-16BE, input order
|
|
116
|
+
self.spans: list[list[int]] = [] # fragment spans of "name":value
|
|
117
|
+
self.sorted = True # names so far strictly ascending
|
|
118
|
+
self.seen: set[str] = set()
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class _Parser:
|
|
122
|
+
__slots__ = ("s", "n", "pos", "max_depth", "max_members", "max_string", "out", "stack")
|
|
123
|
+
|
|
124
|
+
def __init__(self, s: str, max_depth: int, max_members: int, max_string: int) -> None:
|
|
125
|
+
self.s = s
|
|
126
|
+
self.n = len(s)
|
|
127
|
+
self.pos = 0
|
|
128
|
+
self.max_depth = max_depth
|
|
129
|
+
self.max_members = max_members
|
|
130
|
+
self.max_string = max_string
|
|
131
|
+
self.out: list[str] = []
|
|
132
|
+
# One entry per open container: an _Object, or None for an array.
|
|
133
|
+
self.stack: list[_Object | None] = []
|
|
134
|
+
|
|
135
|
+
def run(self) -> str:
|
|
136
|
+
s, n, out, stack = self.s, self.n, self.out, self.stack
|
|
137
|
+
ws = _WS.match
|
|
138
|
+
self.pos = ws(s, 0).end()
|
|
139
|
+
need_value = True
|
|
140
|
+
while True:
|
|
141
|
+
if need_value:
|
|
142
|
+
pos = self.pos
|
|
143
|
+
if pos >= n:
|
|
144
|
+
raise Stop("invalid_json", pos)
|
|
145
|
+
c = s[pos]
|
|
146
|
+
if c == "{" or c == "[":
|
|
147
|
+
if len(stack) >= self.max_depth:
|
|
148
|
+
raise Stop("too_deep", pos)
|
|
149
|
+
pos = ws(s, pos + 1).end()
|
|
150
|
+
self.pos = pos
|
|
151
|
+
if c == "{":
|
|
152
|
+
if pos < n and s[pos] == "}":
|
|
153
|
+
self.pos = pos + 1
|
|
154
|
+
out.append("{}")
|
|
155
|
+
need_value = False
|
|
156
|
+
continue
|
|
157
|
+
out.append("{")
|
|
158
|
+
obj = _Object()
|
|
159
|
+
stack.append(obj)
|
|
160
|
+
self._member(obj)
|
|
161
|
+
else:
|
|
162
|
+
if pos < n and s[pos] == "]":
|
|
163
|
+
self.pos = pos + 1
|
|
164
|
+
out.append("[]")
|
|
165
|
+
need_value = False
|
|
166
|
+
continue
|
|
167
|
+
stack.append(None)
|
|
168
|
+
out.append("[")
|
|
169
|
+
continue
|
|
170
|
+
if c == '"':
|
|
171
|
+
out.append(quote(self._string()))
|
|
172
|
+
elif c == "t":
|
|
173
|
+
self._literal("true")
|
|
174
|
+
elif c == "f":
|
|
175
|
+
self._literal("false")
|
|
176
|
+
elif c == "n":
|
|
177
|
+
self._literal("null")
|
|
178
|
+
elif c == "-" or c in _DIGITS:
|
|
179
|
+
self._number()
|
|
180
|
+
else:
|
|
181
|
+
raise Stop("invalid_json", pos)
|
|
182
|
+
need_value = False
|
|
183
|
+
continue
|
|
184
|
+
|
|
185
|
+
# A value has just been completed.
|
|
186
|
+
if not stack:
|
|
187
|
+
pos = ws(s, self.pos).end()
|
|
188
|
+
if pos != n:
|
|
189
|
+
raise Stop("invalid_json", pos)
|
|
190
|
+
return "".join(out)
|
|
191
|
+
top = stack[-1]
|
|
192
|
+
if top is not None:
|
|
193
|
+
top.spans[-1][1] = len(out)
|
|
194
|
+
pos = ws(s, self.pos).end()
|
|
195
|
+
self.pos = pos
|
|
196
|
+
if pos >= n:
|
|
197
|
+
raise Stop("invalid_json", pos)
|
|
198
|
+
c = s[pos]
|
|
199
|
+
if c == ",":
|
|
200
|
+
self.pos = ws(s, pos + 1).end()
|
|
201
|
+
if top is not None:
|
|
202
|
+
self._member(top)
|
|
203
|
+
else:
|
|
204
|
+
out.append(",")
|
|
205
|
+
need_value = True
|
|
206
|
+
elif c == "}" and top is not None:
|
|
207
|
+
self.pos = pos + 1
|
|
208
|
+
self._close_object(top)
|
|
209
|
+
elif c == "]" and top is None:
|
|
210
|
+
self.pos = pos + 1
|
|
211
|
+
out.append("]")
|
|
212
|
+
stack.pop()
|
|
213
|
+
else:
|
|
214
|
+
raise Stop("invalid_json", pos)
|
|
215
|
+
|
|
216
|
+
def _member(self, top: _Object) -> None:
|
|
217
|
+
"""One member's name and colon, in the spec's order of steps; leaves
|
|
218
|
+
the parser at the start of the value."""
|
|
219
|
+
s, n, pos = self.s, self.n, self.pos
|
|
220
|
+
if pos >= n or s[pos] != '"':
|
|
221
|
+
raise Stop("invalid_json", pos)
|
|
222
|
+
if len(top.keys) >= self.max_members:
|
|
223
|
+
raise Stop("too_large", pos)
|
|
224
|
+
at = pos
|
|
225
|
+
name = self._string()
|
|
226
|
+
if name in top.seen:
|
|
227
|
+
raise Stop("duplicate_member", at)
|
|
228
|
+
top.seen.add(name)
|
|
229
|
+
pos = _WS.match(s, self.pos).end()
|
|
230
|
+
if pos >= n or s[pos] != ":":
|
|
231
|
+
raise Stop("invalid_json", pos)
|
|
232
|
+
self.pos = _WS.match(s, pos + 1).end()
|
|
233
|
+
key = name.encode("utf-16-be")
|
|
234
|
+
out = self.out
|
|
235
|
+
if top.keys:
|
|
236
|
+
out.append(",")
|
|
237
|
+
if top.sorted and not top.keys[-1] < key:
|
|
238
|
+
top.sorted = False
|
|
239
|
+
start = len(out)
|
|
240
|
+
out.append(quote(name))
|
|
241
|
+
out.append(":")
|
|
242
|
+
top.keys.append(key)
|
|
243
|
+
top.spans.append([start, len(out)])
|
|
244
|
+
|
|
245
|
+
def _close_object(self, top: _Object) -> None:
|
|
246
|
+
"""Finish the innermost object, re-emitting its members in UTF-16
|
|
247
|
+
code-unit order when the input did not have them in order."""
|
|
248
|
+
out = self.out
|
|
249
|
+
if not top.sorted:
|
|
250
|
+
base = top.spans[0][0]
|
|
251
|
+
segment = out[base:]
|
|
252
|
+
keys, spans = top.keys, top.spans
|
|
253
|
+
ordered: list[str] = []
|
|
254
|
+
for i, k in enumerate(sorted(range(len(keys)), key=keys.__getitem__)):
|
|
255
|
+
if i:
|
|
256
|
+
ordered.append(",")
|
|
257
|
+
a, b = spans[k]
|
|
258
|
+
ordered.extend(segment[a - base : b - base])
|
|
259
|
+
# The same number of fragments: enclosing spans stay valid.
|
|
260
|
+
out[base:] = ordered
|
|
261
|
+
out.append("}")
|
|
262
|
+
self.stack.pop()
|
|
263
|
+
|
|
264
|
+
def _literal(self, word: str) -> None:
|
|
265
|
+
if not self.s.startswith(word, self.pos):
|
|
266
|
+
raise Stop("invalid_json", self.pos)
|
|
267
|
+
self.pos += len(word)
|
|
268
|
+
self.out.append(word)
|
|
269
|
+
|
|
270
|
+
def _overflow(self, chunk: str, room: int) -> int:
|
|
271
|
+
"""The index in chunk of the code point whose UTF-8 bytes take the
|
|
272
|
+
running total past room."""
|
|
273
|
+
total = 0
|
|
274
|
+
for i, ch in enumerate(chunk):
|
|
275
|
+
total += _utf8_len(ord(ch))
|
|
276
|
+
if total > room:
|
|
277
|
+
return i
|
|
278
|
+
raise AssertionError("no overflow in chunk")
|
|
279
|
+
|
|
280
|
+
def _string(self) -> str:
|
|
281
|
+
"""Decode the string whose opening quote is at self.pos."""
|
|
282
|
+
s, n, limit = self.s, self.n, self.max_string
|
|
283
|
+
pos = self.pos + 1
|
|
284
|
+
parts: list[str] = []
|
|
285
|
+
size = 0 # decoded UTF-8 bytes so far
|
|
286
|
+
while True:
|
|
287
|
+
end = _RUN.match(s, pos).end()
|
|
288
|
+
if end > pos:
|
|
289
|
+
chunk = s[pos:end]
|
|
290
|
+
bad = _NONCHAR.search(chunk)
|
|
291
|
+
width = end - pos if chunk.isascii() else len(chunk.encode("utf-8"))
|
|
292
|
+
if size + width > limit:
|
|
293
|
+
# Code point by code point: a noncharacter is refused
|
|
294
|
+
# before it is appended, the limit after.
|
|
295
|
+
over = self._overflow(chunk, limit - size)
|
|
296
|
+
if bad is not None and bad.start() <= over:
|
|
297
|
+
raise Stop("noncharacter", pos + bad.start())
|
|
298
|
+
raise Stop("too_large", pos + over)
|
|
299
|
+
if bad is not None:
|
|
300
|
+
raise Stop("noncharacter", pos + bad.start())
|
|
301
|
+
parts.append(chunk)
|
|
302
|
+
size += width
|
|
303
|
+
pos = end
|
|
304
|
+
if pos >= n:
|
|
305
|
+
raise Stop("invalid_json", pos)
|
|
306
|
+
c = s[pos]
|
|
307
|
+
if c == '"':
|
|
308
|
+
self.pos = pos + 1
|
|
309
|
+
return "".join(parts)
|
|
310
|
+
if c != "\\":
|
|
311
|
+
raise Stop("invalid_json", pos) # a C0 control character
|
|
312
|
+
at = pos
|
|
313
|
+
pos += 1
|
|
314
|
+
if pos >= n:
|
|
315
|
+
raise Stop("invalid_json", pos)
|
|
316
|
+
e = s[pos]
|
|
317
|
+
pos += 1
|
|
318
|
+
cp = _SIMPLE.get(e)
|
|
319
|
+
if cp is None:
|
|
320
|
+
if e != "u" or _HEX4.match(s, pos) is None:
|
|
321
|
+
raise Stop("invalid_json", at)
|
|
322
|
+
u = int(s[pos : pos + 4], 16)
|
|
323
|
+
pos += 4
|
|
324
|
+
if 0xDC00 <= u <= 0xDFFF:
|
|
325
|
+
raise Stop("lone_surrogate", at)
|
|
326
|
+
if 0xD800 <= u <= 0xDBFF:
|
|
327
|
+
if s[pos : pos + 2] != "\\u":
|
|
328
|
+
raise Stop("lone_surrogate", at)
|
|
329
|
+
pos += 2
|
|
330
|
+
if _HEX4.match(s, pos) is None:
|
|
331
|
+
raise Stop("invalid_json", pos - 2)
|
|
332
|
+
lo = int(s[pos : pos + 4], 16)
|
|
333
|
+
pos += 4
|
|
334
|
+
if not 0xDC00 <= lo <= 0xDFFF:
|
|
335
|
+
raise Stop("lone_surrogate", at)
|
|
336
|
+
cp = 0x10000 + ((u - 0xD800) << 10) + (lo - 0xDC00)
|
|
337
|
+
else:
|
|
338
|
+
cp = u
|
|
339
|
+
if is_noncharacter(cp):
|
|
340
|
+
raise Stop("noncharacter", at)
|
|
341
|
+
parts.append(chr(cp))
|
|
342
|
+
size += _utf8_len(cp)
|
|
343
|
+
if size > limit:
|
|
344
|
+
raise Stop("too_large", at)
|
|
345
|
+
|
|
346
|
+
def _number(self) -> None:
|
|
347
|
+
"""Scan the longest prefix matching the number grammar, classify it,
|
|
348
|
+
and append its canonical form."""
|
|
349
|
+
s, n, start = self.s, self.n, self.pos
|
|
350
|
+
m = _NUMBER.match(s, start)
|
|
351
|
+
if m is None: # "-" without a digit
|
|
352
|
+
raise Stop("invalid_json", start + 1)
|
|
353
|
+
int_end = m.end("int")
|
|
354
|
+
if m.group("int") == "0" and int_end < n and s[int_end] in _DIGITS:
|
|
355
|
+
raise Stop("invalid_json", int_end) # leading zero
|
|
356
|
+
frac, exp = m.group("frac"), m.group("exp")
|
|
357
|
+
if frac is None and int_end < n and s[int_end] == ".":
|
|
358
|
+
raise Stop("invalid_json", int_end + 1) # "1." or "1.e5"
|
|
359
|
+
frac_end = m.end("frac") if frac is not None else int_end
|
|
360
|
+
if exp is None and frac_end < n and s[frac_end] in "eE":
|
|
361
|
+
raise Stop("invalid_json", frac_end + 1) # "1e" or "1e+"
|
|
362
|
+
token = m.group()
|
|
363
|
+
self.pos = m.end()
|
|
364
|
+
if frac is None and exp is None:
|
|
365
|
+
negative = token[0] == "-"
|
|
366
|
+
digits = int_end - start - negative
|
|
367
|
+
if digits > _MAX_INT_DIGITS:
|
|
368
|
+
raise Stop("integer_outside_binary64", start)
|
|
369
|
+
f = float(token)
|
|
370
|
+
if f in (float("inf"), float("-inf")):
|
|
371
|
+
raise Stop("integer_outside_binary64", start)
|
|
372
|
+
text = format_number(f)
|
|
373
|
+
# Admitted when exact, or already the ES6 spelling of its nearest
|
|
374
|
+
# binary64. Every integer below 10**15 < 2**53 is exact.
|
|
375
|
+
if text != token and digits > 15:
|
|
376
|
+
if not f.is_integer() or int(abs(f)) != int(token[negative:]):
|
|
377
|
+
raise Stop("integer_outside_binary64", start)
|
|
378
|
+
self.out.append(text)
|
|
379
|
+
return
|
|
380
|
+
# float() is correctly rounded (ties to even); underflow gives 0 or a
|
|
381
|
+
# subnormal and is admitted. Only overflow to infinity is refused.
|
|
382
|
+
f = float(token)
|
|
383
|
+
if f in (float("inf"), float("-inf")):
|
|
384
|
+
raise Stop("non_finite_number", start)
|
|
385
|
+
self.out.append(format_number(f))
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _byte_offset(raw: bytes, s: str, at: int) -> int:
|
|
389
|
+
if len(raw) == len(s): # ASCII: indices are byte offsets
|
|
390
|
+
return at
|
|
391
|
+
return len(s[:at].encode("utf-8"))
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def canonicalize(raw: bytes, max_bytes: int, max_depth: int, max_members: int, max_string: int) -> bytes:
|
|
395
|
+
"""Canonical bytes of raw, or Stop with a byte offset. Limits are
|
|
396
|
+
already non-negative."""
|
|
397
|
+
if len(raw) > max_bytes:
|
|
398
|
+
raise Stop("too_large", max_bytes, True)
|
|
399
|
+
try:
|
|
400
|
+
s = raw.decode("utf-8") # strict: overlongs, surrogates, > U+10FFFF
|
|
401
|
+
except UnicodeDecodeError as e:
|
|
402
|
+
raise Stop("invalid_utf8", e.start, True) from None
|
|
403
|
+
try:
|
|
404
|
+
return _Parser(s, max_depth, max_members, max_string).run().encode("utf-8")
|
|
405
|
+
except Stop as stop:
|
|
406
|
+
if not stop.in_bytes:
|
|
407
|
+
stop.at = _byte_offset(raw, s, stop.at)
|
|
408
|
+
stop.in_bytes = True
|
|
409
|
+
raise
|
canonprims/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: canonprims
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Canonical serialization for structured data: RFC 8785 JSON over a strict I-JSON loader
|
|
5
|
+
Keywords: canonicalization,rfc8785,jcs,json
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-Expression: MIT OR Apache-2.0
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
License-File: LICENSE-APACHE
|
|
13
|
+
License-File: LICENSE-MIT
|
|
14
|
+
License-File: NOTICE
|
|
15
|
+
Project-URL: Repository, https://github.com/3leaps/canonprims
|
|
16
|
+
Import-Name: canonprims
|
|
17
|
+
|
|
18
|
+
# canonprims (Python)
|
|
19
|
+
|
|
20
|
+
RFC 8785 JSON canonicalization over a strict I-JSON loader, in pure Python:
|
|
21
|
+
one `py3-none-any` wheel with no dependencies outside the standard library,
|
|
22
|
+
no compiler and no native extension. It is gated by the same
|
|
23
|
+
`canonical-json/v0` conformance corpus as the Rust and Go implementations,
|
|
24
|
+
and compared with them byte for byte on generated input.
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
import canonprims
|
|
28
|
+
|
|
29
|
+
limits = canonprims.Limits() # explicit on every call; documented defaults
|
|
30
|
+
canonprims.canonicalize(b'{"b":1,"a":2}', limits) # b'{"a":2,"b":1}'
|
|
31
|
+
canonprims.digest(b'{"b":1,"a":2}', limits) # 'sha256:...'
|
|
32
|
+
canonprims.check(b'{"a":2,"b":1}', limits) # None, or raises Refusal
|
|
33
|
+
canonprims.scheme_info()
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The composition helpers match the Rust crate and the Go package:
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
canonprims.vector(b'{"b":1}', limits).to_json() # golden test vector
|
|
40
|
+
canonprims.canonicalize_ndjson(b'1\n{"a":2}\n', limits, head=2)
|
|
41
|
+
canonprims.sort_canonical_set(b'[3,1,2]', limits) # b'[1,2,3]'
|
|
42
|
+
canonprims.check_canonical_set(b'[1,2,3]', limits)
|
|
43
|
+
canonprims.assemble_canonical_set([b'2', b'1'], limits)
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Input is the bytes of any buffer exporter (`bytes`, `bytearray`, `memoryview`,
|
|
47
|
+
`array`, `mmap`, ...); a `str` is encoded as UTF-8. Limits follow the spec: a
|
|
48
|
+
negative limit behaves as 0. An input with no canonical form raises
|
|
49
|
+
`canonprims.Refusal` (a `ValueError`) with a normative `code` and an
|
|
50
|
+
informative byte `offset`. Nothing is repaired. Nesting uses an explicit
|
|
51
|
+
stack, not the call stack, so `max_depth` can be raised safely.
|
|
52
|
+
|
|
53
|
+
Requires Python 3.10 or later. With no native code, the one wheel installs
|
|
54
|
+
wherever such a Python runs, on any operating system and architecture. See the
|
|
55
|
+
repository README and `docs/spec/jcs-rfc8785.md` for the scheme.
|
|
56
|
+
|
|
57
|
+
## Performance and native wheels
|
|
58
|
+
|
|
59
|
+
The implementation decodes the whole input in one call and scans it with
|
|
60
|
+
compiled regular expressions, so typical documents (manifests, metadata,
|
|
61
|
+
records) take well under a millisecond, and a 10 MiB input takes from
|
|
62
|
+
under a second (long strings) to a few seconds (densely packed small
|
|
63
|
+
values). Compiled native accelerator wheels (PEP 425 platform wheels
|
|
64
|
+
alongside this `py3-none-any` fallback) remain a possible future option if a
|
|
65
|
+
high-volume workload ever warrants them; the pure package would stay the
|
|
66
|
+
reference and the fallback.
|
|
67
|
+
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
canonprims/__init__.py,sha256=l2oCtfVQTFTN9Pf39aD-YKLWPrJW4uhD8iJXODzjMe0,15049
|
|
2
|
+
canonprims/_compose.py,sha256=yYJKuxL1vZWa_-FBYoW95ZjwDAP1Uzf7JLrczcrw5MQ,4896
|
|
3
|
+
canonprims/_jcs.py,sha256=nb2oCalYIxCMbsEUZjLhHBZRllL4jSabNwokp9983PI,15785
|
|
4
|
+
canonprims/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
canonprims-0.2.0.dist-info/licenses/LICENSE-APACHE,sha256=9KHcABW7eFEcVSZjERgEdzrvpj8XXIT6o-HU1nwxEPs,10277
|
|
6
|
+
canonprims-0.2.0.dist-info/licenses/LICENSE-MIT,sha256=26MoNqtjzk2ZWxUu-xwrD6QYg12m80xYrG_54sY1PPE,1069
|
|
7
|
+
canonprims-0.2.0.dist-info/licenses/NOTICE,sha256=2Zwo7xKnSJUPZ7rFKlMivxmHFC6GN2f2AWrh_pj7Joc,1075
|
|
8
|
+
canonprims-0.2.0.dist-info/WHEEL,sha256=rLJE8OLPBZbz7tqxs1yD-wA-ADa1Ec5PuYU-Y_PNWDI,81
|
|
9
|
+
canonprims-0.2.0.dist-info/METADATA,sha256=JEmzTwvnRLKqzNKUMfaEyyYoFa-E8CTkAwU2A9ME38w,2921
|
|
10
|
+
canonprims-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2026 3 Leaps, LLC
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 3 Leaps, LLC
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
canonprims
|
|
2
|
+
Copyright 2026 3 Leaps, LLC
|
|
3
|
+
|
|
4
|
+
This project is dual-licensed under the MIT License (see LICENSE-MIT) or the
|
|
5
|
+
Apache License, Version 2.0 (see LICENSE-APACHE), at your option.
|
|
6
|
+
|
|
7
|
+
Subject to 3 Leaps OSS policies: https://github.com/3leaps/oss-policies
|
|
8
|
+
|
|
9
|
+
## Project Name Notice
|
|
10
|
+
|
|
11
|
+
"canonprims" is a project name of 3 Leaps, LLC, used to identify this software.
|
|
12
|
+
The name derives from "canonicalization" and has no connection with Canon Inc.
|
|
13
|
+
or its marks.
|
|
14
|
+
"3 Leaps®" is a registered trademark of 3 Leaps, LLC, a North Carolina LLC.
|
|
15
|
+
|
|
16
|
+
While code and documentation are open under the MIT or Apache-2.0 License,
|
|
17
|
+
usage of the "canonprims" project name is reserved for official implementations
|
|
18
|
+
to prevent confusion and benefit the ecosystem. Use of this name in derivative
|
|
19
|
+
works does not imply endorsement by 3 Leaps, LLC.
|
|
20
|
+
|
|
21
|
+
For the benefit of the community, please rename your project folder and
|
|
22
|
+
configurations to avoid using "3leaps" or "canonprims" in derivative works that
|
|
23
|
+
are not official 3 Leaps projects.
|
|
24
|
+
|
|
25
|
+
For questions regarding project name usage, contact hello@3leaps.net.
|