| 1 |
|
| 2 |
|
| 3 |
|
| 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 |
|
| 22 |
|
| 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 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
VERSION = 2, 1, 2 |
| 48 |
__version__ = ".".join(str(i) for i in VERSION) |
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 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: |
| 62 |
logging.basicConfig() |
| 63 |
text_type = unicode |
| 64 |
string_types = basestring |
| 65 |
unicode_types = unicode |
| 66 |
integer_types = (int, long) |
| 67 |
classtypes = type, types.ClassType |
| 68 |
|
| 69 |
|
| 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 |
|
| 77 |
|
| 78 |
if x <= 250: |
| 79 |
return spack("<B", x) |
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
else: |
| 85 |
return spack("<BQ", 253, x) |
| 86 |
|
| 87 |
|
| 88 |
|
| 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] |
| 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 |
| 102 |
else: |
| 103 |
return b |
| 104 |
|
| 105 |
|
| 106 |
def _isidentifier(s): |
| 107 |
"""Use of str.isidentifier() for Legacy Python, but slower.""" |
| 108 |
|
| 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 = {} |
| 149 |
self._extensions_by_cls = {} |
| 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 |
|
| 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 |
|
| 173 |
self._use_checksum = bool(use_checksum) |
| 174 |
self._float64 = bool(float64) |
| 175 |
|
| 176 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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)) |
| 239 |
elif value is True: |
| 240 |
f.write(x(b"y", ext_id)) |
| 241 |
elif value is False: |
| 242 |
f.write(x(b"n", ext_id)) |
| 243 |
elif isinstance(value, integer_types): |
| 244 |
if -32768 <= value <= 32767: |
| 245 |
f.write(x(b"h", ext_id) + spack("h", value)) |
| 246 |
else: |
| 247 |
f.write(x(b"i", ext_id) + spack("<q", value)) |
| 248 |
elif isinstance(value, float): |
| 249 |
if self._float64: |
| 250 |
f.write(x(b"d", ext_id) + spack("<d", value)) |
| 251 |
else: |
| 252 |
f.write(x(b"f", ext_id) + spack("<f", value)) |
| 253 |
elif isinstance(value, unicode_types): |
| 254 |
bb = value.encode("UTF-8") |
| 255 |
f.write(x(b"s", ext_id) + lencode(len(bb))) |
| 256 |
f.write(bb) |
| 257 |
elif isinstance(value, (list, tuple)): |
| 258 |
f.write(x(b"l", ext_id) + lencode(len(value))) |
| 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))) |
| 263 |
for key, v in value.items(): |
| 264 |
if PY3: |
| 265 |
assert key.isidentifier() |
| 266 |
else: |
| 267 |
assert _isidentifier(key) |
| 268 |
|
| 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)) |
| 275 |
blob = Blob( |
| 276 |
value, compression=self._compression, use_checksum=self._use_checksum |
| 277 |
) |
| 278 |
blob._to_file(f) |
| 279 |
elif isinstance(value, Blob): |
| 280 |
f.write(x(b"b", ext_id)) |
| 281 |
value._to_file(f) |
| 282 |
elif isinstance(value, BaseStream): |
| 283 |
|
| 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)) |
| 288 |
else: |
| 289 |
raise TypeError("Only ListStream is supported") |
| 290 |
|
| 291 |
|
| 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) |
| 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 |
|
| 304 |
ex = self._extensions_by_cls.get(value.__class__, None) |
| 305 |
|
| 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 |
|
| 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 |
|
| 328 |
char = f.read(1) |
| 329 |
c = char.lower() |
| 330 |
|
| 331 |
|
| 332 |
if not char: |
| 333 |
raise EOFError() |
| 334 |
elif char != c: |
| 335 |
n = strunpack("<B", f.read(1))[0] |
| 336 |
|
| 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] |
| 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 |
|
| 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) |
| 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 |
|
| 380 |
if n == 253: |
| 381 |
n = strunpack("<Q", f.read(8))[0] |
| 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] |
| 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] |
| 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 |
|
| 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 |
|
| 427 |
streams = [] |
| 428 |
|
| 429 |
self._encode(f, ob, streams, None) |
| 430 |
|
| 431 |
|
| 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 |
|
| 447 |
f4 = f.read(4) |
| 448 |
if f4 != b"BSDF": |
| 449 |
raise RuntimeError("This does not look like a BSDF file: %r" % f4) |
| 450 |
|
| 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]: |
| 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]: |
| 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 |
|
| 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: |
| 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 |
|
| 525 |
|
| 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 |
|
| 543 |
|
| 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): |
| 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 |
|
| 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 |
|
| 598 |
|
| 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: |
| 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 |
|
| 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 |
|
| 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 |
|
| 648 |
if self.compression == 0: |
| 649 |
alignment = 8 - (f.tell() + 1) % 8 |
| 650 |
f.write(spack("<B", alignment)) |
| 651 |
f.write(b"\x00" * alignment) |
| 652 |
else: |
| 653 |
f.write(spack("<B", 0)) |
| 654 |
|
| 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 |
|
| 661 |
|
| 662 |
allocated_size = strunpack("<B", f.read(1))[0] |
| 663 |
if allocated_size == 253: |
| 664 |
allocated_size = strunpack("<Q", f.read(8))[0] |
| 665 |
used_size = strunpack("<B", f.read(1))[0] |
| 666 |
if used_size == 253: |
| 667 |
used_size = strunpack("<Q", f.read(8))[0] |
| 668 |
data_size = strunpack("<B", f.read(1))[0] |
| 669 |
if data_size == 253: |
| 670 |
data_size = strunpack("<Q", f.read(8))[0] |
| 671 |
|
| 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 |
|
| 677 |
alignment = strunpack("<B", f.read(1))[0] |
| 678 |
f.read(alignment) |
| 679 |
|
| 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 |
|
| 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: |
| 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 |
|
| 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 |
|
| 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(("~/", "~\\")): |
| 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 |
|
| 819 |
loads = decode |
| 820 |
dumps = encode |
| 821 |
|
| 822 |
|
| 823 |
|
| 824 |
|
| 825 |
|
| 826 |
|
| 827 |
|
| 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): |
| 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: |
| 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 |
|
| 913 |
import bsdf_cli |
| 914 |
|
| 915 |
bsdf_cli.main() |