Example #1
0
def read_memory(memory_path: str, field_bytes: int) -> MemoryDict:
    """
    Returns the memory (as a MemoryDict).
    """
    # Use MemoryDict to verify that memory cells are consistent.
    with open(memory_path, 'rb') as memory_file:
        return MemoryDict.deserialize(memory_file.read(), field_bytes)
Example #2
0
    def from_file(cls, fileobj) -> 'CairoPie':
        """
        Loads an instance of CairoPie from a file.
        `fileobj` can be a path or a file object.
        """

        if isinstance(fileobj, str):
            fileobj = open(fileobj, 'rb')

        verify_zip_file_prefix(fileobj=fileobj)

        with zipfile.ZipFile(fileobj) as zf:
            cls.verify_zip_format(zf)

            with zf.open(cls.METADATA_FILENAME, 'r') as fp:
                metadata = CairoPieMetadata.Schema().load(
                    json.loads(fp.read(cls.MAX_SIZE).decode('ascii')))
            with zf.open(cls.MEMORY_FILENAME, 'r') as fp:
                memory = MemoryDict.deserialize(
                    data=fp.read(cls.MAX_SIZE),
                    field_bytes=metadata.field_bytes,
                )
            with zf.open(cls.ADDITIONAL_DATA_FILENAME, 'r') as fp:
                additional_data = json.loads(
                    fp.read(cls.MAX_SIZE).decode('ascii'))
            with zf.open(cls.EXECUTION_RESOURCES_FILENAME, 'r') as fp:
                execution_resources = ExecutionResources.Schema().load(
                    json.loads(fp.read(cls.MAX_SIZE).decode('ascii')))
        return cls(metadata, memory, additional_data, execution_resources)
def test_memory_dict_serialize():
    memory = MemoryDict({1: 2, 3: 4, 5: 6})
    expected_serialized = bytes([
        1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0,
        6, 0, 0])
    serialized = memory.serialize(3)
    assert expected_serialized == serialized
    assert MemoryDict.deserialize(serialized, 3) == memory