bjdata 0.5.4__tar.gz → 0.6.5__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.
Files changed (41) hide show
  1. {bjdata-0.5.4 → bjdata-0.6.5}/PKG-INFO +7 -6
  2. {bjdata-0.5.4 → bjdata-0.6.5}/README.md +6 -5
  3. {bjdata-0.5.4 → bjdata-0.6.5}/bjdata/__init__.py +2 -2
  4. {bjdata-0.5.4 → bjdata-0.6.5}/bjdata/decoder.py +456 -7
  5. bjdata-0.6.5/bjdata/encoder.py +1030 -0
  6. {bjdata-0.5.4 → bjdata-0.6.5}/bjdata.egg-info/PKG-INFO +7 -6
  7. {bjdata-0.5.4 → bjdata-0.6.5}/bjdata.egg-info/SOURCES.txt +1 -0
  8. {bjdata-0.5.4 → bjdata-0.6.5}/ez_setup.py +144 -112
  9. {bjdata-0.5.4 → bjdata-0.6.5}/setup.py +2 -2
  10. {bjdata-0.5.4 → bjdata-0.6.5}/src/_bjdata.c +72 -11
  11. bjdata-0.6.5/src/common.h +48 -0
  12. {bjdata-0.5.4 → bjdata-0.6.5}/src/decoder.c +951 -227
  13. bjdata-0.6.5/src/decoder.h +147 -0
  14. {bjdata-0.5.4 → bjdata-0.6.5}/src/encoder.c +888 -6
  15. bjdata-0.6.5/src/encoder.h +128 -0
  16. bjdata-0.6.5/src/numpy_compat.h +56 -0
  17. bjdata-0.6.5/test/test.py +3159 -0
  18. bjdata-0.5.4/bjdata/encoder.py +0 -554
  19. bjdata-0.5.4/src/common.h +0 -48
  20. bjdata-0.5.4/src/decoder.h +0 -70
  21. bjdata-0.5.4/src/encoder.h +0 -62
  22. bjdata-0.5.4/test/test.py +0 -1250
  23. {bjdata-0.5.4 → bjdata-0.6.5}/Binary_JData_Specification.md +0 -0
  24. {bjdata-0.5.4 → bjdata-0.6.5}/CHANGELOG +0 -0
  25. {bjdata-0.5.4 → bjdata-0.6.5}/LICENSE +0 -0
  26. {bjdata-0.5.4 → bjdata-0.6.5}/MANIFEST.in +0 -0
  27. {bjdata-0.5.4 → bjdata-0.6.5}/NOTICE +0 -0
  28. {bjdata-0.5.4 → bjdata-0.6.5}/UBJSON-Specification.md +0 -0
  29. {bjdata-0.5.4 → bjdata-0.6.5}/bjdata/__main__.py +0 -0
  30. {bjdata-0.5.4 → bjdata-0.6.5}/bjdata/compat.py +0 -0
  31. {bjdata-0.5.4 → bjdata-0.6.5}/bjdata/markers.py +0 -0
  32. {bjdata-0.5.4 → bjdata-0.6.5}/bjdata.egg-info/dependency_links.txt +0 -0
  33. {bjdata-0.5.4 → bjdata-0.6.5}/bjdata.egg-info/not-zip-safe +0 -0
  34. {bjdata-0.5.4 → bjdata-0.6.5}/bjdata.egg-info/requires.txt +0 -0
  35. {bjdata-0.5.4 → bjdata-0.6.5}/bjdata.egg-info/top_level.txt +0 -0
  36. {bjdata-0.5.4 → bjdata-0.6.5}/pyproject.toml +0 -0
  37. {bjdata-0.5.4 → bjdata-0.6.5}/setup.cfg +0 -0
  38. {bjdata-0.5.4 → bjdata-0.6.5}/src/markers.h +0 -0
  39. {bjdata-0.5.4 → bjdata-0.6.5}/src/numpyapi.h +0 -0
  40. {bjdata-0.5.4 → bjdata-0.6.5}/src/python_funcs.c +0 -0
  41. {bjdata-0.5.4 → bjdata-0.6.5}/src/python_funcs.h +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bjdata
