1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package eu.simuline.octave.io.impl;
17
18 import java.io.BufferedReader;
19 import java.util.HashMap;
20 import java.util.Map;
21
22 import eu.simuline.octave.exception.OctaveParseException;
23 import eu.simuline.octave.io.OctaveIO;
24 import eu.simuline.octave.io.spi.OctaveDataReader;
25 import eu.simuline.octave.type.OctaveCell;
26 import eu.simuline.octave.type.OctaveObject;
27 import eu.simuline.octave.type.OctaveStruct;
28
29 import static eu.simuline.octave.io.impl.StructWriter.LENGTH;
30 import static eu.simuline.octave.io.impl.StructWriter.NAME;
31 import static eu.simuline.octave.io.impl.StructWriter.TYPE_CELL;
32
33
34
35
36
37
38 public final class StructReader extends OctaveDataReader {
39 private static final String N_DIMS2 = "# ndims: 2";
40 private static final String V_DIMS2 = " 1 1";
41
42 private static final CellReaderder.html#CellReader">CellReader CELL_READER = new CellReader();
43
44 @Override
45 public String octaveType() {
46 return "struct";
47 }
48
49 @Override
50 @SuppressWarnings("PMD.NPathComplexity")
51 public OctaveStruct read(final BufferedReader reader) {
52 String line = OctaveIO.readerReadLine(reader);
53
54
55 if (line != null && line.startsWith("# ndims:")) {
56 if (!N_DIMS2.equals(line)) {
57 throw new OctaveParseException
58 ("JavaOctave does not support matrix structs, read '" +
59 line + "'");
60 }
61
62
63 line = OctaveIO.readerReadLine(reader);
64 if (!V_DIMS2.equals(line)) {
65 throw new OctaveParseException
66 ("JavaOctave does not support matrix structs, read '" +
67 line + "'");
68 }
69 line = OctaveIO.readerReadLine(reader);
70 }
71
72
73
74 if (line == null || !line.startsWith(LENGTH)) {
75 throw new OctaveParseException
76 ("Expected <" + LENGTH + "> got <" + line + ">. ");
77 }
78 final int length = Integer.parseInt(line.substring(LENGTH.length()));
79
80
81 final Map<String, OctaveObject> data =
82 new HashMap<String, OctaveObject>();
83
84 for (int i = 0; i < length; i++) {
85
86
87
88
89 do {
90 line = OctaveIO.readerReadLine(reader);
91 } while ("".equals(line));
92 if (!line.startsWith(NAME)) {
93 throw new OctaveParseException
94 ("Expected <" + NAME + "> got <" + line + ">. ");
95 }
96 final String subname = line.substring(NAME.length());
97
98
99
100
101 line = OctaveIO.readerReadLine(reader);
102 if (!line.equals(TYPE_CELL)) {
103 throw new OctaveParseException
104 ("Expected '" + TYPE_CELL + "' got '" + line + "'");
105 }
106
107 final OctaveCell cell = CELL_READER.read(reader);
108 if (cell.getSize(1) != 1 || cell.getSize(2) != 1) {
109 throw new OctaveParseException
110 ("JavaOctave does not support matrix structs, size="
111 + cell.getSize(1) + " " + cell.getSize(2) + "...");
112 }
113
114
115 final OctaveObject value = cell.get(1, 1);
116 data.put(subname, value);
117 }
118
119 return new OctaveStruct(data);
120 }
121
122 }