bjdata 0.6.5__tar.gz → 0.6.7__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.
- {bjdata-0.6.5 → bjdata-0.6.7}/PKG-INFO +2 -2
- {bjdata-0.6.5 → bjdata-0.6.7}/README.md +1 -1
- {bjdata-0.6.5 → bjdata-0.6.7}/bjdata/__init__.py +3 -2
- {bjdata-0.6.5 → bjdata-0.6.7}/bjdata/decoder.py +180 -64
- {bjdata-0.6.5 → bjdata-0.6.7}/bjdata/encoder.py +82 -19
- {bjdata-0.6.5 → bjdata-0.6.7}/bjdata/markers.py +1 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/bjdata.egg-info/PKG-INFO +2 -2
- {bjdata-0.6.5 → bjdata-0.6.7}/bjdata.egg-info/SOURCES.txt +0 -1
- bjdata-0.6.7/pyproject.toml +3 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/setup.py +2 -2
- {bjdata-0.6.5 → bjdata-0.6.7}/src/_bjdata.c +70 -8
- {bjdata-0.6.5 → bjdata-0.6.7}/src/decoder.c +502 -43
- {bjdata-0.6.5 → bjdata-0.6.7}/src/decoder.h +4 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/src/encoder.c +297 -14
- {bjdata-0.6.5 → bjdata-0.6.7}/src/markers.h +1 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/src/numpyapi.h +42 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/test/test.py +102 -1
- bjdata-0.6.5/pyproject.toml +0 -8
- bjdata-0.6.5/src/numpy_compat.h +0 -56
- {bjdata-0.6.5 → bjdata-0.6.7}/Binary_JData_Specification.md +0 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/CHANGELOG +0 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/LICENSE +0 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/MANIFEST.in +0 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/NOTICE +0 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/UBJSON-Specification.md +0 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/bjdata/__main__.py +0 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/bjdata/compat.py +0 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/bjdata.egg-info/dependency_links.txt +0 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/bjdata.egg-info/not-zip-safe +0 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/bjdata.egg-info/requires.txt +0 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/bjdata.egg-info/top_level.txt +0 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/ez_setup.py +0 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/setup.cfg +0 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/src/common.h +0 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/src/encoder.h +0 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/src/python_funcs.c +0 -0
- {bjdata-0.6.5 → bjdata-0.6.7}/src/python_funcs.h +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: bjdata
|
|
3
|
-
Version: 0.6.
|
|
3
|
+
Version: 0.6.7
|
|
4
4
|
Summary: Binary JData and UBJSON encoder/decoder
|
|
5
5
|
Home-page: https://github.com/NeuroJSON/pybj
|
|
6
6
|
Author: Qianqian Fang
|
|
@@ -58,7 +58,7 @@ Dynamic: summary
|
|
|
58
58
|
- Copyright: (C) Qianqian Fang (2020-2026) <q.fang at neu.edu>
|
|
59
59
|
- Copyright: (C) Iotic Labs Ltd. (2016-2019) <vilnis.termanis at iotic-labs.com>
|
|
60
60
|
- License: Apache License, Version 2.0
|
|
61
|
-
- Version: 0.6.
|
|
61
|
+
- Version: 0.6.7
|
|
62
62
|
- URL: https://pypi.org/project/bjdata/
|
|
63
63
|
- Github: https://github.com/NeuroJSON/pybj
|
|
64
64
|
- BJData Spec Version: [Draft 4](https://neurojson.org/bjdata/draft4)
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
- Copyright: (C) Qianqian Fang (2020-2026) <q.fang at neu.edu>
|
|
6
6
|
- Copyright: (C) Iotic Labs Ltd. (2016-2019) <vilnis.termanis at iotic-labs.com>
|
|
7
7
|
- License: Apache License, Version 2.0
|
|
8
|
-
- Version: 0.6.
|
|
8
|
+
- Version: 0.6.7
|
|
9
9
|
- URL: https://pypi.org/project/bjdata/
|
|
10
10
|
- Github: https://github.com/NeuroJSON/pybj
|
|
11
11
|
- BJData Spec Version: [Draft 4](https://neurojson.org/bjdata/draft4)
|
|
@@ -38,15 +38,16 @@ except ImportError: # pragma: no cover
|
|
|
38
38
|
EXTENSION_ENABLED = False
|
|
39
39
|
|
|
40
40
|
from .encoder import EncoderException
|
|
41
|
-
from .decoder import DecoderException
|
|
41
|
+
from .decoder import DecoderException, Extension
|
|
42
42
|
|
|
43
|
-
__version__ = "0.6.
|
|
43
|
+
__version__ = "0.6.7"
|
|
44
44
|
|
|
45
45
|
__all__ = (
|
|
46
46
|
"EXTENSION_ENABLED",
|
|
47
47
|
"dump",
|
|
48
48
|
"dumpb",
|
|
49
49
|
"EncoderException",
|
|
50
|
+
"Extension",
|
|
50
51
|
"load",
|
|
51
52
|
"loadb",
|
|
52
53
|
"DecoderException",
|
|
@@ -20,6 +20,7 @@ from io import BytesIO
|
|
|
20
20
|
from struct import Struct, pack, error as StructError
|
|
21
21
|
from decimal import Decimal, DecimalException
|
|
22
22
|
from functools import reduce
|
|
23
|
+
from collections import namedtuple
|
|
23
24
|
|
|
24
25
|
from .compat import raise_from, intern_unicode
|
|
25
26
|
from .markers import (
|
|
@@ -43,6 +44,7 @@ from .markers import (
|
|
|
43
44
|
TYPE_UINT64,
|
|
44
45
|
TYPE_FLOAT16,
|
|
45
46
|
TYPE_STRING,
|
|
47
|
+
TYPE_EXTENSION,
|
|
46
48
|
OBJECT_START,
|
|
47
49
|
OBJECT_END,
|
|
48
50
|
ARRAY_START,
|
|
@@ -130,7 +132,7 @@ __UNPACK_INT64 = [Struct(">q").unpack, Struct("<q").unpack]
|
|
|
130
132
|
__UNPACK_UINT16 = [Struct(">H").unpack, Struct("<H").unpack]
|
|
131
133
|
__UNPACK_UINT32 = [Struct(">I").unpack, Struct("<I").unpack]
|
|
132
134
|
__UNPACK_UINT64 = [Struct(">Q").unpack, Struct("<Q").unpack]
|
|
133
|
-
__UNPACK_FLOAT16 = [Struct(">
|
|
135
|
+
__UNPACK_FLOAT16 = [Struct(">e").unpack, Struct("<e").unpack]
|
|
134
136
|
__UNPACK_FLOAT32 = [Struct(">f").unpack, Struct("<f").unpack]
|
|
135
137
|
__UNPACK_FLOAT64 = [Struct(">d").unpack, Struct("<d").unpack]
|
|
136
138
|
|
|
@@ -185,6 +187,13 @@ __NUMPY_DTYPE_MAP = {
|
|
|
185
187
|
}
|
|
186
188
|
|
|
187
189
|
|
|
190
|
+
class Extension(namedtuple("Extension", ["type", "data"])):
|
|
191
|
+
"""A BJData extension value, [E][type-id][byte-length][payload]: type is the integer type id
|
|
192
|
+
(0-255 reserved by the specification), data the payload bytes. Encoded back as written."""
|
|
193
|
+
|
|
194
|
+
__slots__ = ()
|
|
195
|
+
|
|
196
|
+
|
|
188
197
|
class DecoderException(ValueError):
|
|
189
198
|
"""Raised when decoding of a UBJSON stream fails."""
|
|
190
199
|
|
|
@@ -371,6 +380,26 @@ __METHOD_MAP = {
|
|
|
371
380
|
}
|
|
372
381
|
|
|
373
382
|
|
|
383
|
+
def __decode_extension(fp_read, marker, le=1):
|
|
384
|
+
typeid = __decode_int_non_negative(fp_read, fp_read(1), le)
|
|
385
|
+
length = __decode_int_non_negative(fp_read, fp_read(1), le)
|
|
386
|
+
data = fp_read(length)
|
|
387
|
+
if len(data) < length:
|
|
388
|
+
raise DecoderException("Extension payload too short")
|
|
389
|
+
return Extension(typeid, data)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
__METHOD_MAP[TYPE_EXTENSION] = __decode_extension
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def __remaining(fp_read):
|
|
396
|
+
"""Bytes left in an in-memory input (loadb), else None (a stream does not say)"""
|
|
397
|
+
src = getattr(fp_read, "__self__", None)
|
|
398
|
+
if isinstance(src, BytesIO):
|
|
399
|
+
return len(src.getbuffer()) - src.tell()
|
|
400
|
+
return None
|
|
401
|
+
|
|
402
|
+
|
|
374
403
|
def prodlist(mylist):
|
|
375
404
|
result = 1
|
|
376
405
|
for x in mylist:
|
|
@@ -489,31 +518,58 @@ def __decode_array_or_string_schema(fp_read, field_name, le):
|
|
|
489
518
|
}
|
|
490
519
|
else:
|
|
491
520
|
raise DecoderException("Unsupported array schema type")
|
|
492
|
-
elif next_marker in __TYPES_FIXLEN or next_marker in (
|
|
493
|
-
|
|
494
|
-
TYPE_BOOL_FALSE,
|
|
495
|
-
):
|
|
496
|
-
elem_marker = next_marker
|
|
497
|
-
elem_count = 1
|
|
498
|
-
m = fp_read(1)
|
|
499
|
-
while m != ARRAY_END:
|
|
500
|
-
if m != elem_marker:
|
|
501
|
-
raise DecoderException("Mixed types in fixed array not supported")
|
|
502
|
-
elem_count += 1
|
|
503
|
-
m = fp_read(1)
|
|
521
|
+
elif next_marker in __TYPES_FIXLEN or next_marker in (TYPE_BOOL_TRUE, TYPE_BOOL_FALSE, ARRAY_START):
|
|
522
|
+
elem_marker, shape = __decode_soa_subarray(fp_read, next_marker)
|
|
504
523
|
is_bool = elem_marker in (TYPE_BOOL_TRUE, TYPE_BOOL_FALSE)
|
|
524
|
+
elem_count = prodlist(shape)
|
|
505
525
|
return {
|
|
506
526
|
"name": field_name,
|
|
507
527
|
"type": "array",
|
|
508
528
|
"marker": elem_marker,
|
|
509
529
|
"count": elem_count,
|
|
530
|
+
"shape": tuple(shape),
|
|
510
531
|
"elem_type": "bool" if is_bool else "numeric",
|
|
532
|
+
"elem_bytes": 1 if is_bool else __DTYPELEN_MAP[elem_marker],
|
|
511
533
|
"bytes": elem_count * (1 if is_bool else __DTYPELEN_MAP[elem_marker]),
|
|
512
534
|
}
|
|
513
535
|
else:
|
|
514
536
|
raise DecoderException("Unsupported array schema type")
|
|
515
537
|
|
|
516
538
|
|
|
539
|
+
def __soa_same_elem(a, b):
|
|
540
|
+
bools = (TYPE_BOOL_TRUE, TYPE_BOOL_FALSE)
|
|
541
|
+
return (b in bools) if a in bools else a == b
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def __decode_soa_subarray(fp_read, first):
|
|
545
|
+
"""An array field of a schema, its [ and first marker read: one element type in a
|
|
546
|
+
rectangular shape, nested to any depth ([TTT], [[TTT][TTT]], ...); returns (marker, shape).
|
|
547
|
+
Ragged or mixed-type array fields have no numpy sub-array dtype and are refused."""
|
|
548
|
+
ragged = "Ragged or mixed-type array fields in an SOA schema are not supported"
|
|
549
|
+
if first == ARRAY_START:
|
|
550
|
+
marker, inner, n, m = None, None, 0, first
|
|
551
|
+
while m != ARRAY_END:
|
|
552
|
+
if m != ARRAY_START:
|
|
553
|
+
raise DecoderException(ragged)
|
|
554
|
+
et, sh = __decode_soa_subarray(fp_read, fp_read(1))
|
|
555
|
+
if n == 0:
|
|
556
|
+
marker, inner = et, sh
|
|
557
|
+
elif sh != inner or not __soa_same_elem(marker, et):
|
|
558
|
+
raise DecoderException(ragged)
|
|
559
|
+
n += 1
|
|
560
|
+
m = fp_read(1)
|
|
561
|
+
return marker, [n] + inner
|
|
562
|
+
if first not in __TYPES_FIXLEN and first not in (TYPE_BOOL_TRUE, TYPE_BOOL_FALSE):
|
|
563
|
+
raise DecoderException("Unsupported sub-array element type")
|
|
564
|
+
n, m = 0, first
|
|
565
|
+
while m != ARRAY_END:
|
|
566
|
+
if m == ARRAY_START or not __soa_same_elem(first, m):
|
|
567
|
+
raise DecoderException(ragged)
|
|
568
|
+
n += 1
|
|
569
|
+
m = fp_read(1)
|
|
570
|
+
return first, [n]
|
|
571
|
+
|
|
572
|
+
|
|
517
573
|
def __decode_soa_field_value(field, raw, record_index, le):
|
|
518
574
|
"""Decode a single field value from raw bytes."""
|
|
519
575
|
ftype = field["type"]
|
|
@@ -525,11 +581,12 @@ def __decode_soa_field_value(field, raw, record_index, le):
|
|
|
525
581
|
elif ftype == "null":
|
|
526
582
|
return None
|
|
527
583
|
elif ftype == "array":
|
|
584
|
+
shape = field.get("shape", (field["count"],))
|
|
528
585
|
if field["elem_type"] == "bool":
|
|
529
586
|
return ndarray(
|
|
530
587
|
[raw[i : i + 1] == TYPE_BOOL_TRUE for i in range(field["count"])]
|
|
531
|
-
)
|
|
532
|
-
return buffer2numpy(raw, dtype=npdtype(__NUMPY_DTYPE_MAP[field["marker"]]))
|
|
588
|
+
).reshape(shape)
|
|
589
|
+
return buffer2numpy(raw, dtype=npdtype(__NUMPY_DTYPE_MAP[field["marker"]])).reshape(shape)
|
|
533
590
|
elif ftype == "nested":
|
|
534
591
|
result = {}
|
|
535
592
|
offset = 0
|
|
@@ -572,7 +629,7 @@ def __schema_to_dtype(schema):
|
|
|
572
629
|
dtype_list.append((fname, "O"))
|
|
573
630
|
elif ftype == "array":
|
|
574
631
|
dt = "?" if f["elem_type"] == "bool" else __NUMPY_DTYPE_MAP[f["marker"]]
|
|
575
|
-
dtype_list.append((fname, dt, (f["count"],)))
|
|
632
|
+
dtype_list.append((fname, dt, f.get("shape", (f["count"],))))
|
|
576
633
|
elif ftype == "nested":
|
|
577
634
|
dtype_list.append((fname, __schema_to_dtype(f["schema"])))
|
|
578
635
|
elif ftype == "string" and f["encoding"] == "fixed":
|
|
@@ -599,6 +656,20 @@ def __decode_soa(fp_read, schema, is_row_major, intern_object_keys, le):
|
|
|
599
656
|
payload = fp_read(record_bytes * count)
|
|
600
657
|
__read_offset_tables(fp_read, schema, count, le)
|
|
601
658
|
|
|
659
|
+
if not is_row_major and any(f["type"] in ("nested", "array") for f in schema):
|
|
660
|
+
# column-major: every leaf placeholder (a field of a nested object, an element of an
|
|
661
|
+
# array field) takes count values in turn, in schema order; as records (each one its
|
|
662
|
+
# leaves in that same order)
|
|
663
|
+
leaves = list(__soa_leaf_sizes(schema))
|
|
664
|
+
cols, at = [], 0
|
|
665
|
+
for nbytes in leaves:
|
|
666
|
+
cols.append(memoryview(payload)[at : at + nbytes * count])
|
|
667
|
+
at += nbytes * count
|
|
668
|
+
payload = b"".join(
|
|
669
|
+
b"".join(bytes(c[i * n : (i + 1) * n]) for c, n in zip(cols, leaves)) for i in range(count)
|
|
670
|
+
)
|
|
671
|
+
is_row_major = True
|
|
672
|
+
|
|
602
673
|
# Convert variable strings through dict intermediate, then to numpy
|
|
603
674
|
if __has_variable_strings(schema):
|
|
604
675
|
records = __decode_soa_to_dicts(
|
|
@@ -613,6 +684,20 @@ def __decode_soa(fp_read, schema, is_row_major, intern_object_keys, le):
|
|
|
613
684
|
return result
|
|
614
685
|
|
|
615
686
|
|
|
687
|
+
def __soa_leaf_sizes(schema):
|
|
688
|
+
"""The byte sizes of the leaf placeholders of a SoA schema in the order they appear (nested
|
|
689
|
+
objects descended into, each element of an array field a leaf of its own)"""
|
|
690
|
+
for f in schema:
|
|
691
|
+
if f["type"] == "nested":
|
|
692
|
+
for g in __soa_leaf_sizes(f["schema"]):
|
|
693
|
+
yield g
|
|
694
|
+
elif f["type"] == "array":
|
|
695
|
+
for _ in range(f["count"]):
|
|
696
|
+
yield f["elem_bytes"]
|
|
697
|
+
else:
|
|
698
|
+
yield f["bytes"]
|
|
699
|
+
|
|
700
|
+
|
|
616
701
|
def __read_offset_tables(fp_read, schema, count, le):
|
|
617
702
|
"""Recursively read offset tables for offset-based string fields."""
|
|
618
703
|
for f in schema:
|
|
@@ -740,7 +825,7 @@ def __schema_to_dtype_with_strings(schema, records):
|
|
|
740
825
|
dtype_list.append((fname, "O"))
|
|
741
826
|
elif ftype == "array":
|
|
742
827
|
dt = "?" if f["elem_type"] == "bool" else __NUMPY_DTYPE_MAP[f["marker"]]
|
|
743
|
-
dtype_list.append((fname, dt, (f["count"],)))
|
|
828
|
+
dtype_list.append((fname, dt, f.get("shape", (f["count"],))))
|
|
744
829
|
elif ftype == "nested":
|
|
745
830
|
nested_records = [r.get(fname, {}) for r in records]
|
|
746
831
|
nested_dt = __schema_to_dtype_with_strings(f["schema"], nested_records)
|
|
@@ -794,6 +879,7 @@ def __get_container_params(
|
|
|
794
879
|
):
|
|
795
880
|
marker = fp_read(1)
|
|
796
881
|
dims = []
|
|
882
|
+
colmajor = False
|
|
797
883
|
if marker == CONTAINER_TYPE:
|
|
798
884
|
marker = fp_read(1)
|
|
799
885
|
|
|
@@ -801,7 +887,7 @@ def __get_container_params(
|
|
|
801
887
|
if marker == OBJECT_START:
|
|
802
888
|
# This is SOA format - decode schema
|
|
803
889
|
schema = __decode_soa_schema(fp_read, intern_object_keys, islittle)
|
|
804
|
-
return marker, True, -1, schema, [], True # -1 count signals SOA
|
|
890
|
+
return marker, True, -1, schema, [], True, False # -1 count signals SOA
|
|
805
891
|
|
|
806
892
|
if marker not in __TYPES:
|
|
807
893
|
raise DecoderException("Invalid container type")
|
|
@@ -821,6 +907,14 @@ def __get_container_params(
|
|
|
821
907
|
intern_object_keys,
|
|
822
908
|
islittle,
|
|
823
909
|
)
|
|
910
|
+
# [[...]]: the dimensions of a column-major array
|
|
911
|
+
colmajor = len(dims) == 1 and (
|
|
912
|
+
isinstance(dims[0], (list, tuple)) or hasattr(dims[0], "ndim")
|
|
913
|
+
)
|
|
914
|
+
if colmajor:
|
|
915
|
+
dims = [int(x) for x in list(dims[0])]
|
|
916
|
+
else:
|
|
917
|
+
dims = [int(x) for x in list(dims)]
|
|
824
918
|
count = prodlist(dims)
|
|
825
919
|
else:
|
|
826
920
|
count = __decode_int_non_negative(fp_read, marker, islittle)
|
|
@@ -844,7 +938,7 @@ def __get_container_params(
|
|
|
844
938
|
counting = False
|
|
845
939
|
else:
|
|
846
940
|
raise DecoderException("Container type without count")
|
|
847
|
-
return marker, counting, count, type_, dims, False
|
|
941
|
+
return marker, counting, count, type_, dims, False, colmajor
|
|
848
942
|
|
|
849
943
|
|
|
850
944
|
def __decode_object(
|
|
@@ -868,11 +962,11 @@ def __decode_object(
|
|
|
868
962
|
)
|
|
869
963
|
|
|
870
964
|
# Check if this is SOA format
|
|
871
|
-
if
|
|
965
|
+
if result[5]: # is_soa flag
|
|
872
966
|
schema = result[3]
|
|
873
967
|
return __decode_soa(fp_read, schema, False, intern_object_keys, islittle)
|
|
874
968
|
|
|
875
|
-
marker, counting, count, type_, dims, _ = result
|
|
969
|
+
marker, counting, count, type_, dims, _, _ = result
|
|
876
970
|
has_pairs_hook = object_pairs_hook is not None
|
|
877
971
|
obj = [] if has_pairs_hook else {}
|
|
878
972
|
|
|
@@ -907,6 +1001,9 @@ def __decode_object(
|
|
|
907
1001
|
# decode key for object
|
|
908
1002
|
key = __decode_object_key(fp_read, marker, intern_object_keys, le)
|
|
909
1003
|
marker = fp_read(1) if type_ == TYPE_NONE else type_
|
|
1004
|
+
# a no-op may take the place of a key, never of the value after one (spec, No-Op)
|
|
1005
|
+
if marker == TYPE_NOOP and type_ == TYPE_NONE:
|
|
1006
|
+
raise DecoderException("A no-op between an object key and its value")
|
|
910
1007
|
|
|
911
1008
|
# decode value
|
|
912
1009
|
try:
|
|
@@ -974,14 +1071,19 @@ def __decode_array(
|
|
|
974
1071
|
)
|
|
975
1072
|
|
|
976
1073
|
# Check if this is SOA format (row-major)
|
|
977
|
-
if
|
|
1074
|
+
if result[5]: # is_soa flag
|
|
978
1075
|
schema = result[3]
|
|
979
1076
|
return __decode_soa(fp_read, schema, True, intern_object_keys, islittle)
|
|
980
1077
|
|
|
981
|
-
marker, counting, count, type_, dims, _ = result
|
|
1078
|
+
marker, counting, count, type_, dims, _, colmajor = result
|
|
982
1079
|
|
|
983
|
-
# special case - no data (None or bool)
|
|
1080
|
+
# special case - no data (None or bool): the items take no input, so a few bytes could ask
|
|
1081
|
+
# for any amount of memory. Up to 2^20 of them, or 64 per byte left, are allowed (2^24 from
|
|
1082
|
+
# a stream)
|
|
984
1083
|
if type_ in __TYPES_NO_DATA:
|
|
1084
|
+
left = __remaining(fp_read)
|
|
1085
|
+
if count > (1 << 24) if left is None else (count > (1 << 20) and count // 64 > left):
|
|
1086
|
+
raise DecoderException("Container count exceeds the remaining input")
|
|
985
1087
|
return [__METHOD_MAP[type_](fp_read, type_, islittle)] * count
|
|
986
1088
|
|
|
987
1089
|
# special case - bytes array
|
|
@@ -995,6 +1097,10 @@ def __decode_array(
|
|
|
995
1097
|
raise DecoderException("Container bytes array too short")
|
|
996
1098
|
return container
|
|
997
1099
|
|
|
1100
|
+
if type_ in __TYPES_FIXLEN and count == 0 and len(dims) > 0:
|
|
1101
|
+
# an empty N-D typed array: its type and shape kept
|
|
1102
|
+
return npzeros(dims, dtype=npdtype(__DTYPE_MAP[type_]))
|
|
1103
|
+
|
|
998
1104
|
if type_ in __TYPES_FIXLEN and count > 0:
|
|
999
1105
|
if hasattr(count, "dtype"):
|
|
1000
1106
|
container = fp_read(count.item() * __DTYPELEN_MAP[type_])
|
|
@@ -1006,7 +1112,11 @@ def __decode_array(
|
|
|
1006
1112
|
# container=typedarray(__DTYPE_MAP[type_], container)
|
|
1007
1113
|
if len(dims) > 0:
|
|
1008
1114
|
container = buffer2numpy(container, dtype=npdtype(__DTYPE_MAP[type_]))
|
|
1009
|
-
|
|
1115
|
+
if colmajor:
|
|
1116
|
+
# the payload is the row-major array of the reversed dimensions
|
|
1117
|
+
container = container.reshape(dims[::-1]).T
|
|
1118
|
+
else:
|
|
1119
|
+
container = container.reshape(dims)
|
|
1010
1120
|
else:
|
|
1011
1121
|
container = buffer2numpy(container, dtype=npdtype(__DTYPE_MAP[type_]))
|
|
1012
1122
|
return container
|
|
@@ -1080,6 +1190,7 @@ def load(
|
|
|
1080
1190
|
object_pairs_hook=None,
|
|
1081
1191
|
intern_object_keys=False,
|
|
1082
1192
|
islittle=True,
|
|
1193
|
+
allroots=False,
|
|
1083
1194
|
):
|
|
1084
1195
|
"""Decodes and returns BJData/UBJSON from the given file-like object
|
|
1085
1196
|
|
|
@@ -1107,6 +1218,11 @@ def load(
|
|
|
1107
1218
|
BJData Draft 4), change to 0 to use big-endian
|
|
1108
1219
|
(for UBJSON & BJData Draft 1)
|
|
1109
1220
|
|
|
1221
|
+
allroots (bool): If set, every root of the input is decoded and a list of them
|
|
1222
|
+
returned (a BJData file may hold several, as concatenated JSON
|
|
1223
|
+
does; a JSON-Mmap file holds its table first). By default only the
|
|
1224
|
+
first value is decoded, and a stream is left at the next one.
|
|
1225
|
+
|
|
1110
1226
|
Returns:
|
|
1111
1227
|
Decoded object
|
|
1112
1228
|
|
|
@@ -1156,54 +1272,52 @@ def load(
|
|
|
1156
1272
|
|
|
1157
1273
|
newobj = []
|
|
1158
1274
|
|
|
1275
|
+
# the first value of the input (a stream is left at the next one); with allroots, every
|
|
1276
|
+
# root of it as a list (a file may hold several, as concatenated JSON does, and a JSON-Mmap
|
|
1277
|
+
# file holds its table first). No-op markers before and between them are skipped
|
|
1159
1278
|
while True:
|
|
1160
1279
|
marker = fp_read(1)
|
|
1161
1280
|
if len(marker) == 0:
|
|
1162
1281
|
break
|
|
1282
|
+
if marker == TYPE_NOOP:
|
|
1283
|
+
continue
|
|
1163
1284
|
try:
|
|
1164
|
-
try:
|
|
1165
|
-
return __METHOD_MAP[marker](fp_read, marker, islittle)
|
|
1166
|
-
except KeyError:
|
|
1167
|
-
pass
|
|
1168
1285
|
if marker == ARRAY_START:
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
islittle,
|
|
1178
|
-
)
|
|
1286
|
+
value = __decode_array(
|
|
1287
|
+
fp_read,
|
|
1288
|
+
bool(no_bytes),
|
|
1289
|
+
bool(uint8_bytes),
|
|
1290
|
+
object_hook,
|
|
1291
|
+
object_pairs_hook,
|
|
1292
|
+
intern_object_keys,
|
|
1293
|
+
islittle,
|
|
1179
1294
|
)
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
islittle,
|
|
1190
|
-
)
|
|
1295
|
+
elif marker == OBJECT_START:
|
|
1296
|
+
value = __decode_object(
|
|
1297
|
+
fp_read,
|
|
1298
|
+
bool(no_bytes),
|
|
1299
|
+
bool(uint8_bytes),
|
|
1300
|
+
object_hook,
|
|
1301
|
+
object_pairs_hook,
|
|
1302
|
+
intern_object_keys,
|
|
1303
|
+
islittle,
|
|
1191
1304
|
)
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
if len(newobj) > 0:
|
|
1195
|
-
pass
|
|
1305
|
+
elif marker in __METHOD_MAP:
|
|
1306
|
+
value = __METHOD_MAP[marker](fp_read, marker, islittle)
|
|
1196
1307
|
else:
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
)
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1308
|
+
raise DecoderException("Invalid marker")
|
|
1309
|
+
except DecoderException as ex:
|
|
1310
|
+
raise_from(
|
|
1311
|
+
DecoderException(
|
|
1312
|
+
ex.args[0],
|
|
1313
|
+
position=(fp.tell() if hasattr(fp, "tell") else None),
|
|
1314
|
+
),
|
|
1315
|
+
ex,
|
|
1316
|
+
)
|
|
1317
|
+
newobj.append(value)
|
|
1318
|
+
if not allroots:
|
|
1319
|
+
return value
|
|
1320
|
+
if len(newobj) == 0:
|
|
1207
1321
|
raise DecoderException("Empty data")
|
|
1208
1322
|
|
|
1209
1323
|
return newobj
|
|
@@ -1217,6 +1331,7 @@ def loadb(
|
|
|
1217
1331
|
object_pairs_hook=None,
|
|
1218
1332
|
intern_object_keys=False,
|
|
1219
1333
|
islittle=True,
|
|
1334
|
+
allroots=False,
|
|
1220
1335
|
):
|
|
1221
1336
|
"""Decodes and returns BJData/UBJSON from the given bytes or bytesarray object. See
|
|
1222
1337
|
load() for available arguments."""
|
|
@@ -1229,4 +1344,5 @@ def loadb(
|
|
|
1229
1344
|
object_pairs_hook=object_pairs_hook,
|
|
1230
1345
|
intern_object_keys=intern_object_keys,
|
|
1231
1346
|
islittle=islittle,
|
|
1347
|
+
allroots=allroots,
|
|
1232
1348
|
)
|
|
@@ -49,6 +49,7 @@ from .markers import (
|
|
|
49
49
|
TYPE_HIGH_PREC,
|
|
50
50
|
TYPE_CHAR,
|
|
51
51
|
TYPE_STRING,
|
|
52
|
+
TYPE_EXTENSION,
|
|
52
53
|
OBJECT_START,
|
|
53
54
|
OBJECT_END,
|
|
54
55
|
ARRAY_START,
|
|
@@ -88,7 +89,7 @@ __DTYPE_TO_MARKER = {
|
|
|
88
89
|
"f2": TYPE_FLOAT16,
|
|
89
90
|
"f4": TYPE_FLOAT32,
|
|
90
91
|
"f8": TYPE_FLOAT64,
|
|
91
|
-
"b1":
|
|
92
|
+
"b1": TYPE_UINT8,
|
|
92
93
|
"S1": TYPE_CHAR,
|
|
93
94
|
}
|
|
94
95
|
|
|
@@ -116,6 +117,9 @@ __BYTES_ARRAY_PREFIX_DRAFT2 = (
|
|
|
116
117
|
)
|
|
117
118
|
|
|
118
119
|
|
|
120
|
+
from .decoder import Extension # noqa: E402 (shared with the decoder)
|
|
121
|
+
|
|
122
|
+
|
|
119
123
|
class EncoderException(TypeError):
|
|
120
124
|
"""Raised when encoding of an object fails."""
|
|
121
125
|
|
|
@@ -336,10 +340,7 @@ def __encode_soa_schema_field(fp_write, field_name, field_info, le):
|
|
|
336
340
|
elif ftype == "null":
|
|
337
341
|
fp_write(TYPE_NULL)
|
|
338
342
|
elif ftype == "array":
|
|
339
|
-
fp_write(
|
|
340
|
-
for _ in range(field_info["count"]):
|
|
341
|
-
fp_write(field_info["marker"])
|
|
342
|
-
fp_write(ARRAY_END)
|
|
343
|
+
fp_write(__soa_array_schema(field_info["marker"], field_info["shape"]))
|
|
343
344
|
elif ftype == "nested":
|
|
344
345
|
fp_write(OBJECT_START)
|
|
345
346
|
for f in field_info["schema"]:
|
|
@@ -377,7 +378,10 @@ def __write_soa_field_value(fp_write, field, index, le):
|
|
|
377
378
|
elif ftype == "null":
|
|
378
379
|
pass
|
|
379
380
|
elif ftype == "array":
|
|
380
|
-
|
|
381
|
+
if field.get("bool"):
|
|
382
|
+
fp_write(b"".join(TYPE_BOOL_TRUE if v else TYPE_BOOL_FALSE for v in values[index].ravel()))
|
|
383
|
+
else:
|
|
384
|
+
fp_write(values[index].tobytes())
|
|
381
385
|
elif ftype == "nested":
|
|
382
386
|
for f in field["schema"]:
|
|
383
387
|
__write_soa_field_value(fp_write, f, index, le)
|
|
@@ -442,10 +446,16 @@ def __build_field_schema(field_dtype, values, count, soa_threshold=None):
|
|
|
442
446
|
if field_dtype.subdtype:
|
|
443
447
|
base, shape = field_dtype.subdtype
|
|
444
448
|
dstr = base.str[1:] if base.str[0] in "<>|" else base.str
|
|
449
|
+
is_bool = dstr in ("?", "b1")
|
|
450
|
+
count_el = 1
|
|
451
|
+
for d in shape:
|
|
452
|
+
count_el *= d
|
|
445
453
|
return {
|
|
446
454
|
"type": "array",
|
|
447
|
-
"marker": __get_numpy_dtype_marker(dstr),
|
|
448
|
-
"
|
|
455
|
+
"marker": TYPE_BOOL_TRUE if is_bool else __get_numpy_dtype_marker(dstr),
|
|
456
|
+
"bool": is_bool,
|
|
457
|
+
"count": count_el,
|
|
458
|
+
"shape": tuple(shape),
|
|
449
459
|
"values": values,
|
|
450
460
|
}
|
|
451
461
|
|
|
@@ -489,6 +499,28 @@ def __collect_offset_fields(schema):
|
|
|
489
499
|
return result
|
|
490
500
|
|
|
491
501
|
|
|
502
|
+
def __soa_array_schema(marker, shape):
|
|
503
|
+
"""An array field's schema: [TTT], nested per dimension ([[TTT][TTT]] for 2x3)"""
|
|
504
|
+
if len(shape) <= 1:
|
|
505
|
+
return ARRAY_START + marker * (shape[0] if shape else 1) + ARRAY_END
|
|
506
|
+
return ARRAY_START + __soa_array_schema(marker, shape[1:]) * shape[0] + ARRAY_END
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def __soa_leaves(schema):
|
|
510
|
+
"""The leaf placeholders of a SoA schema in the order they appear: (field, element) pairs,
|
|
511
|
+
nested objects descended into and each element of an array field a leaf of its own
|
|
512
|
+
(element None for any other field)"""
|
|
513
|
+
for f in schema:
|
|
514
|
+
if f["type"] == "nested":
|
|
515
|
+
for g in __soa_leaves(f["schema"]):
|
|
516
|
+
yield g
|
|
517
|
+
elif f["type"] == "array":
|
|
518
|
+
for k in range(f["count"]):
|
|
519
|
+
yield f, k
|
|
520
|
+
else:
|
|
521
|
+
yield f, None
|
|
522
|
+
|
|
523
|
+
|
|
492
524
|
def __encode_soa(fp_write, item, soa_format, le, soa_threshold=None):
|
|
493
525
|
"""Encode numpy structured array or list of dicts as SOA format."""
|
|
494
526
|
import numpy as np
|
|
@@ -531,9 +563,18 @@ def __encode_soa(fp_write, item, soa_format, le, soa_threshold=None):
|
|
|
531
563
|
for f in schema:
|
|
532
564
|
__write_soa_field_value(fp_write, f, i, le)
|
|
533
565
|
else:
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
566
|
+
# column-major: every leaf placeholder (a field of a nested object, an element of an
|
|
567
|
+
# array field) takes count values in turn, in schema order
|
|
568
|
+
for f, k in __soa_leaves(schema):
|
|
569
|
+
if k is None:
|
|
570
|
+
for i in range(count):
|
|
571
|
+
__write_soa_field_value(fp_write, f, i, le)
|
|
572
|
+
else:
|
|
573
|
+
col = np.asarray(f["values"]).reshape(count, -1)[:, k]
|
|
574
|
+
if f.get("bool"):
|
|
575
|
+
fp_write(b"".join(TYPE_BOOL_TRUE if v else TYPE_BOOL_FALSE for v in col))
|
|
576
|
+
else:
|
|
577
|
+
fp_write(np.ascontiguousarray(col).tobytes())
|
|
537
578
|
|
|
538
579
|
for f in __collect_offset_fields(schema):
|
|
539
580
|
encoded = [v.encode("utf-8") for v in f["values"]]
|
|
@@ -567,7 +608,10 @@ def __write_soa_field_value(fp_write, field, index, le):
|
|
|
567
608
|
elif ftype == "null":
|
|
568
609
|
pass
|
|
569
610
|
elif ftype == "array":
|
|
570
|
-
|
|
611
|
+
if field.get("bool"):
|
|
612
|
+
fp_write(b"".join(TYPE_BOOL_TRUE if v else TYPE_BOOL_FALSE for v in values[index].ravel()))
|
|
613
|
+
else:
|
|
614
|
+
fp_write(values[index].tobytes())
|
|
571
615
|
elif ftype == "nested":
|
|
572
616
|
for f in field["schema"]:
|
|
573
617
|
__write_soa_field_value(fp_write, f, index, le)
|
|
@@ -628,6 +672,13 @@ def __encode_value(
|
|
|
628
672
|
if isinstance(item, UNICODE_TYPE):
|
|
629
673
|
__encode_string(fp_write, item, le)
|
|
630
674
|
|
|
675
|
+
elif isinstance(item, Extension):
|
|
676
|
+
# [E][type-id][byte-length][payload]
|
|
677
|
+
fp_write(TYPE_EXTENSION)
|
|
678
|
+
__encode_int(fp_write, int(item.type), le)
|
|
679
|
+
__encode_int(fp_write, len(item.data), le)
|
|
680
|
+
fp_write(bytes(item.data))
|
|
681
|
+
|
|
631
682
|
elif item is None:
|
|
632
683
|
fp_write(TYPE_NULL)
|
|
633
684
|
|
|
@@ -831,10 +882,20 @@ def __encode_numpy(fp_write, item, uint8_bytes, islittle, default):
|
|
|
831
882
|
except ImportError:
|
|
832
883
|
raise Exception("bjdata", "you must install 'numpy' to encode this data")
|
|
833
884
|
|
|
834
|
-
|
|
885
|
+
if np.iscomplexobj(item):
|
|
886
|
+
# BJData has no complex numbers; JData annotates them
|
|
887
|
+
raise EncoderException(
|
|
888
|
+
"complex arrays have no BJData form; encode them as JData annotations "
|
|
889
|
+
"first (e.g. jdata.encode)"
|
|
890
|
+
)
|
|
891
|
+
|
|
892
|
+
# numbers in the output's byte order (BJData: little-endian)
|
|
893
|
+
order = "<" if islittle else ">"
|
|
835
894
|
if np.isscalar(item):
|
|
895
|
+
if item.dtype.kind in "biuf":
|
|
896
|
+
item = np.asarray(item, dtype=item.dtype.newbyteorder(order))
|
|
836
897
|
fp_write(__map_dtype(item.dtype.str))
|
|
837
|
-
fp_write(item.
|
|
898
|
+
fp_write(item.tobytes())
|
|
838
899
|
return
|
|
839
900
|
|
|
840
901
|
if not (type(item).__name__ == "ndarray" or type(item).__name__ == "chararray"):
|
|
@@ -852,10 +913,12 @@ def __encode_numpy(fp_write, item, uint8_bytes, islittle, default):
|
|
|
852
913
|
fp_write(item.data)
|
|
853
914
|
return
|
|
854
915
|
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
916
|
+
# the payload is written as stored: row-major, contiguous and in the output's byte order
|
|
917
|
+
# (Fortran-ordered arrays, strided views and other-endian arrays included)
|
|
918
|
+
if item.dtype.kind in "biufU":
|
|
919
|
+
item = np.ascontiguousarray(item, dtype=item.dtype.newbyteorder(order))
|
|
920
|
+
else:
|
|
921
|
+
item = np.ascontiguousarray(item)
|
|
859
922
|
|
|
860
923
|
fp_write(
|
|
861
924
|
ARRAY_START + CONTAINER_TYPE + __map_dtype(item.dtype.str) + CONTAINER_COUNT
|
|
@@ -865,7 +928,7 @@ def __encode_numpy(fp_write, item, uint8_bytes, islittle, default):
|
|
|
865
928
|
__encode_int(fp_write, value, islittle)
|
|
866
929
|
fp_write(ARRAY_END)
|
|
867
930
|
|
|
868
|
-
fp_write(item.
|
|
931
|
+
fp_write(item.tobytes())
|
|
869
932
|
|
|
870
933
|
|
|
871
934
|
def dump(
|