aboutsummaryrefslogtreecommitdiffstats
path: root/src/org/apache/fop/render/ps/ASCIIHexOutputStream.java
blob: 34b2c51922f4f291d938361359b576e89a48ed29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
 * $Id$
 * Copyright (C) 2002 The Apache Software Foundation. All rights reserved.
 * For details on use and redistribution please refer to the
 * LICENSE file included with these sources.
 */
package org.apache.fop.render.ps;

import java.io.OutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;

/**
 * This class applies a ASCII Hex encoding to the stream.
 *
 * @author <a href="mailto:jeremias.maerki@outline.ch">Jeremias Maerki</a>
 * @version $Id$
 */
public class ASCIIHexOutputStream extends FilterOutputStream
        implements Finalizable {

    private static final int EOL   = 0x0A; //"\n"
    private static final int EOD   = 0x3E; //">"
    private static final int ZERO  = 0x30; //"0"
    private static final int NINE  = 0x39; //"9"
    private static final int A     = 0x41; //"A"
    private static final int ADIFF = A - NINE - 1;

    private int posinline = 0;


    /** @see java.io.FilterOutputStream **/
    public ASCIIHexOutputStream(OutputStream out) {
        super(out);
    }


    /** @see java.io.FilterOutputStream **/
    public void write(int b) throws IOException {
        b &= 0xFF;

        int digit1 = ((b & 0xF0) >> 4) + ZERO;
        if (digit1 > NINE) {
            digit1 += ADIFF;
        }
        out.write(digit1);

        int digit2 = (b & 0x0F) + ZERO;
        if (digit2 > NINE) {
            digit2 += ADIFF;
        }
        out.write(digit2);

        posinline++;
        checkLineWrap();
    }


    private void checkLineWrap() throws IOException {
        //Maximum line length is 80 characters
        if (posinline >= 40) {
            out.write(EOL);
            posinline = 0;
        }
    }


    /** @see org.apache.fop.render.ps.Finalizable **/
    public void finalizeStream() throws IOException {
        checkLineWrap();
        //Write closing character ">"
        super.write(EOD);

        flush();
        if (out instanceof Finalizable) {
            ((Finalizable) out).finalizeStream();
        }
    }


    /** @see java.io.FilterOutputStream **/
    public void close() throws IOException {
        finalizeStream();
        super.close();
    }


}