-
Notifications
You must be signed in to change notification settings - Fork 239
/
slob.py
1498 lines (1242 loc) · 35.3 KB
/
slob.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# slob.py
# Copyright (C) 2020-2023 Saeed Rasooli
# Copyright (C) 2019 Igor Tkach <itkach@gmail.com>
# as part of https://github.com/itkach/slob
#
# This program is a free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. Or on Debian systems, from /usr/share/common-licenses/GPL
# If not, see <http://www.gnu.org/licenses/gpl.txt>.
import encodings
import io
import operator
import os
import pickle
import sys
import tempfile
import typing
import warnings
from abc import abstractmethod
from bisect import bisect_left
from builtins import open as fopen
from collections.abc import Callable, Iterator, Mapping, Sequence
from datetime import datetime, timezone
from functools import cache, lru_cache
from io import BufferedIOBase, IOBase
from os.path import isdir
from struct import calcsize, pack, unpack
from threading import RLock
from types import MappingProxyType, TracebackType
from typing import (
TYPE_CHECKING,
Any,
Generic,
NamedTuple,
TypeVar,
cast,
)
from uuid import UUID, uuid4
import icu # type: ignore
from icu import Collator, Locale, UCollAttribute, UCollAttributeValue
if TYPE_CHECKING:
from .icu_types import T_Collator
__all__ = [
"MAX_TEXT_LEN",
"MAX_TINY_TEXT_LEN",
"MIME_HTML",
"MIME_TEXT",
"MultiFileReader",
"UnknownEncoding",
"Writer",
"encodings",
"fopen",
"open",
"read_byte_string",
"read_header",
"sortkey",
]
DEFAULT_COMPRESSION = "lzma2"
UTF8 = "utf-8"
MAGIC = b"!-1SLOB\x1f"
class Compression(NamedTuple):
compress: Callable[..., bytes] # first arg: bytes
decompress: Callable[[bytes], bytes]
class Ref(NamedTuple):
key: str
bin_index: int
item_index: int
fragment: str
class Header(NamedTuple):
magic: bytes
uuid: UUID
encoding: str
compression: str
tags: MappingProxyType[str, str]
content_types: Sequence[str]
blob_count: int
store_offset: int
refs_offset: int
size: int
U_CHAR = ">B"
U_CHAR_SIZE = calcsize(U_CHAR)
U_SHORT = ">H"
U_SHORT_SIZE = calcsize(U_SHORT)
U_INT = ">I"
U_INT_SIZE = calcsize(U_INT)
U_LONG_LONG = ">Q"
U_LONG_LONG_SIZE = calcsize(U_LONG_LONG)
def calcmax(len_size_spec: str) -> int:
return 2 ** (calcsize(len_size_spec) * 8) - 1
MAX_TEXT_LEN = calcmax(U_SHORT)
MAX_TINY_TEXT_LEN = calcmax(U_CHAR)
MAX_LARGE_BYTE_STRING_LEN = calcmax(U_INT)
MAX_BIN_ITEM_COUNT = calcmax(U_SHORT)
PRIMARY: int = Collator.PRIMARY
SECONDARY: int = Collator.SECONDARY
TERTIARY: int = Collator.TERTIARY
QUATERNARY: int = Collator.QUATERNARY
IDENTICAL: int = Collator.IDENTICAL
class CompressionModule(typing.Protocol):
# gzip.compress(data, compresslevel=9, *, mtime=None)
# bz2.compress(data, compresslevel=9)
# zlib.compress(data, /, level=-1, wbits=15)
# lzma.compress(data, format=1, check=-1, preset=None, filters=None)
@staticmethod
def compress(data: bytes, compresslevel: int = 9) -> bytes:
raise NotImplementedError
# gzip.decompress(data)
# bz2.decompress(data)
# zlib.decompress(data, /, wbits=15, bufsize=16384)
# lzma.decompress(data, format=0, memlimit=None, filters=None)
@staticmethod
def decompress(
data: bytes,
**kwargs: "Mapping[str, Any]",
) -> bytes:
raise NotImplementedError
def init_compressions() -> "dict[str, Compression]":
def ident(x: bytes) -> bytes:
return x
compressions: "dict[str, Compression]" = {
"": Compression(ident, ident),
}
for name in ("bz2", "zlib"):
m: CompressionModule
try:
m = cast(CompressionModule, __import__(name))
except ImportError:
warnings.showwarning(
message=f"{name} is not available",
category=ImportWarning,
filename=__file__,
lineno=0,
)
continue
def compress_new(x: bytes, m: CompressionModule = m) -> bytes:
return m.compress(x, 9)
compressions[name] = Compression(compress_new, m.decompress)
try:
import lzma
except ImportError:
warnings.warn("lzma is not available", stacklevel=1)
else:
filters = [{"id": lzma.FILTER_LZMA2}]
compressions["lzma2"] = Compression(
lambda s: lzma.compress(
s,
format=lzma.FORMAT_RAW,
filters=filters,
),
lambda s: lzma.decompress(
s,
format=lzma.FORMAT_RAW,
filters=filters,
),
)
return compressions
COMPRESSIONS = init_compressions()
del init_compressions
MIME_TEXT = "text/plain"
MIME_HTML = "text/html"
class FileFormatException(Exception):
pass
class UnknownFileFormat(FileFormatException):
pass
class UnknownCompression(FileFormatException):
pass
class UnknownEncoding(FileFormatException):
pass
class IncorrectFileSize(FileFormatException):
pass
@cache
def sortkey(
strength: int,
maxlength: "int | None" = None,
) -> "Callable":
# pass empty locale to use root locale
# if you pass no arg, it will use system locale
c: "T_Collator" = Collator.createInstance(Locale(""))
c.setStrength(strength)
c.setAttribute(
UCollAttribute.ALTERNATE_HANDLING,
UCollAttributeValue.SHIFTED,
)
if maxlength is None:
return c.getSortKey
return lambda x: c.getSortKey(x)[:maxlength]
class MultiFileReader(BufferedIOBase):
def __init__(
self,
*args: str,
) -> None:
filenames: "list[str]" = list(args)
files = []
ranges = []
offset = 0
for name in filenames:
size = os.stat(name).st_size
ranges.append(range(offset, offset + size))
files.append(fopen(name, "rb"))
offset += size
self.size = offset
self._ranges = ranges
self._files = files
self._fcount = len(self._files)
self._offset = -1
self.seek(0)
def __enter__(self) -> "MultiFileReader":
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
self.close()
def close(self) -> None:
for f in self._files:
f.close()
self._files.clear()
self._ranges.clear()
@property
def closed(self) -> bool:
return len(self._ranges) == 0
def isatty(self) -> bool: # noqa: PLR6301
return False
def readable(self) -> bool: # noqa: PLR6301
return True
def seek(
self,
offset: int,
whence: int = io.SEEK_SET,
) -> int:
if whence == io.SEEK_SET:
self._offset = offset
elif whence == io.SEEK_CUR:
self._offset += offset
elif whence == io.SEEK_END:
self._offset = self.size + offset
else:
raise ValueError(f"Invalid value for parameter whence: {whence!r}")
return self._offset
def seekable(self) -> bool: # noqa: PLR6301
return True
def tell(self) -> int:
return self._offset
def writable(self) -> bool: # noqa: PLR6301
return False
def read(self, n: "int | None" = -1) -> bytes:
file_index = -1
actual_offset = 0
for i, r in enumerate(self._ranges):
if self._offset in r:
file_index = i
actual_offset = self._offset - r.start
break
result = b""
to_read = self.size if n == -1 or n is None else n
while -1 < file_index < self._fcount:
f = self._files[file_index]
f.seek(actual_offset)
read = f.read(to_read)
read_count = len(read)
self._offset += read_count
result += read
to_read -= read_count
if to_read > 0:
file_index += 1
actual_offset = 0
else:
break
return result
class KeydItemDict:
def __init__(
self,
blobs: "Sequence[Blob | Ref]",
strength: int,
maxlength: "int | None" = None,
) -> None:
self.blobs = blobs
self.sortkey = sortkey(strength, maxlength=maxlength)
def __len__(self) -> int:
return len(self.blobs)
# https://docs.python.org/3/library/bisect.html
# key= parameter to bisect_left is added in Python 3.10
def __getitem__(self, key: str) -> "Iterator[Blob | Ref]":
blobs = self.blobs
key_as_sk = self.sortkey(key)
i = bisect_left(
blobs,
key_as_sk,
key=lambda blob: self.sortkey(blob.key),
)
if i == len(blobs):
return
while i < len(blobs):
if self.sortkey(blobs[i].key) == key_as_sk:
yield blobs[i]
else:
break
i += 1
def __contains__(self, key: str) -> bool:
try:
next(self[key])
except StopIteration:
return False
return True
class Blob:
def __init__( # noqa: PLR0913
self,
content_id: int,
key: str,
fragment: str,
read_content_type_func: "Callable[[], str]",
read_func: "Callable",
) -> None:
# print(f"read_func is {type(read_func)}")
# read_func is <class 'functools._lru_cache_wrapper'>
self._content_id = content_id
self._key = key
self._fragment = fragment
self._read_content_type = read_content_type_func
self._read = read_func
@property
def identity(self) -> int:
return self._content_id
@property
def key(self) -> str:
return self._key
@property
def fragment(self) -> str:
return self._fragment
@property
def content_type(self) -> str:
return self._read_content_type()
@property
def content(self) -> bytes:
return self._read()
def __str__(self) -> str:
return self.key
def __repr__(self) -> str:
return f"<{self.__class__.__module__}.{self.__class__.__name__} {self.key}>"
def read_byte_string(f: "IOBase", len_spec: str) -> bytes:
length = unpack(len_spec, f.read(calcsize(len_spec)))[0]
return f.read(length)
class StructReader:
def __init__(
self,
_file: "IOBase",
encoding: "str | None" = None,
) -> None:
self._file = _file
self.encoding = encoding
def read_int(self) -> int:
s = self.read(U_INT_SIZE)
return unpack(U_INT, s)[0]
def read_long(self) -> int:
b = self.read(U_LONG_LONG_SIZE)
return unpack(U_LONG_LONG, b)[0]
def read_byte(self) -> int:
s = self.read(U_CHAR_SIZE)
return unpack(U_CHAR, s)[0]
def read_short(self) -> int:
return unpack(U_SHORT, self._file.read(U_SHORT_SIZE))[0]
def _read_text(self, len_spec: str) -> str:
if self.encoding is None:
raise ValueError("self.encoding is None")
max_len = 2 ** (8 * calcsize(len_spec)) - 1
byte_string = read_byte_string(self._file, len_spec)
if len(byte_string) == max_len:
terminator = byte_string.find(0)
if terminator > -1:
byte_string = byte_string[:terminator]
return byte_string.decode(self.encoding)
def read_tiny_text(self) -> str:
return self._read_text(U_CHAR)
def read_text(self) -> str:
return self._read_text(U_SHORT)
def read(self, n: int) -> bytes:
return self._file.read(n)
def write(self, data: bytes) -> int:
return self._file.write(data)
def seek(self, pos: int) -> None:
self._file.seek(pos)
def tell(self) -> int:
return self._file.tell()
def close(self) -> None:
self._file.close()
def flush(self) -> None:
self._file.flush()
class StructWriter:
def __init__(
self,
_file: "io.BufferedWriter",
encoding: "str | None" = None,
) -> None:
self._file = _file
self.encoding = encoding
def write_int(self, value: int) -> None:
self._file.write(pack(U_INT, value))
def write_long(self, value: int) -> None:
self._file.write(pack(U_LONG_LONG, value))
def write_byte(self, value: int) -> None:
self._file.write(pack(U_CHAR, value))
def write_short(self, value: int) -> None:
self._file.write(pack(U_SHORT, value))
def _write_text(
self,
text: str,
len_size_spec: str,
encoding: "str | None" = None,
pad_to_length: "int | None" = None,
) -> None:
if encoding is None:
encoding = self.encoding
if encoding is None:
raise ValueError("encoding is None")
text_bytes = text.encode(encoding)
length = len(text_bytes)
max_length = calcmax(len_size_spec)
if length > max_length:
raise ValueError(f"Text is too long for size spec {len_size_spec}")
self._file.write(
pack(
len_size_spec,
pad_to_length or length,
),
)
self._file.write(text_bytes)
if pad_to_length:
for _ in range(pad_to_length - length):
self._file.write(pack(U_CHAR, 0))
def write_tiny_text(
self,
text: str,
encoding: "str | None" = None,
editable: bool = False,
) -> None:
pad_to_length = 255 if editable else None
self._write_text(
text,
U_CHAR,
encoding=encoding,
pad_to_length=pad_to_length,
)
def write_text(
self,
text: str,
encoding: "str | None" = None,
) -> None:
self._write_text(text, U_SHORT, encoding=encoding)
def close(self) -> None:
self._file.close()
def flush(self) -> None:
self._file.flush()
@property
def name(self) -> str:
return self._file.name
def tell(self) -> int:
return self._file.tell()
def write(self, data: bytes) -> int:
return self._file.write(data)
def read_header(_file: "MultiFileReader") -> Header:
_file.seek(0)
magic = _file.read(len(MAGIC))
if magic != MAGIC:
raise UnknownFileFormat(f"magic {magic!r} != {MAGIC!r}")
uuid = UUID(bytes=_file.read(16))
encoding = read_byte_string(_file, U_CHAR).decode(UTF8)
if encodings.search_function(encoding) is None:
raise UnknownEncoding(encoding)
reader = StructReader(_file, encoding)
compression = reader.read_tiny_text()
if compression not in COMPRESSIONS:
raise UnknownCompression(compression)
def read_tags() -> "dict[str, str]":
count = reader.read_byte()
return {reader.read_tiny_text(): reader.read_tiny_text() for _ in range(count)}
tags = read_tags()
def read_content_types() -> "Sequence[str]":
content_types: "list[str]" = []
count = reader.read_byte()
for _ in range(count):
content_type = reader.read_text()
content_types.append(content_type)
return tuple(content_types)
content_types = read_content_types()
blob_count = reader.read_int()
store_offset = reader.read_long()
size = reader.read_long()
refs_offset = reader.tell()
return Header(
magic=magic,
uuid=uuid,
encoding=encoding,
compression=compression,
tags=MappingProxyType(tags),
content_types=content_types,
blob_count=blob_count,
store_offset=store_offset,
refs_offset=refs_offset,
size=size,
)
def meld_ints(a: int, b: int) -> int:
return (a << 16) | b
def unmeld_ints(c: int) -> "tuple[int, int]":
bstr = bin(c).lstrip("0b").zfill(48)
a, b = bstr[-48:-16], bstr[-16:]
return int(a, 2), int(b, 2)
class Slob:
def __init__(
self,
*filenames: str,
) -> None:
self._f = MultiFileReader(*filenames)
try:
self._header = read_header(self._f)
if self._f.size != self._header.size:
raise IncorrectFileSize(
f"File size should be {self._header.size}, "
f"{self._f.size} bytes found",
)
except FileFormatException:
self._f.close()
raise
self._refs = RefList(
self._f,
self._header.encoding,
offset=self._header.refs_offset,
)
self._g = MultiFileReader(*filenames)
self._store = Store(
self._g,
self._header.store_offset,
COMPRESSIONS[self._header.compression].decompress,
self._header.content_types,
)
def __enter__(self) -> "Slob":
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
self.close()
@property
def identity(self) -> str:
return self._header.uuid.hex
@property
def content_types(self) -> "Sequence[str]":
return self._header.content_types
@property
def tags(self) -> MappingProxyType[str, str]:
return self._header.tags
@property
def blob_count(self) -> int:
return self._header.blob_count
@property
def compression(self) -> str:
return self._header.compression
@property
def encoding(self) -> str:
return self._header.encoding
def __len__(self) -> int:
return len(self._refs)
def __getitem__(self, i: int) -> Any:
# this is called by bisect_left
return self.getBlobByIndex(i)
def __iter__(self) -> "Iterator[Blob]":
for i in range(len(self._refs)):
yield self.getBlobByIndex(i)
def count(self) -> int:
# just to comply with Sequence and make type checker happy
raise NotImplementedError
def index(self, x: "Blob") -> int:
# just to comply with Sequence and make type checker happy
raise NotImplementedError
def getBlobByIndex(self, i: int) -> "Blob":
ref = self._refs[i]
def read_func() -> bytes:
return self._store.get(ref.bin_index, ref.item_index)[1]
read_func = lru_cache(maxsize=None)(read_func)
def read_content_type_func() -> str:
return self._store.content_type(ref.bin_index, ref.item_index)
content_id = meld_ints(ref.bin_index, ref.item_index)
return Blob(
content_id=content_id,
key=ref.key,
fragment=ref.fragment,
read_content_type_func=read_content_type_func,
read_func=read_func,
)
def get(self, blob_id: int) -> "tuple[str, bytes]":
"""Returns (content_type: str, content: bytes)."""
bin_index, bin_item_index = unmeld_ints(blob_id)
return self._store.get(bin_index, bin_item_index)
@cache
def as_dict(
self: "Slob",
strength: int = TERTIARY,
maxlength: "int | None" = None,
) -> KeydItemDict:
return KeydItemDict(
cast(Sequence, self),
strength=strength,
maxlength=maxlength,
)
def close(self) -> None:
self._f.close()
self._g.close()
def open(*filenames: str) -> Slob:
return Slob(*filenames)
class BinMemWriter:
def __init__(self) -> None:
self.content_type_ids: "list[int]" = []
self.item_dir: "list[bytes]" = []
self.items: "list[bytes]" = []
self.current_offset = 0
def add(self, content_type_id: int, blob_bytes: bytes) -> None:
self.content_type_ids.append(content_type_id)
self.item_dir.append(pack(U_INT, self.current_offset))
length_and_bytes = pack(U_INT, len(blob_bytes)) + blob_bytes
self.items.append(length_and_bytes)
self.current_offset += len(length_and_bytes)
def __len__(self) -> int:
return len(self.item_dir)
def finalize(
self,
fout: "BufferedIOBase",
compress: "Callable[[bytes], bytes]",
) -> None:
count = len(self)
fout.write(pack(U_INT, count))
for content_type_id in self.content_type_ids:
fout.write(pack(U_CHAR, content_type_id))
content = b"".join(self.item_dir + self.items)
compressed = compress(content)
fout.write(pack(U_INT, len(compressed)))
fout.write(compressed)
self.content_type_ids.clear()
self.item_dir.clear()
self.items.clear()
ItemT = TypeVar("ItemT")
class ItemList(Generic[ItemT]):
def __init__(
self,
reader: "StructReader",
offset: int,
count_or_spec: "str | int",
pos_spec: str,
) -> None:
self.lock = RLock()
self.reader = reader
reader.seek(offset)
count: int
if isinstance(count_or_spec, str):
count_spec = count_or_spec
count = unpack(count_spec, reader.read(calcsize(count_spec)))[0]
elif isinstance(count_or_spec, int):
count = count_or_spec
else:
raise TypeError(f"invalid {count_or_spec = }")
self._count: int = count
self.pos_offset = reader.tell()
self.pos_spec = pos_spec
self.pos_size = calcsize(pos_spec)
self.data_offset = self.pos_offset + self.pos_size * count
def __len__(self) -> int:
return self._count
def pos(self, i: int) -> int:
with self.lock:
self.reader.seek(self.pos_offset + self.pos_size * i)
return unpack(self.pos_spec, self.reader.read(self.pos_size))[0]
def read(self, pos: int) -> ItemT:
with self.lock:
self.reader.seek(self.data_offset + pos)
return self._read_item()
@abstractmethod
def _read_item(self) -> ItemT:
pass
def __getitem__(self, i: int) -> ItemT:
if i >= len(self) or i < 0:
raise IndexError("index out of range")
return self.read(self.pos(i))
class RefList(ItemList[Ref]):
def __init__(
self,
f: "IOBase",
encoding: str,
offset: int = 0,
count: "int | None" = None,
) -> None:
super().__init__(
reader=StructReader(f, encoding),
offset=offset,
count_or_spec=U_INT if count is None else count,
pos_spec=U_LONG_LONG,
)
@lru_cache(maxsize=512)
def __getitem__(
self,
i: int,
) -> "Ref":
if i >= len(self) or i < 0:
raise IndexError("index out of range")
return cast(Ref, self.read(self.pos(i)))
def _read_item(self) -> "Ref":
key = self.reader.read_text()
bin_index = self.reader.read_int()
item_index = self.reader.read_short()
fragment = self.reader.read_tiny_text()
return Ref(
key=key,
bin_index=bin_index,
item_index=item_index,
fragment=fragment,
)
@cache
def as_dict(
self: "RefList",
strength: int = TERTIARY,
maxlength: "int | None" = None,
) -> KeydItemDict:
return KeydItemDict(
cast(Sequence, self),
strength=strength,
maxlength=maxlength,
)
class Bin(ItemList[bytes]):
def __init__(
self,
count: int,
bin_bytes: bytes,
) -> None:
super().__init__(
reader=StructReader(io.BytesIO(bin_bytes)),
offset=0,
count_or_spec=count,
pos_spec=U_INT,
)
def _read_item(self) -> bytes:
content_len = self.reader.read_int()
return self.reader.read(content_len)
class StoreItem(NamedTuple):
content_type_ids: list[int]
compressed_content: bytes
class Store(ItemList[StoreItem]):
def __init__(
self,
_file: "IOBase",
offset: int,
decompress: "Callable[[bytes], bytes]",
content_types: "Sequence[str]",
) -> None:
super().__init__(
reader=StructReader(_file),
offset=offset,
count_or_spec=U_INT,
pos_spec=U_LONG_LONG,
)
self.decompress = decompress
self.content_types = content_types
@lru_cache(maxsize=32)
def __getitem__(
self,
i: int,
) -> "StoreItem":
if i >= len(self) or i < 0:
raise IndexError("index out of range")
return cast(StoreItem, self.read(self.pos(i)))
def _read_item(self) -> "StoreItem":
bin_item_count = self.reader.read_int()
packed_content_type_ids = self.reader.read(bin_item_count * U_CHAR_SIZE)
content_type_ids = []
for i in range(bin_item_count):
content_type_id = unpack(U_CHAR, packed_content_type_ids[i : i + 1])[0]
content_type_ids.append(content_type_id)
content_length = self.reader.read_int()
content = self.reader.read(content_length)
return StoreItem(
content_type_ids=content_type_ids,
compressed_content=content,
)
def _content_type(
self,
bin_index: int,
item_index: int,
) -> "tuple[str, StoreItem]":
store_item = self[bin_index]
content_type_id = store_item.content_type_ids[item_index]
content_type = self.content_types[content_type_id]
return content_type, store_item
def content_type(
self,
bin_index: int,
item_index: int,
) -> str:
return self._content_type(bin_index, item_index)[0]
@lru_cache(maxsize=16)
def _decompress(self, bin_index: int) -> bytes:
store_item = self[bin_index]
return self.decompress(store_item.compressed_content)
def get(
self,
bin_index: int,
item_index: int,
) -> "tuple[str, bytes]":
content_type, store_item = self._content_type(bin_index, item_index)
content = self._decompress(bin_index)
count = len(store_item.content_type_ids)
store_bin = Bin(count, content)