Skip to content

Commit

Permalink
Merge pull request #76 from cdm-processors/cocas-binary-images
Browse files Browse the repository at this point in the history
Add support for binary images in `cocas`
  • Loading branch information
Intelix8996 authored Aug 31, 2024
2 parents cfb6fc3 + 6a3da2a commit 6bbf417
Showing 1 changed file with 35 additions and 6 deletions.
41 changes: 35 additions & 6 deletions cocas/linker/image.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
from collections.abc import Callable
from pathlib import Path
from typing import Union

WriterFn = Callable[[Path, bytearray], None]

def write_image(filename: Union[Path, str], arr: bytearray):
"""
Write the contents or array into file in logisim-compatible format

:param filename: path to output file
:param arr: bytearray to be written
"""
def write_binary_image(filename: Path, arr: bytearray):
with open(filename, mode='wb') as f:
f.write(arr)


def write_logisim_image(filename: Path, arr: bytearray):
with open(filename, mode='w') as f:
f.write("v2.0 raw\n")
zeroes = 0
Expand All @@ -25,3 +27,30 @@ def write_image(filename: Union[Path, str], arr: bytearray):
f.write('00\n')
zeroes = 0
f.write(f'{byte:02x}\n')


DEFAULT_WRITER = write_binary_image

IMAGE_WRITERS: dict[str, WriterFn] = {
'.bin': write_binary_image,
'.img': write_logisim_image,
}


def write_image(filename: Union[Path, str], arr: bytearray):
"""
Write the contents of array into file in format
that is derived from extension.
If extension is unknown then format is defaulted
to binary.
:param filename: path to output file
:param arr: bytearray to be written
"""

if not isinstance(filename, Path):
filename = Path(filename)

writer = IMAGE_WRITERS.get(filename.suffix, DEFAULT_WRITER)

writer(filename, arr)

0 comments on commit 6bbf417

Please sign in to comment.