Debian Codegraph @

morfologik-fsa/src/main/java/morfologik/fsa/FSAHeader.java

raw symbols SCIP
1 package morfologik.fsa;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.OutputStream;
6
7 /**
8 * Standard FSA file header, as described in <code>fsa</code> package
9 * documentation.
10 */
11 public final class FSAHeader {
12 /**
13 * FSA magic (4 bytes).
14 */
15 final static int FSA_MAGIC =
16 ('\\' << 24) |
17 ('f' << 16) |
18 ('s' << 8) |
19 ('a');
20
21 /**
22 * Maximum length of the header block.
23 */
24 static final int MAX_HEADER_LENGTH = 4 + 8;
25
26 /** FSA version number. */
27 final byte version;
28
29 FSAHeader(byte version) {
30 this.version = version;
31 }
32
33 /**
34 * Read FSA header and version from a stream, consuming read bytes.
35 *
36 * @param in The input stream to read data from.
37 * @return Returns a valid {@link FSAHeader} with version information.
38 * @throws IOException If the stream ends prematurely or if it contains invalid data.
39 */
40 public static FSAHeader read(InputStream in) throws IOException {
41 if (in.read() != ((FSA_MAGIC >>> 24) ) ||
42 in.read() != ((FSA_MAGIC >>> 16) & 0xff) ||
43 in.read() != ((FSA_MAGIC >>> 8) & 0xff) ||
44 in.read() != ((FSA_MAGIC ) & 0xff)) {
45 throw new IOException("Invalid file header, probably not an FSA.");
46 }
47
48 int version = in.read();
49 if (version == -1) {
50 throw new IOException("Truncated file, no version number.");
51 }
52
53 return new FSAHeader((byte) version);
54 }
55
56 /**
57 * Writes FSA magic bytes and version information.
58 *
59 * @param os The stream to write to.
60 * @param version Automaton version.
61 * @throws IOException Rethrown if writing fails.
62 */
63 public static void write(OutputStream os, byte version) throws IOException {
64 os.write(FSA_MAGIC >> 24);
65 os.write(FSA_MAGIC >> 16);
66 os.write(FSA_MAGIC >> 8);
67 os.write(FSA_MAGIC);
68 os.write(version);
69 }
70 }