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;
10 import net.mograsim.logic.core.types.BitVector;
11 import net.mograsim.machine.MainMemory;
12 import net.mograsim.machine.MainMemoryDefinition;
14 public class MainMemoryParser
16 private final static String lineSeparator = System.getProperty("line.separator");
18 public static void parseMemory(final MainMemory memory, String inputPath) throws IOException
20 try (InputStream input = new FileInputStream(inputPath))
22 parseMemory(memory, input);
27 * @param input The input to parse must be in csv format; The stream is closed after being consumed.
31 public static MainMemory parseMemory(MainMemoryDefinition memDef, InputStream input) throws IOException
35 MainMemory memory = new WordAddressableMemory(memDef);
36 parseMemory(memory, input);
39 catch (NullPointerException e)
41 throw new MainMemoryParseException(e);
47 * @param input The input to parse must be in csv format; The stream is closed after being consumed.
51 public static void parseMemory(final MainMemory memory, InputStream input) throws IOException
53 try (BufferedReader reader = new BufferedReader(new InputStreamReader(input)))
55 MainMemoryDefinition def = memory.getDefinition();
57 long minAddr = def.getMinimalAddress();
58 long maxAddr = def.getMaximalAddress();
64 for (; i <= maxAddr && reader.ready() && !"".equals((line = reader.readLine())); i++)
66 memory.setCell(i, BitVector.parse(line));
76 public static InputStream write(MainMemory memory)
78 return new InputStream()
80 long instIndex = memory.getDefinition().getMinimalAddress(), maxAddress = memory.getDefinition().getMaximalAddress();
81 InputStream instStream = new ByteArrayInputStream(new byte[0]);
84 public int read() throws IOException
86 int val = instStream.read();
87 if (val == -1 && instIndex <= maxAddress)
89 instStream = new ByteArrayInputStream((memory.getCell(instIndex++).toString() + lineSeparator).getBytes());
90 val = instStream.read();