Debian Codegraph @

imageio/plugins/_bsdf.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # This file is distributed under the terms of the 2-clause BSD License.
3 # Copyright (c) 2017-2018, Almar Klein
4
5 """
6 Python implementation of the Binary Structured Data Format (BSDF).
7
8 BSDF is a binary format for serializing structured (scientific) data.
9 See http://bsdf.io for more information.
10
11 This is the reference implementation, which is relatively relatively
12 sophisticated, providing e.g. lazy loading of blobs and streamed
13 reading/writing. A simpler Python implementation is available as
14 ``bsdf_lite.py``.
15
16 This module has no dependencies and works on Python 2.7 and 3.4+.
17
18 Note: on Legacy Python (Python 2.7), non-Unicode strings are encoded as bytes.
19 """
20
21 # todo: in 2020, remove six stuff, __future__ and _isidentifier
22 # todo: in 2020, remove 'utf-8' args to encode/decode; it's faster
23
24 from __future__ import absolute_import, division, print_function
25
26 import bz2
27 import hashlib
28 import logging
29 import os
30 import re
31 import struct
32 import sys
33 import types
34 import zlib
35 from io import BytesIO
36
37 logger = logging.getLogger(__name__)
38
39 # Notes on versioning: the major and minor numbers correspond to the
40 # BSDF format version. The major number if increased when backward
41 # incompatible changes are introduced. An implementation must raise an
42 # exception when the file being read has a higher major version. The
43 # minor number is increased when new backward compatible features are
44 # introduced. An implementation must display a warning when the file
45 # being read has a higher minor version. The patch version is increased
46 # for subsequent releases of the implementation.
47 VERSION = 2, 1, 2
48 __version__ = ".".join(str(i) for i in VERSION)
49
50
51 # %% The encoder and decoder implementation
52
53 # From six.py
54 PY3 = sys.version_info[0] >= 3
55 if PY3:
56 text_type = str
57 string_types = str
58 unicode_types = str
59 integer_types = int
60 classtypes = type
61 else: # pragma: no cover
62 logging.basicConfig() # avoid "no handlers found" error
63 text_type = unicode # noqa
64 string_types = basestring # noqa
65 unicode_types = unicode # noqa
66 integer_types = (int, long) # noqa
67 classtypes = type, types.ClassType
68
69 # Shorthands
70 spack = struct.pack
71 strunpack = struct.unpack
72
73
74 def lencode(x):
75 """Encode an unsigned integer into a variable sized blob of bytes."""
76 # We could support 16 bit and 32 bit as well, but the gain is low, since
77 # 9 bytes for collections with over 250 elements is marginal anyway.
78 if x <= 250:
79 return spack("<B", x)
80 # elif x < 65536:
81 # return spack('<BH', 251, x)
82 # elif x < 4294967296:
83 # return spack('<BI', 252, x)
84 else:
85 return spack("<BQ", 253, x)
86
87
88 # Include len decoder for completeness; we've inlined it for performance.
89 def lendecode(f):
90 """Decode an unsigned integer from a file."""
91 n = strunpack("<B", f.read(1))[0]
92 if n == 253:
93 n = strunpack("<Q", f.read(8))[0] # noqa
94 return n
95
96
97 def encode_type_id(b, ext_id):
98 """Encode the type identifier, with or without extension id."""
99 if ext_id is not None:
100 bb = ext_id.encode("UTF-8")
101 return b.upper() + lencode(len(bb)) + bb # noqa
102 else:
103 return b # noqa
104
105
106 def _isidentifier(s): # pragma: no cover
107 """Use of str.isidentifier() for Legacy Python, but slower."""
108 # http://stackoverflow.com/questions/2544972/
109 return (
110 isinstance(s, string_types)
111 and re.match(r"^\w+$", s, re.UNICODE)
112 and re.match(r"^[0-9]", s) is None
113 )
114
115
116 class BsdfSerializer(object):
117 """Instances of this class represent a BSDF encoder/decoder.
118
119 It acts as a placeholder for a set of extensions and encoding/decoding
120 options. Use this to predefine extensions and options for high
121 performance encoding/decoding. For general use, see the functions
122 `save()`, `encode()`, `load()`, and `decode()`.
123
124 This implementation of BSDF supports streaming lists (keep adding
125 to a list after writing the main file), lazy loading of blobs, and
126 in-place editing of blobs (for streams opened with a+).
127
128 Options for encoding:
129
130 * compression (int or str): ``0`` or "no" for no compression (default),
131 ``1`` or "zlib" for Zlib compression (same as zip files and PNG), and
132 ``2`` or "bz2" for Bz2 compression (more compact but slower writing).
133 Note that some BSDF implementations (e.g. JavaScript) may not support
134 compression.
135 * use_checksum (bool): whether to include a checksum with binary blobs.
136 * float64 (bool): Whether to write floats as 64 bit (default) or 32 bit.
137
138 Options for decoding:
139
140 * load_streaming (bool): if True, and the final object in the structure was
141 a stream, will make it available as a stream in the decoded object.
142 * lazy_blob (bool): if True, bytes are represented as Blob objects that can
143 be used to lazily access the data, and also overwrite the data if the
144 file is open in a+ mode.
145 """
146
147 def __init__(self, extensions=None, **options):
148 self._extensions = {} # name -> extension
149 self._extensions_by_cls = {} # cls -> (name, extension.encode)
150 if extensions is None:
151 extensions = standard_extensions
152 for extension in extensions:
153 self.add_extension(extension)
154 self._parse_options(**options)
155
156 def _parse_options(
157 self,
158 compression=0,
159 use_checksum=False,
160 float64=True,
161 load_streaming=False,
162 lazy_blob=False,
163 ):
164 # Validate compression
165 if isinstance(compression, string_types):
166 m = {"no": 0, "zlib": 1, "bz2": 2}
167 compression = m.get(compression.lower(), compression)
168 if compression not in (0, 1, 2):
169 raise TypeError("Compression must be 0, 1, 2, " '"no", "zlib", or "bz2"')
170 self._compression = compression
171
172 # Other encoding args
173 self._use_checksum = bool(use_checksum)
174 self._float64 = bool(float64)
175
176 # Decoding args
177 self._load_streaming = bool(load_streaming)
178 self._lazy_blob = bool(lazy_blob)
179
180 def add_extension(self, extension_class):
181 """Add an extension to this serializer instance, which must be
182 a subclass of Extension. Can be used as a decorator.
183 """
184 # Check class
185 if not (
186 isinstance(extension_class, type) and issubclass(extension_class, Extension)
187 ):
188 raise TypeError("add_extension() expects a Extension class.")
189 extension = extension_class()
190
191 # Get name
192 name = extension.name
193 if not isinstance(name, str):
194 raise TypeError("Extension name must be str.")
195 if len(name) == 0 or len(name) > 250:
196 raise NameError(
197 "Extension names must be nonempty and shorter " "than 251 chars."
198 )
199 if name in self._extensions:
200 logger.warning(
201 'BSDF warning: overwriting extension "%s", '
202 "consider removing first" % name
203 )
204
205 # Get classes
206 cls = extension.cls
207 if not cls:
208 clss = []
209 elif isinstance(cls, (tuple, list)):
210 clss = cls
211 else:
212 clss = [cls]
213 for cls in clss:
214 if not isinstance(cls, classtypes):
215 raise TypeError("Extension classes must be types.")
216
217 # Store
218 for cls in clss:
219 self._extensions_by_cls[cls] = name, extension.encode
220 self._extensions[name] = extension
221 return extension_class
222
223 def remove_extension(self, name):
224 """Remove a converted by its unique name."""
225 if not isinstance(name, str):
226 raise TypeError("Extension name must be str.")
227 if name in self._extensions:
228 self._extensions.pop(name)
229 for cls in list(self._extensions_by_cls.keys()):
230 if self._extensions_by_cls[cls][0] == name:
231 self._extensions_by_cls.pop(cls)
232
233 def _encode(self, f, value, streams, ext_id):
234 """Main encoder function."""
235 x = encode_type_id
236
237 if value is None:
238 f.write(x(b"v", ext_id)) # V for void
239 elif value is True:
240 f.write(x(b"y", ext_id)) # Y for yes
241 elif value is False:
242 f.write(x(b"n", ext_id)) # N for no
243 elif isinstance(value, integer_types):
244 if -32768 <= value <= 32767:
245 f.write(x(b"h", ext_id) + spack("h", value)) # H for ...
246 else:
247 f.write(x(b"i", ext_id) + spack("<q", value)) # I for int
248 elif isinstance(value, float):
249 if self._float64:
250 f.write(x(b"d", ext_id) + spack("<d", value)) # D for double
251 else:
252 f.write(x(b"f", ext_id) + spack("<f", value)) # f for float
253 elif isinstance(value, unicode_types):
254 bb = value.encode("UTF-8")
255 f.write(x(b"s", ext_id) + lencode(len(bb))) # S for str
256 f.write(bb)
257 elif isinstance(value, (list, tuple)):
258 f.write(x(b"l", ext_id) + lencode(len(value))) # L for list
259 for v in value:
260 self._encode(f, v, streams, None)
261 elif isinstance(value, dict):
262 f.write(x(b"m", ext_id) + lencode(len(value))) # M for mapping
263 for key, v in value.items():
264 if PY3:
265 assert key.isidentifier() # faster
266 else: # pragma: no cover
267 assert _isidentifier(key)
268 # yield ' ' * indent + key
269 name_b = key.encode("UTF-8")
270 f.write(lencode(len(name_b)))
271 f.write(name_b)
272 self._encode(f, v, streams, None)
273 elif isinstance(value, bytes):
274 f.write(x(b"b", ext_id)) # B for blob
275 blob = Blob(
276 value, compression=self._compression, use_checksum=self._use_checksum
277 )
278 blob._to_file(f) # noqa
279 elif isinstance(value, Blob):
280 f.write(x(b"b", ext_id)) # B for blob
281 value._to_file(f) # noqa
282 elif isinstance(value, BaseStream):
283 # Initialize the stream
284 if value.mode != "w":
285 raise ValueError("Cannot serialize a read-mode stream.")
286 elif isinstance(value, ListStream):
287 f.write(x(b"l", ext_id) + spack("<BQ", 255, 0)) # L for list
288 else:
289 raise TypeError("Only ListStream is supported")
290 # Mark this as *the* stream, and activate the stream.
291 # The save() function verifies this is the last written object.
292 if len(streams) > 0:
293 raise ValueError("Can only have one stream per file.")
294 streams.append(value)
295 value._activate(f, self._encode, self._decode) # noqa
296 else:
297 if ext_id is not None:
298 raise ValueError(
299 "Extension %s wronfully encodes object to another "
300 "extension object (though it may encode to a list/dict "
301 "that contains other extension objects)." % ext_id
302 )
303 # Try if the value is of a type we know
304 ex = self._extensions_by_cls.get(value.__class__, None)
305 # Maybe its a subclass of a type we know
306 if ex is None:
307 for name, c in self._extensions.items():
308 if c.match(self, value):
309 ex = name, c.encode
310 break
311 else:
312 ex = None
313 # Success or fail
314 if ex is not None:
315 ext_id2, extension_encode = ex
316 self._encode(f, extension_encode(self, value), streams, ext_id2)
317 else:
318 t = (
319 "Class %r is not a valid base BSDF type, nor is it "
320 "handled by an extension."
321 )
322 raise TypeError(t % value.__class__.__name__)
323
324 def _decode(self, f):
325 """Main decoder function."""
326
327 # Get value
328 char = f.read(1)
329 c = char.lower()
330
331 # Conversion (uppercase value identifiers signify converted values)
332 if not char:
333 raise EOFError()
334 elif char != c:
335 n = strunpack("<B", f.read(1))[0]
336 # if n == 253: n = strunpack('<Q', f.read(8))[0] # noqa - noneed
337 ext_id = f.read(n).decode("UTF-8")
338 else:
339 ext_id = None
340
341 if c == b"v":
342 value = None
343 elif c == b"y":
344 value = True
345 elif c == b"n":
346 value = False
347 elif c == b"h":
348 value = strunpack("<h", f.read(2))[0]
349 elif c == b"i":
350 value = strunpack("<q", f.read(8))[0]
351 elif c == b"f":
352 value = strunpack("<f", f.read(4))[0]
353 elif c == b"d":
354 value = strunpack("<d", f.read(8))[0]
355 elif c == b"s":
356 n_s = strunpack("<B", f.read(1))[0]
357 if n_s == 253:
358 n_s = strunpack("<Q", f.read(8))[0] # noqa
359 value = f.read(n_s).decode("UTF-8")
360 elif c == b"l":
361 n = strunpack("<B", f.read(1))[0]
362 if n >= 254:
363 # Streaming
364 closed = n == 254
365 n = strunpack("<Q", f.read(8))[0]
366 if self._load_streaming:
367 value = ListStream(n if closed else "r")
368 value._activate(f, self._encode, self._decode) # noqa
369 elif closed:
370 value = [self._decode(f) for i in range(n)]
371 else:
372 value = []
373 try:
374 while True:
375 value.append(self._decode(f))
376 except EOFError:
377 pass
378 else:
379 # Normal
380 if n == 253:
381 n = strunpack("<Q", f.read(8))[0] # noqa
382 value = [self._decode(f) for i in range(n)]
383 elif c == b"m":
384 value = dict()
385 n = strunpack("<B", f.read(1))[0]
386 if n == 253:
387 n = strunpack("<Q", f.read(8))[0] # noqa
388 for i in range(n):
389 n_name = strunpack("<B", f.read(1))[0]
390 if n_name == 253:
391 n_name = strunpack("<Q", f.read(8))[0] # noqa
392 assert n_name > 0
393 name = f.read(n_name).decode("UTF-8")
394 value[name] = self._decode(f)
395 elif c == b"b":
396 if self._lazy_blob:
397 value = Blob((f, True))
398 else:
399 blob = Blob((f, False))
400 value = blob.get_bytes()
401 else:
402 raise RuntimeError("Parse error %r" % char)
403
404 # Convert value if we have an extension for it
405 if ext_id is not None:
406 extension = self._extensions.get(ext_id, None)
407 if extension is not None:
408 value = extension.decode(self, value)
409 else:
410 logger.warning("BSDF warning: no extension found for %r" % ext_id)
411
412 return value
413
414 def encode(self, ob):
415 """Save the given object to bytes."""
416 f = BytesIO()
417 self.save(f, ob)
418 return f.getvalue()
419
420 def save(self, f, ob):
421 """Write the given object to the given file object."""
422 f.write(b"BSDF")
423 f.write(struct.pack("<B", VERSION[0]))
424 f.write(struct.pack("<B", VERSION[1]))
425
426 # Prepare streaming, this list will have 0 or 1 item at the end
427 streams = []
428
429 self._encode(f, ob, streams, None)
430
431 # Verify that stream object was at the end, and add initial elements
432 if len(streams) > 0:
433 stream = streams[0]
434 if stream._start_pos != f.tell():
435 raise ValueError(
436 "The stream object must be " "the last object to be encoded."
437 )
438
439 def decode(self, bb):
440 """Load the data structure that is BSDF-encoded in the given bytes."""
441 f = BytesIO(bb)
442 return self.load(f)
443
444 def load(self, f):
445 """Load a BSDF-encoded object from the given file object."""
446 # Check magic string
447 f4 = f.read(4)
448 if f4 != b"BSDF":
449 raise RuntimeError("This does not look like a BSDF file: %r" % f4)
450 # Check version
451 major_version = strunpack("<B", f.read(1))[0]
452 minor_version = strunpack("<B", f.read(1))[0]
453 file_version = "%i.%i" % (major_version, minor_version)
454 if major_version != VERSION[0]: # major version should be 2
455 t = (
456 "Reading file with different major version (%s) "
457 "from the implementation (%s)."
458 )
459 raise RuntimeError(t % (__version__, file_version))
460 if minor_version > VERSION[1]: # minor should be < ours
461 t = (
462 "BSDF warning: reading file with higher minor version (%s) "
463 "than the implementation (%s)."
464 )
465 logger.warning(t % (__version__, file_version))
466
467 return self._decode(f)
468
469
470 # %% Streaming and blob-files
471
472
473 class BaseStream(object):
474 """Base class for streams."""
475
476 def __init__(self, mode="w"):
477 self._i = 0
478 self._count = -1
479 if isinstance(mode, int):
480 self._count = mode
481 mode = "r"
482 elif mode == "w":
483 self._count = 0
484 assert mode in ("r", "w")
485 self._mode = mode
486 self._f = None
487 self._start_pos = 0
488
489 def _activate(self, file, encode_func, decode_func):
490 if self._f is not None: # Associated with another write
491 raise IOError("Stream object cannot be activated twice?")
492 self._f = file
493 self._start_pos = self._f.tell()
494 self._encode = encode_func
495 self._decode = decode_func
496
497 @property
498 def mode(self):
499 """The mode of this stream: 'r' or 'w'."""
500 return self._mode
501
502
503 class ListStream(BaseStream):
504 """A streamable list object used for writing or reading.
505 In read mode, it can also be iterated over.
506 """
507
508 @property
509 def count(self):
510 """The number of elements in the stream (can be -1 for unclosed
511 streams in read-mode).
512 """
513 return self._count
514
515 @property
516 def index(self):
517 """The current index of the element to read/write."""
518 return self._i
519
520 def append(self, item):
521 """Append an item to the streaming list. The object is immediately
522 serialized and written to the underlying file.
523 """
524 # if self._mode != 'w':
525 # raise IOError('This ListStream is not in write mode.')
526 if self._count != self._i:
527 raise IOError("Can only append items to the end of the stream.")
528 if self._f is None:
529 raise IOError("List stream is not associated with a file yet.")
530 if self._f.closed:
531 raise IOError("Cannot stream to a close file.")
532 self._encode(self._f, item, [self], None)
533 self._i += 1
534 self._count += 1
535
536 def close(self, unstream=False):
537 """Close the stream, marking the number of written elements. New
538 elements may still be appended, but they won't be read during decoding.
539 If ``unstream`` is False, the stream is turned into a regular list
540 (not streaming).
541 """
542 # if self._mode != 'w':
543 # raise IOError('This ListStream is not in write mode.')
544 if self._count != self._i:
545 raise IOError("Can only close when at the end of the stream.")
546 if self._f is None:
547 raise IOError("ListStream is not associated with a file yet.")
548 if self._f.closed:
549 raise IOError("Cannot close a stream on a close file.")
550 i = self._f.tell()
551 self._f.seek(self._start_pos - 8 - 1)
552 self._f.write(spack("<B", 253 if unstream else 254))
553 self._f.write(spack("<Q", self._count))
554 self._f.seek(i)
555
556 def next(self):
557 """Read and return the next element in the streaming list.
558 Raises StopIteration if the stream is exhausted.
559 """
560 if self._mode != "r":
561 raise IOError("This ListStream in not in read mode.")
562 if self._f is None:
563 raise IOError("ListStream is not associated with a file yet.")
564 if getattr(self._f, "closed", None): # not present on 2.7 http req :/
565 raise IOError("Cannot read a stream from a close file.")
566 if self._count >= 0:
567 if self._i >= self._count:
568 raise StopIteration()
569 self._i += 1
570 return self._decode(self._f)
571 else:
572 # This raises EOFError at some point.
573 try:
574 res = self._decode(self._f)
575 self._i += 1
576 return res
577 except EOFError:
578 self._count = self._i
579 raise StopIteration()
580
581 def __iter__(self):
582 if self._mode != "r":
583 raise IOError("Cannot iterate: ListStream in not in read mode.")
584 return self
585
586 def __next__(self):
587 return self.next()
588
589
590 class Blob(object):
591 """Object to represent a blob of bytes. When used to write a BSDF file,
592 it's a wrapper for bytes plus properties such as what compression to apply.
593 When used to read a BSDF file, it can be used to read the data lazily, and
594 also modify the data if reading in 'r+' mode and the blob isn't compressed.
595 """
596
597 # For now, this does not allow re-sizing blobs (within the allocated size)
598 # but this can be added later.
599
600 def __init__(self, bb, compression=0, extra_size=0, use_checksum=False):
601 if isinstance(bb, bytes):
602 self._f = None
603 self.compressed = self._from_bytes(bb, compression)
604 self.compression = compression
605 self.allocated_size = self.used_size + extra_size
606 self.use_checksum = use_checksum
607 elif isinstance(bb, tuple) and len(bb) == 2 and hasattr(bb[0], "read"):
608 self._f, allow_seek = bb
609 self.compressed = None
610 self._from_file(self._f, allow_seek)
611 self._modified = False
612 else:
613 raise TypeError("Wrong argument to create Blob.")
614
615 def _from_bytes(self, value, compression):
616 """When used to wrap bytes in a blob."""
617 if compression == 0:
618 compressed = value
619 elif compression == 1:
620 compressed = zlib.compress(value, 9)
621 elif compression == 2:
622 compressed = bz2.compress(value, 9)
623 else: # pragma: no cover
624 assert False, "Unknown compression identifier"
625
626 self.data_size = len(value)
627 self.used_size = len(compressed)
628 return compressed
629
630 def _to_file(self, f):
631 """Private friend method called by encoder to write a blob to a file."""
632 # Write sizes - write at least in a size that allows resizing
633 if self.allocated_size <= 250 and self.compression == 0:
634 f.write(spack("<B", self.allocated_size))
635 f.write(spack("<B", self.used_size))
636 f.write(lencode(self.data_size))
637 else:
638 f.write(spack("<BQ", 253, self.allocated_size))
639 f.write(spack("<BQ", 253, self.used_size))
640 f.write(spack("<BQ", 253, self.data_size))
641 # Compression and checksum
642 f.write(spack("B", self.compression))
643 if self.use_checksum:
644 f.write(b"\xff" + hashlib.md5(self.compressed).digest())
645 else:
646 f.write(b"\x00")
647 # Byte alignment (only necessary for uncompressed data)
648 if self.compression == 0:
649 alignment = 8 - (f.tell() + 1) % 8 # +1 for the byte to write
650 f.write(spack("<B", alignment)) # padding for byte alignment
651 f.write(b"\x00" * alignment)
652 else:
653 f.write(spack("<B", 0))
654 # The actual data and extra space
655 f.write(self.compressed)
656 f.write(b"\x00" * (self.allocated_size - self.used_size))
657
658 def _from_file(self, f, allow_seek):
659 """Used when a blob is read by the decoder."""
660 # Read blob header data (5 to 42 bytes)
661 # Size
662 allocated_size = strunpack("<B", f.read(1))[0]
663 if allocated_size == 253:
664 allocated_size = strunpack("<Q", f.read(8))[0] # noqa
665 used_size = strunpack("<B", f.read(1))[0]
666 if used_size == 253:
667 used_size = strunpack("<Q", f.read(8))[0] # noqa
668 data_size = strunpack("<B", f.read(1))[0]
669 if data_size == 253:
670 data_size = strunpack("<Q", f.read(8))[0] # noqa
671 # Compression and checksum
672 compression = strunpack("<B", f.read(1))[0]
673 has_checksum = strunpack("<B", f.read(1))[0]
674 if has_checksum:
675 checksum = f.read(16)
676 # Skip alignment
677 alignment = strunpack("<B", f.read(1))[0]
678 f.read(alignment)
679 # Get or skip data + extra space
680 if allow_seek:
681 self.start_pos = f.tell()
682 self.end_pos = self.start_pos + used_size
683 f.seek(self.start_pos + allocated_size)
684 else:
685 self.start_pos = None
686 self.end_pos = None
687 self.compressed = f.read(used_size)
688 f.read(allocated_size - used_size)
689 # Store info
690 self.alignment = alignment
691 self.compression = compression
692 self.use_checksum = checksum if has_checksum else None
693 self.used_size = used_size
694 self.allocated_size = allocated_size
695 self.data_size = data_size
696
697 def seek(self, p):
698 """Seek to the given position (relative to the blob start)."""
699 if self._f is None:
700 raise RuntimeError(
701 "Cannot seek in a blob " "that is not created by the BSDF decoder."
702 )
703 if p < 0:
704 p = self.allocated_size + p
705 if p < 0 or p > self.allocated_size:
706 raise IOError("Seek beyond blob boundaries.")
707 self._f.seek(self.start_pos + p)
708
709 def tell(self):
710 """Get the current file pointer position (relative to the blob start)."""
711 if self._f is None:
712 raise RuntimeError(
713 "Cannot tell in a blob " "that is not created by the BSDF decoder."
714 )
715 return self._f.tell() - self.start_pos
716
717 def write(self, bb):
718 """Write bytes to the blob."""
719 if self._f is None:
720 raise RuntimeError(
721 "Cannot write in a blob " "that is not created by the BSDF decoder."
722 )
723 if self.compression:
724 raise IOError("Cannot arbitrarily write in compressed blob.")
725 if self._f.tell() + len(bb) > self.end_pos:
726 raise IOError("Write beyond blob boundaries.")
727 self._modified = True
728 return self._f.write(bb)
729
730 def read(self, n):
731 """Read n bytes from the blob."""
732 if self._f is None:
733 raise RuntimeError(
734 "Cannot read in a blob " "that is not created by the BSDF decoder."
735 )
736 if self.compression:
737 raise IOError("Cannot arbitrarily read in compressed blob.")
738 if self._f.tell() + n > self.end_pos:
739 raise IOError("Read beyond blob boundaries.")
740 return self._f.read(n)
741
742 def get_bytes(self):
743 """Get the contents of the blob as bytes."""
744 if self.compressed is not None:
745 compressed = self.compressed
746 else:
747 i = self._f.tell()
748 self.seek(0)
749 compressed = self._f.read(self.used_size)
750 self._f.seek(i)
751 if self.compression == 0:
752 value = compressed
753 elif self.compression == 1:
754 value = zlib.decompress(compressed)
755 elif self.compression == 2:
756 value = bz2.decompress(compressed)
757 else: # pragma: no cover
758 raise RuntimeError("Invalid compression %i" % self.compression)
759 return value
760
761 def update_checksum(self):
762 """Reset the blob's checksum if present. Call this after modifying
763 the data.
764 """
765 # or ... should the presence of a checksum mean that data is proteced?
766 if self.use_checksum and self._modified:
767 self.seek(0)
768 compressed = self._f.read(self.used_size)
769 self._f.seek(self.start_pos - self.alignment - 1 - 16)
770 self._f.write(hashlib.md5(compressed).digest())
771
772
773 # %% High-level functions
774
775
776 def encode(ob, extensions=None, **options):
777 """Save (BSDF-encode) the given object to bytes.
778 See `BSDFSerializer` for details on extensions and options.
779 """
780 s = BsdfSerializer(extensions, **options)
781 return s.encode(ob)
782
783
784 def save(f, ob, extensions=None, **options):
785 """Save (BSDF-encode) the given object to the given filename or
786 file object. See` BSDFSerializer` for details on extensions and options.
787 """
788 s = BsdfSerializer(extensions, **options)
789 if isinstance(f, string_types):
790 with open(f, "wb") as fp:
791 return s.save(fp, ob)
792 else:
793 return s.save(f, ob)
794
795
796 def decode(bb, extensions=None, **options):
797 """Load a (BSDF-encoded) structure from bytes.
798 See `BSDFSerializer` for details on extensions and options.
799 """
800 s = BsdfSerializer(extensions, **options)
801 return s.decode(bb)
802
803
804 def load(f, extensions=None, **options):
805 """Load a (BSDF-encoded) structure from the given filename or file object.
806 See `BSDFSerializer` for details on extensions and options.
807 """
808 s = BsdfSerializer(extensions, **options)
809 if isinstance(f, string_types):
810 if f.startswith(("~/", "~\\")): # pragma: no cover
811 f = os.path.expanduser(f)
812 with open(f, "rb") as fp:
813 return s.load(fp)
814 else:
815 return s.load(f)
816
817
818 # Aliases for json compat
819 loads = decode
820 dumps = encode
821
822
823 # %% Standard extensions
824
825 # Defining extensions as a dict would be more compact and feel lighter, but
826 # that would only allow lambdas, which is too limiting, e.g. for ndarray
827 # extension.
828
829
830 class Extension(object):
831 """Base class to implement BSDF extensions for special data types.
832
833 Extension classes are provided to the BSDF serializer, which
834 instantiates the class. That way, the extension can be somewhat dynamic:
835 e.g. the NDArrayExtension exposes the ndarray class only when numpy
836 is imported.
837
838 A extension instance must have two attributes. These can be attributes of
839 the class, or of the instance set in ``__init__()``:
840
841 * name (str): the name by which encoded values will be identified.
842 * cls (type): the type (or list of types) to match values with.
843 This is optional, but it makes the encoder select extensions faster.
844
845 Further, it needs 3 methods:
846
847 * `match(serializer, value) -> bool`: return whether the extension can
848 convert the given value. The default is ``isinstance(value, self.cls)``.
849 * `encode(serializer, value) -> encoded_value`: the function to encode a
850 value to more basic data types.
851 * `decode(serializer, encoded_value) -> value`: the function to decode an
852 encoded value back to its intended representation.
853
854 """
855
856 name = ""
857 cls = ()
858
859 def __repr__(self):
860 return "<BSDF extension %r at 0x%s>" % (self.name, hex(id(self)))
861
862 def match(self, s, v):
863 return isinstance(v, self.cls)
864
865 def encode(self, s, v):
866 raise NotImplementedError()
867
868 def decode(self, s, v):
869 raise NotImplementedError()
870
871
872 class ComplexExtension(Extension):
873 name = "c"
874 cls = complex
875
876 def encode(self, s, v):
877 return (v.real, v.imag)
878
879 def decode(self, s, v):
880 return complex(v[0], v[1])
881
882
883 class NDArrayExtension(Extension):
884 name = "ndarray"
885
886 def __init__(self):
887 if "numpy" in sys.modules:
888 import numpy as np
889
890 self.cls = np.ndarray
891
892 def match(self, s, v): # pragma: no cover - e.g. work for nd arrays in JS
893 return hasattr(v, "shape") and hasattr(v, "dtype") and hasattr(v, "tobytes")
894
895 def encode(self, s, v):
896 return dict(shape=v.shape, dtype=text_type(v.dtype), data=v.tobytes())
897
898 def decode(self, s, v):
899 try:
900 import numpy as np
901 except ImportError: # pragma: no cover
902 return v
903 a = np.frombuffer(v["data"], dtype=v["dtype"])
904 a = a.reshape(v["shape"])
905 return a
906
907
908 standard_extensions = [ComplexExtension, NDArrayExtension]
909
910
911 if __name__ == "__main__":
912 # Invoke CLI
913 import bsdf_cli
914
915 bsdf_cli.main()