1 package net.mograsim.machine.standard.memory;
3 import java.io.BufferedReader;
4 import java.io.ByteArrayInputStream;
5 import java.io.FileInputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.InputStreamReader;
9 import java.nio.charset.StandardCharsets;
11 import net.mograsim.logic.core.types.BitVector;
12 import net.mograsim.machine.MainMemory;
13 import net.mograsim.machine.MainMemoryDefinition;
15 public class MainMemoryParser
17 private final static String lineSeparator = System.getProperty("line.separator");
19 public static void parseMemory(final MainMemory memory, String inputPath) throws IOException
21 try (InputStream input = new FileInputStream(inputPath))
23 parseMemory(memory, input);
28 * @param input The input to parse must be in csv format; The stream is closed after being consumed.
32 public static MainMemory parseMemory(MainMemoryDefinition memDef, InputStream input) throws IOException
36 MainMemory memory = new WordAddressableMemory(memDef);
37 parseMemory(memory, input);
40 catch (NullPointerException e)
42 throw new MainMemoryParseException(e);
48 * @param input The input to parse must be in csv format; The stream is closed after being consumed.
52 public static void parseMemory(final MainMemory memory, InputStream input) throws IOException
54 try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)))
56 MainMemoryDefinition def = memory.getDefinition();
58 long minAddr = def.getMinimalAddress();
59 long maxAddr = def.getMaximalAddress();
65 for (; i <= maxAddr && reader.ready() && !"".equals((line = reader.readLine())); i++)
67 memory.setCell(i, BitVector.parseBitstring(line));
77 public static InputStream write(MainMemory memory)
79 return new InputStream()
81 long instIndex = memory.getDefinition().getMinimalAddress(), maxAddress = memory.getDefinition().getMaximalAddress();
82 InputStream instStream = new ByteArrayInputStream(new byte[0]);
85 public int read() throws IOException
87 int val = instStream.read();
88 if (val == -1 && instIndex <= maxAddress)
90 instStream = new ByteArrayInputStream(
91 (memory.getCell(instIndex++).toBitstring() + lineSeparator).getBytes(StandardCharsets.UTF_8));
92 val = instStream.read();