Debian Codegraph @

src/uk/me/parabola/io/FileBlock.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2016.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 3 or
6 * version 2 as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 */
13 package uk.me.parabola.io;
14
15 import java.io.ByteArrayOutputStream;
16 import java.io.IOException;
17 import java.io.OutputStream;
18
19 import uk.me.parabola.imgfmt.app.ImgFileWriter;
20 import uk.me.parabola.imgfmt.app.labelenc.CharacterEncoder;
21 import uk.me.parabola.imgfmt.app.labelenc.CodeFunctions;
22
23 /**
24 * A block forming part of a file.
25 *
26 * Used for TDB and MPS files. It will be read and written using the structured reader and
27 * writer defined in this package.
28 */
29 public abstract class FileBlock {
30 private final byte blockId;
31
32 private final ByteArrayOutputStream output = new ByteArrayOutputStream();
33
34 public FileBlock(int blockId) {
35 this.blockId = (byte) blockId;
36
37 fillHeader();
38 }
39
40 /**
41 * Write the body of the block.
42 */
43 protected abstract void writeBody(StructuredOutputStream output) throws IOException;
44
45 private StructuredOutputStream getStructuredOutput(int codePage) {
46 CharacterEncoder enc = CodeFunctions.createEncoderForLBL(0, codePage).getEncoder();
47 return new StructuredOutputStream(output, enc);
48 }
49
50 /**
51 * Write to an output stream.
52 *
53 * This version can write to a .img file.
54 */
55 public void writeTo(ImgFileWriter w, int codePage) throws IOException {
56 byte[] b = writeToCommon(codePage);
57 w.put(b);
58 }
59
60 /**
61 * Write to an output stream.
62 *
63 * This will be to the actual TDB file.
64 */
65 public void writeTo(OutputStream os, int codePage) throws IOException {
66 byte[] b = writeToCommon(codePage);
67 os.write(b);
68 }
69
70 private byte[] writeToCommon(int codePage) throws IOException {
71 writeBody(getStructuredOutput(codePage));
72
73 byte[] b = this.output.toByteArray();
74
75 // Fill in the actual full block length
76 int blockLength = b.length - 3;
77 b[1] = (byte) (blockLength & 0xff);
78 b[2] = (byte) ((blockLength >> 8) & 0xff);
79 return b;
80 }
81
82 /**
83 * Write the header to the internal buffer. The length may not be known yet and so is re-written later.
84 */
85 private void fillHeader() {
86 try {
87 byte[] b = new byte[3];
88 b[0] = this.blockId;
89
90 output.write(b);
91 } catch (IOException ignore) {
92 // does not throw
93 }
94 }
95 }