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
20 import eu.simuline.octave.exception.OctaveParseException;
21
22 import eu.simuline.octave.io.OctaveIO;
23
24 import eu.simuline.octave.io.spi.OctaveDataReader;
25 import eu.simuline.octave.type.OctaveSparseBoolean;
26 import eu.simuline.octave.util.StringUtil;
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 public final class SparseBooleanReader extends OctaveDataReader {
42
43 @Override
44 public String octaveType() {
45 return "sparse bool matrix";
46 }
47
48
49
50
51 @Override
52 @SuppressWarnings("checkstyle:magicnumber")
53
54
55 public OctaveSparseBoolean read(final BufferedReader reader) {
56 final int nnz = parseHeader("# nnz: ",
57 OctaveIO.readerReadLine(reader));
58 final int rows = parseHeader("# rows: ",
59 OctaveIO.readerReadLine(reader));
60 final int columns = parseHeader("# columns: ",
61 OctaveIO.readerReadLine(reader));
62
63 final OctaveSparseBoolean sparse =
64 new OctaveSparseBoolean(rows, columns, nnz);
65 for (int n = 0; n < nnz; ++n) {
66 final String line = OctaveIO.readerReadLine(reader);
67 final String[] split = line.split(" ");
68 if (split.length != 3) {
69 throw new OctaveParseException("split.length != 3");
70 }
71 try {
72 final int row = Integer.parseInt(split[0]);
73 final int column = Integer.parseInt(split[1]);
74 final boolean value = StringUtil.parseBoolean(split[2]);
75 sparse.set(value, row, column);
76 } catch (final NumberFormatException e) {
77 throw new OctaveParseException(e);
78 }
79 }
80
81 return sparse;
82 }
83
84 private int parseHeader(final String prefix, final String line) {
85 if (line == null || !line.startsWith(prefix)) {
86 throw new OctaveParseException
87 ("Expected a line that should start with '" + prefix +
88 "', got '" + line + "'");
89 }
90 try {
91 return Integer.parseInt(line.substring(prefix.length()));
92 } catch (final NumberFormatException e) {
93 throw new OctaveParseException(e);
94 }
95 }
96
97 }