From 1436068d4c9f8b625e33ccadffde127dbc585bc8 Mon Sep 17 00:00:00 2001 From: Jim Rybarski Date: Fri, 27 Nov 2015 00:38:32 -0600 Subject: [PATCH] #125: refactored to make adding more metadata easier --- nd2reader/common/v3.py | 97 +++++++++++++ nd2reader/interface.py | 6 +- nd2reader/model/label.py | 5 + nd2reader/parser/v3.py | 296 ++++++++++++++++++++------------------- 4 files changed, 259 insertions(+), 145 deletions(-) diff --git a/nd2reader/common/v3.py b/nd2reader/common/v3.py index 6fb0424..65222c3 100644 --- a/nd2reader/common/v3.py +++ b/nd2reader/common/v3.py @@ -1,5 +1,6 @@ import struct import array +import six def read_chunk(fh, chunk_location): @@ -13,6 +14,8 @@ def read_chunk(fh, chunk_location): :rtype: bytes """ + if chunk_location is None: + return None fh.seek(chunk_location) # The chunk metadata is always 16 bytes long chunk_metadata = fh.read(16) @@ -32,4 +35,98 @@ def read_array(fh, kind, chunk_location): if kind not in kinds: raise ValueError('You attempted to read an array of an unknown type.') raw_data = read_chunk(fh, chunk_location) + if raw_data is None: + return None return array.array(kinds[kind], raw_data) + + +def _parse_unsigned_char(data): + return struct.unpack("B", data.read(1))[0] + + +def _parse_unsigned_int(data): + return struct.unpack("I", data.read(4))[0] + + +def _parse_unsigned_long(data): + return struct.unpack("Q", data.read(8))[0] + + +def _parse_double(data): + return struct.unpack("d", data.read(8))[0] + + +def _parse_string(data): + value = data.read(2) + while not value.endswith(six.b("\x00\x00")): + # the string ends at the first instance of \x00\x00 + value += data.read(2) + return value.decode("utf16")[:-1].encode("utf8") + + +def _parse_char_array(data): + array_length = struct.unpack("Q", data.read(8))[0] + return array.array("B", data.read(array_length)) + + +def _parse_metadata_item(data, cursor_position): + """ + Reads hierarchical data, analogous to a Python dict. + + """ + new_count, length = struct.unpack("