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.BitVectorMemory;
13 import net.mograsim.machine.MainMemory;
14 import net.mograsim.machine.MainMemoryDefinition;
15 import net.mograsim.machine.MemoryDefinition;
16 import net.mograsim.machine.StandardMainMemory;
17 import net.mograsim.machine.mi.MPROM;
18 import net.mograsim.machine.mi.MPROMDefinition;
19 import net.mograsim.machine.mi.StandardMPROM;
21 public class BitVectorBasedMemoryParser
23 private final static String lineSeparator = System.getProperty("line.separator");
25 public static void parseMemory(final BitVectorMemory memory, String inputPath) throws IOException
27 try (InputStream input = new FileInputStream(inputPath))
29 parseMemory(memory, input);
34 * @param input The input to parse must be in csv format; The stream is closed after being consumed.
38 public static MainMemory parseMainMemory(MainMemoryDefinition memDef, InputStream input) throws IOException
42 MainMemory memory = new StandardMainMemory(memDef);
43 parseMemory(memory, input);
46 catch (NullPointerException e)
48 throw new BitVectorMemoryParseException(e);
53 * @param input The input to parse must be in csv format; The stream is closed after being consumed.
57 public static MPROM parseMPROM(MPROMDefinition memDef, InputStream input) throws IOException
61 MPROM memory = new StandardMPROM(memDef);
62 parseMemory(memory, input);
65 catch (NullPointerException e)
67 throw new BitVectorMemoryParseException(e);
73 * @param input The input to parse must be in csv format; The stream is closed after being consumed.
77 public static void parseMemory(final BitVectorMemory memory, InputStream input) throws IOException
79 try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)))
81 MemoryDefinition def = memory.getDefinition();
83 long minAddr = def.getMinimalAddress();
84 long maxAddr = def.getMaximalAddress();
90 for (; i <= maxAddr && reader.ready() && !"".equals((line = reader.readLine())); i++)
92 memory.setCell(i, BitVector.parseBitstring(line));
102 public static InputStream write(BitVectorMemory memory)
104 return new InputStream()
106 long instIndex = memory.getDefinition().getMinimalAddress(), maxAddress = memory.getDefinition().getMaximalAddress();
107 InputStream instStream = new ByteArrayInputStream(new byte[0]);
110 public int read() throws IOException
112 int val = instStream.read();
113 if (val == -1 && instIndex <= maxAddress)
115 instStream = new ByteArrayInputStream(
116 (memory.getCell(instIndex++).toBitstring() + lineSeparator).getBytes(StandardCharsets.UTF_8));
117 val = instStream.read();