/
__init__.py
2390 lines (1966 loc) · 76.5 KB
/
__init__.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim :set ft=py:
""" Command line interface to Blosc via python-blosc """
from __future__ import division
import abc
import argparse
import contextlib
import cStringIO
import json
import itertools
import os
import os.path as path
import pprint
import struct
import sys
import zlib
try:
from collections import OrderedDict
except ImportError: # pragma: no cover
from ordereddict import OrderedDict
import blosc
import numpy as np
from .checksums import (check_valid_checksum,
CHECKSUMS_LOOKUP,
CHECKSUMS_AVAIL,
)
from .exceptions import FileNotFound
from .constants import (FORMAT_VERSION,
EXTENSION,
PREFIX,
BLOSC_HEADER_LENGTH,
BLOSCPACK_HEADER_LENGTH,
METADATA_HEADER_LENGTH,
MAX_FORMAT_VERSION,
MAX_CHUNKS,
MAX_META_SIZE,
)
__version__ = '0.6.0-rc1'
__author__ = 'Valentin Haenel <valentin@haenel.co>'
# Bloscpack args
BLOSCPACK_ARGS = ('offsets', 'checksum', 'max_app_chunks')
_BLOSCPACK_ARGS_SET = set(BLOSCPACK_ARGS) # cached
DEFAULT_OFFSETS = True
DEFAULT_CHECKSUM = 'adler32'
DEFAULT_MAX_APP_CHUNKS = lambda x: 10 * x
DEFAULT_BLOSCPACK_ARGS = dict(zip(BLOSCPACK_ARGS,
(DEFAULT_OFFSETS, DEFAULT_CHECKSUM, DEFAULT_MAX_APP_CHUNKS)))
DEFAULT_CHUNK_SIZE = '1M'
# Blosc args
BLOSC_ARGS = ('typesize', 'clevel', 'shuffle', 'cname')
_BLOSC_ARGS_SET = set(BLOSC_ARGS) # cached
DEFAULT_TYPESIZE = 8
DEFAULT_CLEVEL = 7
MAX_CLEVEL = 9
DEFAULT_SHUFFLE = True
DEFAULT_CNAME = 'blosclz'
DEFAULT_BLOSC_ARGS = dict(zip(BLOSC_ARGS,
(DEFAULT_TYPESIZE, DEFAULT_CLEVEL, DEFAULT_SHUFFLE, DEFAULT_CNAME)))
# metadata args
METADATA_ARGS = ('magic_format', 'meta_checksum', 'meta_codec', 'meta_level', 'max_meta_size')
_METADATA_ARGS_SET = set(METADATA_ARGS) # cached
DEFAULT_MAGIC_FORMAT = 'JSON'
DEFAULT_META_CHECKSUM = 'adler32'
DEFAULT_META_CODEC = 'zlib'
DEFAULT_META_LEVEL = 6
DEFAULT_MAX_META_SIZE = lambda x: 10 * x
DEFAULT_METADATA_ARGS = dict(zip(METADATA_ARGS,
(DEFAULT_MAGIC_FORMAT, DEFAULT_META_CHECKSUM,
DEFAULT_META_CODEC, DEFAULT_META_LEVEL, DEFAULT_MAX_META_SIZE)))
# Codecs available from Blosc
CNAME_AVAIL = blosc.compressor_list()
# verbosity levels
NORMAL = 'NORMAL'
VERBOSE = 'VERBOSE'
DEBUG = 'DEBUG'
LEVEL = NORMAL
VERBOSITY_LEVELS = (NORMAL, VERBOSE, DEBUG)
# lookup table for human readable sizes
SUFFIXES = OrderedDict((
("B", 2**0 ),
("K", 2**10),
("M", 2**20),
("G", 2**30),
("T", 2**40)))
class ChunkingException(BaseException):
pass
class NoSuchCodec(ValueError):
pass
class NoSuchSerializer(ValueError):
pass
class FormatVersionMismatch(RuntimeError):
pass
class ChecksumMismatch(RuntimeError):
pass
class ChecksumLengthMismatch(RuntimeError):
pass
class NoMetadataFound(RuntimeError):
pass
class NoChangeInMetadata(RuntimeError):
pass
class MetadataSectionTooSmall(RuntimeError):
pass
class NonUniformTypesize(RuntimeError):
pass
class NotEnoughSpace(RuntimeError):
pass
class NotANumpyArray(RuntimeError):
pass
class Codec(object):
""" Uniform codec object.
Parameters
----------
name : str
the name of the codec
compress : callable
a compression function taking data and level as args
decompress : callable
a decompression function taking data as arg
"""
def __init__(self, name, compress, decompress):
self.name = name
self._compress = compress
self._decompress = decompress
def compress(self, data, level):
return self._compress(data, level)
def decompress(self, data):
return self._decompress(data)
CODECS = [Codec('None', lambda data, level: data, lambda data: data),
Codec('zlib', zlib.compress, zlib.decompress)]
CODECS_AVAIL = [c.name for c in CODECS]
CODECS_LOOKUP = dict(((c.name, c) for c in CODECS))
def _check_valid_codec(codec):
""" Check the validity of a codec.
Parameters
----------
codec : str
the string descriptor of the codec
Raises
------
NoSuchCodec
if no such checksum exists.
"""
if codec not in CODECS_AVAIL:
raise NoSuchCodec("codec '%s' does not exist" % codec)
class Serializer(object):
""" Uniform serializer object.
Parameters
----------
name : str
the name of the serializer
compress : callable
a compression function taking a dict as arg
decompress : callable
a decompression function taking serialized data as arg
"""
def __init__(self, name, dumps, loads):
self.name = name
self._loads = loads
self._dumps = dumps
def dumps(self, dict_):
return self._dumps(dict_)
def loads(self, data):
return self._loads(data)
SERIZLIALIZERS = [Serializer('JSON',
lambda x: json.dumps(x, separators=(',', ':')),
lambda x: json.loads(x))]
SERIZLIALIZERS_AVAIL = [s.name for s in SERIZLIALIZERS]
SERIZLIALIZERS_LOOKUP = dict(((s.name, s) for s in SERIZLIALIZERS))
def _check_valid_serializer(serializer):
""" Check the validity of a serializer.
Parameters
----------
serializer : str
the magic format of the serializer
Raises
------
NoSuchSerializer
if no such serializer exists.
"""
if serializer not in SERIZLIALIZERS_AVAIL:
raise NoSuchSerializer("serializer '%s' does not exist" % serializer)
def print_verbose(message, level=VERBOSE):
""" Print message with desired verbosity level. """
if level not in VERBOSITY_LEVELS:
raise TypeError("Desired level '%s' is not one of %s" % (level,
str(VERBOSITY_LEVELS)))
if VERBOSITY_LEVELS.index(level) <= VERBOSITY_LEVELS.index(LEVEL):
for line in [l for l in message.split('\n') if l != '']:
print('%s: %s' % (PREFIX, line))
def print_debug(message):
""" Print message with verbosity level ``DEBUG``. """
print_verbose(message, level=DEBUG)
def print_normal(message):
""" Print message with verbosity level ``NORMAL``. """
print_verbose(message, level=NORMAL)
def error(message, exit_code=1):
""" Print message and exit with desired code. """
for line in [l for l in message.split('\n') if l != '']:
print('%s: error: %s' % (PREFIX, line))
sys.exit(exit_code)
def pretty_size(size_in_bytes):
""" Pretty print filesize. """
if size_in_bytes == 0:
return "0B"
for suf, lim in reversed(sorted(SUFFIXES.items(), key=lambda x: x[1])):
if size_in_bytes < lim:
continue
else:
return str(round(size_in_bytes/lim, 2))+suf
def double_pretty_size(size_in_bytes):
""" Pretty print filesize including size in bytes. """
return ("%s (%dB)" % (pretty_size(size_in_bytes), size_in_bytes))
def reverse_pretty(readable):
""" Reverse pretty printed file size. """
# otherwise we assume it has a suffix
suffix = readable[-1]
if suffix not in SUFFIXES.keys():
raise ValueError(
"'%s' is not a valid prefix multiplier, use one of: '%s'" %
(suffix, SUFFIXES.keys()))
else:
return int(float(readable[:-1]) * SUFFIXES[suffix])
def drop_caches(): # pragma: no cover
if os.geteuid() == 0:
os.system('echo 3 > /proc/sys/vm/drop_caches')
else:
raise RuntimeError('Need root permission to drop caches')
def sync():
os.system('sync')
def decode_uint8(byte):
return struct.unpack('<B', byte)[0]
def decode_uint32(fourbyte):
return struct.unpack('<I', fourbyte)[0]
def decode_int32(fourbyte):
return struct.unpack('<i', fourbyte)[0]
def decode_int64(eightbyte):
return struct.unpack('<q', eightbyte)[0]
def decode_bitfield(byte):
return bin(decode_uint8(byte))[2:].rjust(8, '0')
def decode_magic_string(str_):
return str_.strip('\x00')
def encode_uint8(byte):
return struct.pack('<B', byte)
def encode_uint32(byte):
return struct.pack('<I', byte)
def encode_int32(fourbyte):
return struct.pack('<i', fourbyte)
def encode_int64(eightbyte):
return struct.pack('<q', eightbyte)
@contextlib.contextmanager
def open_two_file(input_fp, output_fp):
""" Hack for making with statement work on two files with 2.6. """
yield input_fp, output_fp
input_fp.close()
output_fp.close()
PYTHON_VERSION = sys.version_info[0:3]
if sys.version_info < (2, 7, 5): # pragma: no cover
memoryview = lambda x: x
def join_with_eol(items):
return ', '.join(items) + '\n'
class BloscPackCustomFormatter(argparse.HelpFormatter):
""" Custom HelpFormatter.
Basically a combination and extension of ArgumentDefaultsHelpFormatter and
RawTextHelpFormatter. Adds default values to argument help, but only if the
default is not in [None, True, False]. Also retains all whitespace as it
is.
"""
def _get_help_string(self, action):
help_ = action.help
if '%(default)' not in action.help \
and action.default not in \
[argparse.SUPPRESS, None, True, False]:
defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE]
if action.option_strings or action.nargs in defaulting_nargs:
help_ += ' (default: %(default)s)'
return help_
def _split_lines(self, text, width):
return text.splitlines()
def _inject_blosc_group(parser):
blosc_group = parser.add_argument_group(title='blosc settings')
blosc_group.add_argument('-t', '--typesize',
metavar='<size>',
default=DEFAULT_TYPESIZE,
type=int,
help='typesize for blosc')
blosc_group.add_argument('-l', '--clevel',
default=DEFAULT_CLEVEL,
choices=range(10),
metavar='[0, 9]',
type=int,
help='compression level')
blosc_group.add_argument('-s', '--no-shuffle',
action='store_false',
default=DEFAULT_SHUFFLE,
dest='shuffle',
help='deactivate shuffle')
blosc_group.add_argument('-c', '--codec',
metavar='<codec>',
type=str,
choices=CNAME_AVAIL,
default=DEFAULT_CNAME,
dest='cname',
help="codec to be used by Blosc: \n%s"
% join_with_eol(CNAME_AVAIL))
def create_parser():
""" Create and return the parser. """
parser = argparse.ArgumentParser(
#usage='%(prog)s [GLOBAL_OPTIONS] (compress | decompress)
# [COMMAND_OPTIONS] <in_file> [<out_file>]',
description='command line de/compression with blosc',
formatter_class=BloscPackCustomFormatter)
## print version of bloscpack, python-blosc and blosc itself
parser.add_argument('--version',
action='version',
version='%(prog)s:\t' + ("'%s'\n" % __version__) +
"python-blosc:\t'%s'\n" % blosc.version.__version__ +
"blosc:\t\t'%s'\n" % blosc.BLOSC_VERSION_STRING)
output_group = parser.add_mutually_exclusive_group()
output_group.add_argument('-v', '--verbose',
action='store_true',
default=False,
help='be verbose about actions')
output_group.add_argument('-d', '--debug',
action='store_true',
default=False,
help='print debugging output too')
global_group = parser.add_argument_group(title='global options')
global_group.add_argument('-f', '--force',
action='store_true',
default=False,
help='disable overwrite checks for existing files\n' +
'(use with caution)')
class CheckThreadOption(argparse.Action):
def __call__(self, parser, namespace, value, option_string=None):
if not 1 <= value <= blosc.BLOSC_MAX_THREADS:
error('%s must be 1 <= n <= %d'
% (option_string, blosc.BLOSC_MAX_THREADS))
setattr(namespace, self.dest, value)
global_group.add_argument('-n', '--nthreads',
metavar='[1, %d]' % blosc.BLOSC_MAX_THREADS,
action=CheckThreadOption,
default=blosc.ncores,
type=int,
dest='nthreads',
help='set number of threads, (default: %(default)s (ncores))')
subparsers = parser.add_subparsers(title='subcommands',
metavar='', dest='subcommand')
compress_parser = subparsers.add_parser('compress',
formatter_class=BloscPackCustomFormatter,
help='perform compression on file')
c_parser = subparsers.add_parser('c',
formatter_class=BloscPackCustomFormatter,
help="alias for 'compress'")
class CheckChunkSizeOption(argparse.Action):
def __call__(self, parser, namespace, value, option_string=None):
if value == 'max':
value = blosc.BLOSC_MAX_BUFFERSIZE
else:
try:
# try to get the value as bytes
if value[-1] in SUFFIXES.keys():
value = reverse_pretty(value)
# seems to be intended to be a naked int
else:
value = int(value)
except ValueError as ve:
error('%s error: %s' % (option_string, str(ve) +
" or 'max'"))
if value < 0:
error('%s must be > 0 ' % option_string)
setattr(namespace, self.dest, value)
for p in [compress_parser, c_parser]:
_inject_blosc_group(p)
bloscpack_chunking_group = p.add_mutually_exclusive_group()
bloscpack_chunking_group.add_argument('-z', '--chunk-size',
metavar='<size>',
action=CheckChunkSizeOption,
type=str,
default=DEFAULT_CHUNK_SIZE,
dest='chunk_size',
help="set desired chunk size or 'max'")
bloscpack_group = p.add_argument_group(title='bloscpack settings')
checksum_format = join_with_eol(CHECKSUMS_AVAIL[0:3]) + \
join_with_eol(CHECKSUMS_AVAIL[3:6]) + \
join_with_eol(CHECKSUMS_AVAIL[6:])
checksum_help = 'set desired checksum:\n' + checksum_format
bloscpack_group.add_argument('-k', '--checksum',
metavar='<checksum>',
type=str,
choices=CHECKSUMS_AVAIL,
default=DEFAULT_CHECKSUM,
dest='checksum',
help=checksum_help)
bloscpack_group.add_argument('-o', '--no-offsets',
action='store_false',
default=DEFAULT_OFFSETS,
dest='offsets',
help='deactivate offsets')
bloscpack_group.add_argument('-m', '--metadata',
metavar='<metadata>',
type=str,
dest='metadata',
help="file containing the metadata, must contain valid JSON")
decompress_parser = subparsers.add_parser('decompress',
formatter_class=BloscPackCustomFormatter,
help='perform decompression on file')
d_parser = subparsers.add_parser('d',
formatter_class=BloscPackCustomFormatter,
help="alias for 'decompress'")
for p in [decompress_parser, d_parser]:
p.add_argument('-e', '--no-check-extension',
action='store_true',
default=False,
dest='no_check_extension',
help='disable checking input file for extension (*.blp)\n' +
'(requires use of <out_file>)')
for p, help_in, help_out in [(compress_parser,
'file to be compressed', 'file to compress to'),
(c_parser,
'file to be compressed', 'file to compress to'),
(decompress_parser,
'file to be decompressed', 'file to decompress to'),
(d_parser,
'file to be decompressed', 'file to decompress to'),
]:
p.add_argument('in_file',
metavar='<in_file>',
type=str,
default=None,
help=help_in)
p.add_argument('out_file',
metavar='<out_file>',
type=str,
nargs='?',
default=None,
help=help_out)
append_parser = subparsers.add_parser('append',
formatter_class=BloscPackCustomFormatter,
help='append data to a compressed file')
a_parser = subparsers.add_parser('a',
formatter_class=BloscPackCustomFormatter,
help="alias for 'append'")
for p in (append_parser, a_parser):
_inject_blosc_group(p)
p.add_argument('original_file',
metavar='<original_file>',
type=str,
help="file to append to")
p.add_argument('new_file',
metavar='<new_file>',
type=str,
help="file to append from")
p.add_argument('-e', '--no-check-extension',
action='store_true',
default=False,
dest='no_check_extension',
help='disable checking original file for extension (*.blp)\n')
p.add_argument('-m', '--metadata',
metavar='<metadata>',
type=str,
dest='metadata',
help="file containing the metadata, must contain valid JSON")
info_parser = subparsers.add_parser('info',
formatter_class=BloscPackCustomFormatter,
help='print information about a compressed file')
i_parser = subparsers.add_parser('i',
formatter_class=BloscPackCustomFormatter,
help="alias for 'info'")
for p in (info_parser, i_parser):
p.add_argument('file_',
metavar='<file>',
type=str,
default=None,
help="file to show info for")
return parser
def decode_blosc_header(buffer_):
""" Read and decode header from compressed Blosc buffer.
Parameters
----------
buffer_ : string of bytes
the compressed buffer
Returns
-------
settings : dict
a dict containing the settings from Blosc
Notes
-----
Please see the readme for a precise descripttion of the blosc header
format.
"""
buffer_ = memoryview(buffer_)
return {'version': decode_uint8(buffer_[0]),
'versionlz': decode_uint8(buffer_[1]),
'flags': decode_uint8(buffer_[2]),
'typesize': decode_uint8(buffer_[3]),
'nbytes': decode_uint32(buffer_[4:8]),
'blocksize': decode_uint32(buffer_[8:12]),
'ctbytes': decode_uint32(buffer_[12:16])}
def calculate_nchunks(in_file_size, chunk_size=DEFAULT_CHUNK_SIZE):
""" Determine chunking for an input file.
Parameters
----------
in_file_size : int
the size of the input file
chunk_size : int or str
the desired chunk size
Returns
-------
nchunks, chunk_size, last_chunk_size
nchunks : int
the number of chunks
chunk_size : int
the size of each chunk in bytes
last_chunk_size : int
the size of the last chunk in bytes
Raises
------
ChunkingException
if the resulting nchunks is larger than MAX_CHUNKS
"""
if in_file_size <= 0:
raise ValueError("'in_file_size' must be strictly positive, not %d"
% in_file_size)
# convert a human readable description to an int
if isinstance(chunk_size, basestring):
chunk_size = reverse_pretty(chunk_size)
check_range('chunk_size', chunk_size, 1, blosc.BLOSC_MAX_BUFFERSIZE)
# downcast
if chunk_size > in_file_size:
print_verbose(
"Input was smaller than the given 'chunk_size': %s using: %s"
% (double_pretty_size(chunk_size),
double_pretty_size(in_file_size)))
chunk_size = in_file_size
quotient, remainder = divmod(in_file_size, chunk_size)
# the user wants a single chunk
if chunk_size == in_file_size:
nchunks = 1
chunk_size = in_file_size
last_chunk_size = in_file_size
# no remainder, perfect fit
elif remainder == 0:
nchunks = quotient
last_chunk_size = chunk_size
# with a remainder
else:
nchunks = quotient + 1
last_chunk_size = remainder
if nchunks > MAX_CHUNKS:
raise ChunkingException(
"nchunks: '%d' is greater than the MAX_CHUNKS: '%d'" %
(nchunks, MAX_CHUNKS))
print_verbose('nchunks: %d' % nchunks, level=VERBOSE)
print_verbose('chunk_size: %s' % double_pretty_size(chunk_size),
level=VERBOSE)
print_verbose('last_chunk_size: %s' % double_pretty_size(last_chunk_size),
level=DEBUG)
return nchunks, chunk_size, last_chunk_size
def check_range(name, value, min_, max_):
""" Check that a variable is in range. """
if not isinstance(value, (int, long)):
raise TypeError("'%s' must be of type 'int'" % name)
elif not min_ <= value <= max_:
raise ValueError(
"'%s' must be in the range %s <= n <= %s, not '%s'" %
tuple(map(str, (name, min_, max_, value))))
def _check_str(name, value, max_len):
if not isinstance(value, str):
raise TypeError("'%s' must be of type 'int'" % name)
elif len(value) > max_len:
raise ValueError("'%s' can be of max length '%i' but is: '%s'" %
(name, max_len, len(value)))
def _pad_with_nulls(str_, len_):
""" Pad string with null bytes.
Parameters
----------
str_ : str
the string to pad
len_ : int
the final desired length
"""
return str_ + ("\x00" * (len_ - len(str_)))
def _check_options(options):
""" Check the options bitfield.
Parameters
----------
options : str
Raises
------
TypeError
if options is not a string
ValueError
either if any character in option is not a zero or a one, or if options
is not of length 8
"""
if not isinstance(options, str):
raise TypeError("'options' must be of type 'str', not '%s'" %
type(options))
elif (not len(options) == 8 or
not all(map(lambda x: x in ['0', '1'], iter(options)))):
raise ValueError(
"'options' must be string of 0s and 1s of length 8, not '%s'" %
options)
def _check_options_zero(options, indices):
for i in indices:
if options[i] != '0':
raise ValueError(
'Element %i was non-zero when attempting to decode options')
def _check_blosc_args(blosc_args):
""" Check the integrity of the blosc arguments dict.
Parameters
----------
blosc_args : dict
blosc args dictionary
Raises
------
ValueError
if there are missing or unexpected keys present
Notes
-----
Check the value of the 'BLOSC_ARGS' constant for the details of what
keys should be contained in the dictionary.
"""
__check_args('blosc', blosc_args, _BLOSC_ARGS_SET)
def _check_bloscpack_args(bloscpack_args):
""" Check the integrity of the bloscpack arguments dict.
Parameters
----------
bloscpack_args : dict
blosc args dictionary
Raises
------
ValueError
if there are missing or unexpected keys present
Notes
-----
Check the value of the 'BLOSCPACK_ARGS' constant for the details of what
keys should be contained in the dictionary.
"""
__check_args('bloscpack', bloscpack_args, _BLOSCPACK_ARGS_SET)
def _check_metadata_arguments(metadata_args):
""" Check the integrity of the metadata arguments dict.
Parameters
----------
metadata_args : dict
metadata args dictionary
Raises
------
ValueError
if there are missing or unexpected keys present
Notes
-----
Check the value of the 'METADATA_ARGS' constant for the details of what
keys should be contained in the dictionary.
"""
__check_args('metadata', metadata_args, _METADATA_ARGS_SET)
def __check_args(name, received, expected):
""" Check an arg dict.
Parameters
----------
name : str
the name of the arg dict
received : dict
the arg dict received
expected : set of str
the keys that should have been contained
"""
received = set(received.keys())
missing = expected.difference(received)
if len(missing) != 0:
raise ValueError("%s args was missing: '%s'" % (name, repr(missing)))
extra = received.difference(expected)
if len(extra) != 0:
raise ValueError("%s args had some extras: '%s'" % (name, repr(extra)))
def create_options(offsets=DEFAULT_OFFSETS, metadata=False):
""" Create the options bitfield.
Parameters
----------
offsets : bool
metadata : bool
"""
return "".join([str(int(i)) for i in
[False, False, False, False, False, False, metadata, offsets]])
def decode_options(options):
""" Parse the options bitfield.
Parameters
----------
options : str
the options bitfield
Returns
-------
options : dict mapping str -> bool
"""
_check_options(options)
_check_options_zero(options, range(6))
return {'offsets': bool(int(options[7])),
'metadata': bool(int(options[6])),
}
def create_metadata_options():
""" Create the metadata options bitfield. """
return "00000000"
def decode_metadata_options(options):
_check_options(options)
_check_options_zero(options, range(8))
return {}
from .headers import BloscPackHeader
def _handle_max_apps(offsets, nchunks, max_app_chunks):
""" Process and handle the 'max_app_chunks' argument
Parameters
----------
offsets: bool
if the offsets to the chunks are present
nchunks : int
the number of chunks
max_app_chunks : callable or int
the total number of possible append chunks
Returns
-------
max_app_chunks : int
the int value
Raises
------
TypeError
if 'max_app_chunks' is neither a callable or an int
ValueError
if 'max_app_chunks' is a callable and returned either a non-int or a
negative int.
Notes
-----
The 'max_app_chunks' parameter can either be a function of 'nchunks'
(callable that takes a single int as argument and returns a single int) or
an int. The sum of the resulting value and 'nchunks' can not be larger
than MAX_CHUNKS. The value of 'max_app_chunks' must be '0' if there is not
offsets section or if nchunks is unknown (has the value '-1').
The function performs some silent optimisations. First, if there are no
offsets or 'nchunks' is unknown any value for 'max_app_chunks' will be
silently ignored. Secondly, if the resulting value of max_app_chunks would
be too large, i.e. the sum of 'nchunks' and 'max_app_chunks' is larger than
'MAX_CHUNKS', then 'max_app_chunks' is automatically set to the maximum
permissible value.
"""
# first check that the args are actually valid
check_range('nchunks', nchunks, -1, MAX_CHUNKS)
# then check that we actually need to evaluate it
if offsets and nchunks != -1:
if hasattr(max_app_chunks, '__call__'):
# it's a callable all right
print_debug("max_app_chunks is a callable")
max_app_chunks = max_app_chunks(nchunks)
if not isinstance(max_app_chunks, (int, long)):
raise ValueError(
"max_app_chunks callable returned a non integer "
"of type '%s'" % type(max_app_chunks))
# check that the result is still positive, might be quite large
if max_app_chunks < 0:
raise ValueError(
'max_app_chunks callable returned a negative integer')
elif isinstance(max_app_chunks, (int, long)):
# it's a plain int, check it's range
print_debug("max_app_chunks is an int")
check_range('max_app_chunks', max_app_chunks, 0, MAX_CHUNKS)
else:
raise TypeError('max_app_chunks was neither a callable or an int')
# we managed to get a reasonable value, make sure it's not too large
if nchunks + max_app_chunks > MAX_CHUNKS:
max_app_chunks = MAX_CHUNKS - nchunks
print_debug(
"max_app_chunks was too large, setting to max value: %d"
% max_app_chunks)
else:
if max_app_chunks is not None:
print_debug('max_app_chunks will be silently ignored')
max_app_chunks = 0
print_debug("max_app_chunks was set to: %d" % max_app_chunks)
return max_app_chunks
def create_metadata_header(magic_format='',
options="00000000",
meta_checksum='None',
meta_codec='None',
meta_level=0,
meta_size=0,
max_meta_size=0,
meta_comp_size=0,
user_codec='',
):
_check_str('magic-format', magic_format, 8)
_check_options(options)
check_valid_checksum(meta_checksum)
_check_valid_codec(meta_codec)
check_range('meta_level', meta_level, 0, MAX_CLEVEL)
check_range('meta_size', meta_size, 0, MAX_META_SIZE)
check_range('max_meta_size', max_meta_size, 0, MAX_META_SIZE)
check_range('meta_comp_size', meta_comp_size, 0, MAX_META_SIZE)