3
- Version: 0.5.4
3
+ Version: 0.6.5
4
4
  Summary: Binary JData and UBJSON encoder/decoder
5
5
  Home-page: https://github.com/NeuroJSON/pybj
6
6
  Author: Qianqian Fang
@@ -55,19 +55,19 @@ Dynamic: summary
55
55
 
56
56
  # Binary JData for Python - a lightweight binary JSON format
57
57
 
58
- - Copyright: (C) Qianqian Fang (2020-2025) <q.fang at neu.edu>
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.5.4
61
+ - Version: 0.6.5
62
62
  - URL: https://pypi.org/project/bjdata/
63
63
  - Github: https://github.com/NeuroJSON/pybj
64
- - BJData Spec Version: [V1 Draft 3](https://neurojson.org/bjdata/draft3)
64
+ - BJData Spec Version: [Draft 4](https://neurojson.org/bjdata/draft4)
65
65
  - Acknowledgement: This project is supported by US National Institute of Health (NIH) grant U24-NS124027
66
66
 
67
67
  ![Build Status](https://github.com/NeuroJSON/pybj/actions/workflows/run_test.yml/badge.svg)
68
68
 
69
69
  This is a Python v3.2+ (and 2.7+) [Binary JData](https://neurojson.org) encoder
70
- and decoder based on the [Draft-3](Binary_JData_Specification.md) specification.
70
+ and decoder based on the [Draft-4](Binary_JData_Specification.md) specification.
71
71
 
72
72
  ## Installing / packaging
73
73
  ```shell
@@ -190,7 +190,7 @@ This package was modified based on the py-ubjson package developed by
190
190
  Project URL: https://github.com/Iotic-Labs/py-ubjson
191
191
 
192
192
  The major changes were focused on supporting the Binary JData Specification
193
- [Draft 3](https://neurojson.org/bjdata/draft3) -
193
+ [Draft 4](https://neurojson.org/bjdata/draft4) -
194
194
  an extended Universal Binary JSON (UBJSON) Specification Draft-12 by adding
195
195
  the below new features:
196
196
 
@@ -200,3 +200,4 @@ the below new features:
200
200
  * BJData does not convert NaN/Inf/-Inf to `null`
201
201
  * BJData uses little-Endian as the default integer/floating-point numbers while UBJSON uses big-Endian
202
202
  * BJData only permits non-zero-fixed-length data types (`UiuImlMLhdDCB`) in strongly-typed array/object containers
203
+ * BJData Draft-4 adds new optimized container Stucture-of-Arrays (SoA) for packed objects.
@@ -2,19 +2,19 @@
2
2
 
3
3
  # Binary JData for Python - a lightweight binary JSON format
4
4
 
5
- - Copyright: (C) Qianqian Fang (2020-2025) <q.fang at neu.edu>
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.5.4
8
+ - Version: 0.6.5
9
9
  - URL: https://pypi.org/project/bjdata/
10
10
  - Github: https://github.com/NeuroJSON/pybj
11
- - BJData Spec Version: [V1 Draft 3](https://neurojson.org/bjdata/draft3)
11
+ - BJData Spec Version: [Draft 4](https://neurojson.org/bjdata/draft4)
12
12
  - Acknowledgement: This project is supported by US National Institute of Health (NIH) grant U24-NS124027
13
13
 
14
14
  ![Build Status](https://github.com/NeuroJSON/pybj/actions/workflows/run_test.yml/badge.svg)
15
15
 
16
16
  This is a Python v3.2+ (and 2.7+) [Binary JData](https://neurojson.org) encoder
17
- and decoder based on the [Draft-3](Binary_JData_Specification.md) specification.
17
+ and decoder based on the [Draft-4](Binary_JData_Specification.md) specification.
18
18
 
19
19
  ## Installing / packaging
20
20
  ```shell
@@ -137,7 +137,7 @@ This package was modified based on the py-ubjson package developed by
137
137
  Project URL: https://github.com/Iotic-Labs/py-ubjson
138
138
 
139
139
  The major changes were focused on supporting the Binary JData Specification
140
- [Draft 3](https://neurojson.org/bjdata/draft3) -
140
+ [Draft 4](https://neurojson.org/bjdata/draft4) -
141
141
  an extended Universal Binary JSON (UBJSON) Specification Draft-12 by adding
142
142
  the below new features:
143
143
 
@@ -147,3 +147,4 @@ the below new features:
147
147
  * BJData does not convert NaN/Inf/-Inf to `null`
148
148
  * BJData uses little-Endian as the default integer/floating-point numbers while UBJSON uses big-Endian
149
149
  * BJData only permits non-zero-fixed-length data types (`UiuImlMLhdDCB`) in strongly-typed array/object containers
150
+ * BJData Draft-4 adds new optimized container Stucture-of-Arrays (SoA) for packed objects.
@@ -14,7 +14,7 @@
14
14
  # limitations under the License.
15
15
 
16
16
 
17
- """BJData (Draft 3) and UBJSON (Draft 12) implementation
17
+ """BJData (Draft 4) and UBJSON (Draft 12) implementation
18
18
 
19
19
  Example usage:
20
20
 
@@ -40,7 +40,7 @@ except ImportError: # pragma: no cover
40
40
  from .encoder import EncoderException
41
41
  from .decoder import DecoderException
42
42
 
43
- __version__ = "0.5.4"
43
+ __version__ = "0.6.5"
44
44
 
45
45
  __all__ = (
46
46
  "EXTENSION_ENABLED",
@@ -14,7 +14,7 @@
14
14
  # limitations under the License.
15
15
 
16
16
 
17
- """BJData (Draft 2) and UBJSON encoder"""
17
+ """BJData (Draft 4) and UBJSON decoder with SOA support"""
18
18
 
19
19
  from io import BytesIO
20
20
  from struct import Struct, pack, error as StructError
@@ -55,6 +55,8 @@ from numpy import (
55
55
  dtype as npdtype,
56
56
  frombuffer as buffer2numpy,
57
57
  half as halfprec,
58
+ zeros as npzeros,
59
+ empty as npempty,
58
60
  )
59
61
  from array import array as typedarray
60
62
 
@@ -164,6 +166,24 @@ __DTYPELEN_MAP = {
164
166
  TYPE_CHAR: 1,
165
167
  }
166
168
 
169
+ # Numpy dtype strings for SOA
170
+ __NUMPY_DTYPE_MAP = {
171
+ TYPE_BYTE: "u1",
172
+ TYPE_INT8: "i1",
173
+ TYPE_UINT8: "u1",
174
+ TYPE_INT16: "i2",
175
+ TYPE_UINT16: "u2",
176
+ TYPE_INT32: "i4",
177
+ TYPE_UINT32: "u4",
178
+ TYPE_INT64: "i8",
179
+ TYPE_UINT64: "u8",
180
+ TYPE_FLOAT16: "f2",
181
+ TYPE_FLOAT32: "f4",
182
+ TYPE_FLOAT64: "f8",
183
+ TYPE_BOOL_TRUE: "?",
184
+ TYPE_BOOL_FALSE: "?",
185
+ }
186
+
167
187
 
168
188
  class DecoderException(ValueError):
169
189
  """Raised when decoding of a UBJSON stream fails."""
@@ -358,6 +378,410 @@ def prodlist(mylist):
358
378
  return result
359
379
 
360
380
 
381
+ def __decode_soa_schema(fp_read, intern_object_keys, le):
382
+ """Decode SOA schema: {field1:type1, field2:type2, ...}
383
+
384
+ Supports:
385
+ - Fixed-length numeric types
386
+ - Boolean (T marker)
387
+ - Null (Z marker)
388
+ - Fixed-length string: S<int><length>
389
+ - Dictionary-based string: [$S#<n><str1><str2>...
390
+ - Offset-table-based string: [$<int-type>]
391
+ - Fixed-size array: [<type><type>...] (repeated markers)
392
+ """
393
+ schema = []
394
+ marker = fp_read(1)
395
+
396
+ while marker != OBJECT_END:
397
+ if marker == TYPE_NOOP:
398
+ marker = fp_read(1)
399
+ continue
400
+
401
+ field_name = __decode_object_key(fp_read, marker, intern_object_keys, le)
402
+ type_marker = fp_read(1)
403
+
404
+ if type_marker in __TYPES_FIXLEN:
405
+ schema.append(
406
+ {
407
+ "name": field_name,
408
+ "type": "numeric",
409
+ "marker": type_marker,
410
+ "bytes": __DTYPELEN_MAP[type_marker],
411
+ }
412
+ )
413
+ elif type_marker in (TYPE_BOOL_TRUE, TYPE_BOOL_FALSE):
414
+ schema.append(
415
+ {"name": field_name, "type": "bool", "marker": type_marker, "bytes": 1}
416
+ )
417
+ elif type_marker == TYPE_NULL:
418
+ schema.append({"name": field_name, "type": "null", "bytes": 0})
419
+ elif type_marker == TYPE_STRING:
420
+ length_marker = fp_read(1)
421
+ if length_marker not in __TYPES_INT:
422
+ raise DecoderException("SOA schema only supports fixed-length types")
423
+ length = __decode_int_non_negative(fp_read, length_marker, le)
424
+ schema.append(
425
+ {
426
+ "name": field_name,
427
+ "type": "string",
428
+ "encoding": "fixed",
429
+ "bytes": length,
430
+ }
431
+ )
432
+ elif type_marker == OBJECT_START:
433
+ nested = __decode_soa_schema(fp_read, intern_object_keys, le)
434
+ schema.append(
435
+ {
436
+ "name": field_name,
437
+ "type": "nested",
438
+ "schema": nested,
439
+ "bytes": sum(f["bytes"] for f in nested),
440
+ }
441
+ )
442
+ elif type_marker == ARRAY_START:
443
+ schema.append(__decode_array_or_string_schema(fp_read, field_name, le))
444
+ else:
445
+ raise DecoderException("Unsupported SOA schema type")
446
+
447
+ marker = fp_read(1)
448
+
449
+ return schema
450
+
451
+
452
+ def __decode_array_or_string_schema(fp_read, field_name, le):
453
+ """Decode array schema: fixed array [TTT], dict [$S#...], or offset [$U]."""
454
+ next_marker = fp_read(1)
455
+
456
+ if next_marker == CONTAINER_TYPE:
457
+ inner = fp_read(1)
458
+ if inner == TYPE_STRING:
459
+ if fp_read(1) != CONTAINER_COUNT:
460
+ raise DecoderException("Expected # in dict-string schema")
461
+ dict_count = __decode_int_non_negative(fp_read, fp_read(1), le)
462
+ dictionary = []
463
+ for _ in range(dict_count):
464
+ str_len = __decode_int_non_negative(fp_read, fp_read(1), le)
465
+ dictionary.append(fp_read(str_len).decode("utf-8"))
466
+ idx_bytes = 1 if dict_count <= 255 else (2 if dict_count <= 65535 else 4)
467
+ idx_marker = (
468
+ TYPE_UINT8
469
+ if idx_bytes == 1
470
+ else (TYPE_UINT16 if idx_bytes == 2 else TYPE_UINT32)
471
+ )
472
+ return {
473
+ "name": field_name,
474
+ "type": "string",
475
+ "encoding": "dict",
476
+ "bytes": idx_bytes,
477
+ "dict": dictionary,
478
+ "index_marker": idx_marker,
479
+ }
480
+ elif inner in __TYPES_INT:
481
+ if fp_read(1) != ARRAY_END:
482
+ raise DecoderException("Expected ] in offset-string schema")
483
+ return {
484
+ "name": field_name,
485
+ "type": "string",
486
+ "encoding": "offset",
487
+ "bytes": __DTYPELEN_MAP[inner],
488
+ "index_marker": inner,
489
+ }
490
+ else:
491
+ raise DecoderException("Unsupported array schema type")
492
+ elif next_marker in __TYPES_FIXLEN or next_marker in (
493
+ TYPE_BOOL_TRUE,
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)
504
+ is_bool = elem_marker in (TYPE_BOOL_TRUE, TYPE_BOOL_FALSE)
505
+ return {
506
+ "name": field_name,
507
+ "type": "array",
508
+ "marker": elem_marker,
509
+ "count": elem_count,
510
+ "elem_type": "bool" if is_bool else "numeric",
511
+ "bytes": elem_count * (1 if is_bool else __DTYPELEN_MAP[elem_marker]),
512
+ }
513
+ else:
514
+ raise DecoderException("Unsupported array schema type")
515
+
516
+
517
+ def __decode_soa_field_value(field, raw, record_index, le):
518
+ """Decode a single field value from raw bytes."""
519
+ ftype = field["type"]
520
+
521
+ if ftype == "numeric":
522
+ return buffer2numpy(raw, dtype=npdtype(__NUMPY_DTYPE_MAP[field["marker"]]))[0]
523
+ elif ftype == "bool":
524
+ return raw[0:1] == TYPE_BOOL_TRUE
525
+ elif ftype == "null":
526
+ return None
527
+ elif ftype == "array":
528
+ if field["elem_type"] == "bool":
529
+ return ndarray(
530
+ [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"]]))
533
+ elif ftype == "nested":
534
+ result = {}
535
+ offset = 0
536
+ for f in field["schema"]:
537
+ result[f["name"]] = __decode_soa_field_value(
538
+ f, raw[offset : offset + f["bytes"]], record_index, le
539
+ )
540
+ offset += f["bytes"]
541
+ return result
542
+ elif ftype == "string":
543
+ enc = field["encoding"]
544
+ if enc == "fixed":
545
+ return raw.rstrip(b"\x00").decode("utf-8")
546
+ elif enc == "dict":
547
+ idx = buffer2numpy(
548
+ raw, dtype=npdtype(__NUMPY_DTYPE_MAP[field["index_marker"]])
549
+ )[0].item()
550
+ return field["dict"][idx]
551
+ elif enc == "offset":
552
+ idx = buffer2numpy(
553
+ raw, dtype=npdtype(__NUMPY_DTYPE_MAP[field["index_marker"]])
554
+ )[0].item()
555
+ return field["string_buffer"][
556
+ field["offsets"][idx] : field["offsets"][idx + 1]
557
+ ]
558
+ return None
559
+
560
+
561
+ def __schema_to_dtype(schema):
562
+ """Build numpy dtype from SOA schema."""
563
+ dtype_list = []
564
+ for f in schema:
565
+ fname = f["name"]
566
+ ftype = f["type"]
567
+ if ftype == "numeric":
568
+ dtype_list.append((fname, __NUMPY_DTYPE_MAP[f["marker"]]))
569
+ elif ftype == "bool":
570
+ dtype_list.append((fname, "?"))
571
+ elif ftype == "null":
572
+ dtype_list.append((fname, "O"))
573
+ elif ftype == "array":
574
+ dt = "?" if f["elem_type"] == "bool" else __NUMPY_DTYPE_MAP[f["marker"]]
575
+ dtype_list.append((fname, dt, (f["count"],)))
576
+ elif ftype == "nested":
577
+ dtype_list.append((fname, __schema_to_dtype(f["schema"])))
578
+ elif ftype == "string" and f["encoding"] == "fixed":
579
+ dtype_list.append((fname, "U" + str(f["bytes"])))
580
+ return npdtype(dtype_list)
581
+
582
+
583
+ def __decode_soa(fp_read, schema, is_row_major, intern_object_keys, le):
584
+ """Decode SOA payload into numpy structured array."""
585
+ if fp_read(1) != CONTAINER_COUNT:
586
+ raise DecoderException("Expected # after SOA schema")
587
+ marker = fp_read(1)
588
+ if marker == ARRAY_START:
589
+ dims = []
590
+ m = fp_read(1)
591
+ while m != ARRAY_END:
592
+ dims.append(__METHOD_MAP[m](fp_read, m, le))
593
+ m = fp_read(1)
594
+ count = prodlist(dims)
595
+ else:
596
+ count = __decode_int_non_negative(fp_read, marker, le)
597
+ dims = [count]
598
+ record_bytes = sum(f["bytes"] for f in schema)
599
+ payload = fp_read(record_bytes * count)
600
+ __read_offset_tables(fp_read, schema, count, le)
601
+
602
+ # Convert variable strings through dict intermediate, then to numpy
603
+ if __has_variable_strings(schema):
604
+ records = __decode_soa_to_dicts(
605
+ payload, schema, count, record_bytes, is_row_major, le
606
+ )
607
+ return __dicts_to_numpy(records, schema, dims)
608
+
609
+ result = npempty(count, dtype=__schema_to_dtype(schema))
610
+ __fill_numpy_result(result, payload, schema, count, record_bytes, is_row_major, le)
611
+ if len(dims) > 1:
612
+ result = result.reshape(dims)
613
+ return result
614
+
615
+
616
+ def __read_offset_tables(fp_read, schema, count, le):
617
+ """Recursively read offset tables for offset-based string fields."""
618
+ for f in schema:
619
+ if f.get("encoding") == "offset":
620
+ f["offsets"] = []
621
+ for _ in range(count + 1):
622
+ f["offsets"].append(
623
+ __METHOD_MAP[f["index_marker"]](fp_read, f["index_marker"], le)
624
+ )
625
+ buf_len = f["offsets"][-1] if f["offsets"] else 0
626
+ f["string_buffer"] = fp_read(buf_len).decode("utf-8") if buf_len else ""
627
+ elif f.get("type") == "nested":
628
+ __read_offset_tables(fp_read, f["schema"], count, le)
629
+
630
+
631
+ def __has_variable_strings(schema):
632
+ """Check if schema has dict/offset strings."""
633
+ for f in schema:
634
+ if f.get("type") == "string" and f.get("encoding") in ("dict", "offset"):
635
+ return True
636
+ if f.get("type") == "nested" and __has_variable_strings(f["schema"]):
637
+ return True
638
+ return False
639
+
640
+
641
+ def __fill_numpy_result(result, payload, schema, count, record_bytes, is_row_major, le):
642
+ """Fill numpy structured array from payload."""
643
+ if is_row_major:
644
+ for i in range(count):
645
+ base = i * record_bytes
646
+ offset = 0
647
+ for f in schema:
648
+ __set_field_value(
649
+ result,
650
+ f["name"],
651
+ f,
652
+ i,
653
+ payload[base + offset : base + offset + f["bytes"]],
654
+ le,
655
+ )
656
+ offset += f["bytes"]
657
+ else:
658
+ col_offset = 0
659
+ for f in schema:
660
+ for i in range(count):
661
+ offset = col_offset + i * f["bytes"]
662
+ __set_field_value(
663
+ result, f["name"], f, i, payload[offset : offset + f["bytes"]], le
664
+ )
665
+ col_offset += f["bytes"] * count
666
+
667
+
668
+ def __set_field_value(result, name, field, index, raw, le):
669
+ """Set a field value in numpy result, handling nested structs."""
670
+ if field["type"] == "nested":
671
+ offset = 0
672
+ for f in field["schema"]:
673
+ __set_field_value(
674
+ result[name], f["name"], f, index, raw[offset : offset + f["bytes"]], le
675
+ )
676
+ offset += f["bytes"]
677
+ else:
678
+ result[name][index] = __decode_soa_field_value(field, raw, index, le)
679
+
680
+
681
+ def __decode_soa_to_dicts(payload, schema, count, record_bytes, is_row_major, le):
682
+ """Decode SOA to list of dicts (for variable-length strings)."""
683
+ records = []
684
+ for i in range(count):
685
+ record = {}
686
+ if is_row_major:
687
+ base = i * record_bytes
688
+ offset = 0
689
+ for f in schema:
690
+ record[f["name"]] = __decode_soa_field_value(
691
+ f, payload[base + offset : base + offset + f["bytes"]], i, le
692
+ )
693
+ offset += f["bytes"]
694
+ else:
695
+ col_offset = 0
696
+ for f in schema:
697
+ offset = col_offset + i * f["bytes"]
698
+ record[f["name"]] = __decode_soa_field_value(
699
+ f, payload[offset : offset + f["bytes"]], i, le
700
+ )
701
+ col_offset += f["bytes"] * count
702
+ records.append(record)
703
+ return records
704
+
705
+
706
+ def __get_max_string_len(records, field_name):
707
+ """Get maximum string length for a field across all records."""
708
+ max_len = 1
709
+ for r in records:
710
+ val = r.get(field_name, "")
711
+ if isinstance(val, str):
712
+ max_len = max(max_len, len(val))
713
+ elif isinstance(val, dict):
714
+ for k in val:
715
+ nested_max = __get_max_string_len_nested(val, k)
716
+ max_len = max(max_len, nested_max)
717
+ return max_len
718
+
719
+
720
+ def __get_max_string_len_nested(record, field_name):
721
+ """Get maximum string length for nested field."""
722
+ val = record.get(field_name, "")
723
+ if isinstance(val, str):
724
+ return len(val)
725
+ return 1
726
+
727
+
728
+ # --- NEW FUNCTION ---
729
+ def __schema_to_dtype_with_strings(schema, records):
730
+ """Build numpy dtype from SOA schema, using actual string lengths from data."""
731
+ dtype_list = []
732
+ for f in schema:
733
+ fname = f["name"]
734
+ ftype = f["type"]
735
+ if ftype == "numeric":
736
+ dtype_list.append((fname, __NUMPY_DTYPE_MAP[f["marker"]]))
737
+ elif ftype == "bool":
738
+ dtype_list.append((fname, "?"))
739
+ elif ftype == "null":
740
+ dtype_list.append((fname, "O"))
741
+ elif ftype == "array":
742
+ dt = "?" if f["elem_type"] == "bool" else __NUMPY_DTYPE_MAP[f["marker"]]
743
+ dtype_list.append((fname, dt, (f["count"],)))
744
+ elif ftype == "nested":
745
+ nested_records = [r.get(fname, {}) for r in records]
746
+ nested_dt = __schema_to_dtype_with_strings(f["schema"], nested_records)
747
+ dtype_list.append((fname, nested_dt))
748
+ elif ftype == "string":
749
+ max_len = max(1, max(len(r.get(fname, "")) for r in records))
750
+ dtype_list.append((fname, f"U{max_len}"))
751
+ return npdtype(dtype_list)
752
+
753
+
754
+ # --- NEW FUNCTION ---
755
+ def __dicts_to_numpy(records, schema, dims):
756
+ """Convert list of dicts to numpy structured array."""
757
+ count = len(records)
758
+ if count == 0:
759
+ return npempty(0, dtype=__schema_to_dtype(schema))
760
+
761
+ struct_dtype = __schema_to_dtype_with_strings(schema, records)
762
+ result = npempty(count, dtype=struct_dtype)
763
+
764
+ for i, record in enumerate(records):
765
+ __set_record_value(result, record, schema, i)
766
+
767
+ if len(dims) > 1:
768
+ result = result.reshape(dims)
769
+
770
+ return result
771
+
772
+
773
+ # --- NEW FUNCTION ---
774
+ def __set_record_value(result, record, schema, index):
775
+ """Set a record's values in numpy result."""
776
+ for f in schema:
777
+ fname = f["name"]
778
+ val = record.get(fname)
779
+ if f["type"] == "nested" and isinstance(val, dict):
780
+ __set_record_value(result[fname], val, f["schema"], index)
781
+ else:
782
+ result[fname][index] = val
783
+
784
+
361
785
  def __get_container_params(
362
786
  fp_read,
363
787
  in_mapping,
@@ -372,6 +796,13 @@ def __get_container_params(
372
796
  dims = []
373
797
  if marker == CONTAINER_TYPE:
374
798
  marker = fp_read(1)
799
+
800
+ # Check for SOA: ${ indicates schema object
801
+ if marker == OBJECT_START:
802
+ # This is SOA format - decode schema
803
+ schema = __decode_soa_schema(fp_read, intern_object_keys, islittle)
804
+ return marker, True, -1, schema, [], True # -1 count signals SOA
805
+
375
806
  if marker not in __TYPES:
376
807
  raise DecoderException("Invalid container type")
377
808
  type_ = marker
@@ -413,7 +844,7 @@ def __get_container_params(
413
844
  counting = False
414
845
  else:
415
846
  raise DecoderException("Container type without count")
416
- return marker, counting, count, type_, dims
847
+ return marker, counting, count, type_, dims, False
417
848
 
418
849
 
419
850
  def __decode_object(
@@ -425,7 +856,7 @@ def __decode_object(
425
856
  intern_object_keys,
426
857
  islittle,
427
858
  ):
428
- marker, counting, count, type_, dims = __get_container_params(
859
+ result = __get_container_params(
429
860
  fp_read,
430
861
  True,
431
862
  no_bytes,
@@ -435,6 +866,13 @@ def __decode_object(
435
866
  intern_object_keys,
436
867
  islittle,
437
868
  )
869
+
870
+ # Check if this is SOA format
871
+ if len(result) == 6 and result[5]: # is_soa flag
872
+ schema = result[3]
873
+ return __decode_soa(fp_read, schema, False, intern_object_keys, islittle)
874
+
875
+ marker, counting, count, type_, dims, _ = result
438
876
  has_pairs_hook = object_pairs_hook is not None
439
877
  obj = [] if has_pairs_hook else {}
440
878
 
@@ -524,7 +962,7 @@ def __decode_array(
524
962
  intern_object_keys,
525
963
  islittle,
526
964
  ):
527
- marker, counting, count, type_, dims = __get_container_params(
965
+ result = __get_container_params(
528
966
  fp_read,
529
967
  False,
530
968
  no_bytes,
@@ -535,6 +973,13 @@ def __decode_array(
535
973
  islittle,
536
974
  )
537
975
 
976
+ # Check if this is SOA format (row-major)
977
+ if len(result) == 6 and result[5]: # is_soa flag
978
+ schema = result[3]
979
+ return __decode_soa(fp_read, schema, True, intern_object_keys, islittle)
980
+
981
+ marker, counting, count, type_, dims, _ = result
982
+
538
983
  # special case - no data (None or bool)
539
984
  if type_ in __TYPES_NO_DATA:
540
985
  return [__METHOD_MAP[type_](fp_read, type_, islittle)] * count
@@ -566,7 +1011,7 @@ def __decode_array(
566
1011
  container = buffer2numpy(container, dtype=npdtype(__DTYPE_MAP[type_]))
567
1012
  return container
568
1013
 
569
- container = []
1014
+ container = list()
570
1015
  while count > 0 and (counting or marker != ARRAY_END):
571
1016
  if marker == TYPE_NOOP:
572
1017
  marker = fp_read(1)
@@ -645,7 +1090,7 @@ def load(
645
1090
  any other array (i.e. result in a list).
646
1091
  uint8_bytes (bool): If set, typed UBJSON arrays (uint8) will be
647
1092
  converted to a bytes instance instead of being
648
- treated as an array (for UBJSON & BJData Draft 2).
1093
+ treated as an array (for UBJSON & BJData Draft 4).
649
1094
  Ignored if no_bytes is set.
650
1095
  object_hook (callable): Called with the result of any object literal
651
1096
  decoded (instead of dict).
@@ -659,7 +1104,7 @@ def load(
659
1104
  in Python2 (since interning does not apply
660
1105
  to unicode) and wil be ignored.
661
1106
  islittle (1 or 0): default is 1 for little-endian for all numerics (for
662
- BJData Draft 2), change to 0 to use big-endian
1107
+ BJData Draft 4), change to 0 to use big-endian
663
1108
  (for UBJSON & BJData Draft 1)
664
1109
 
665
1110
  Returns:
@@ -697,6 +1142,10 @@ def load(
697
1142
  +----------------------------------+---------------+
698
1143
  | null | None |
699
1144
  +----------------------------------+---------------+
1145
+
1146
+ SOA (Structure of Arrays) format is automatically detected and decoded
1147
+ to a list of dicts. String fields with fixed, dict, or offset encoding
1148
+ are all supported.
700
1149
  """
701
1150
  if object_pairs_hook is None and object_hook is None:
702
1151
  object_hook = __object_hook_noop