aboutsummaryrefslogtreecommitdiffstats
path: root/src/jogl/classes/jogamp/opengl/util/pngj/ProgressiveOutputStream.java
blob: bbec247fbf515453e027ecf9a8cceb96526bb0bd (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
package jogamp.opengl.util.pngj;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * stream that outputs to memory and allows to flush fragments every 'size' bytes to some other destination
 */
abstract class ProgressiveOutputStream extends ByteArrayOutputStream {
	private final int size;

	public ProgressiveOutputStream(int size) {
		this.size = size;
	}

	@Override
	public final void close() throws IOException {
		flush();
		super.close();
	}

	@Override
	public final void flush() throws IOException {
		super.flush();
		checkFlushBuffer(true);
	}

	@Override
	public final void write(byte[] b, int off, int len) {
		super.write(b, off, len);
		checkFlushBuffer(false);
	}

	@Override
	public final void write(byte[] b) throws IOException {
		super.write(b);
		checkFlushBuffer(false);
	}

	@Override
	public final void write(int arg0) {
		super.write(arg0);
		checkFlushBuffer(false);
	}

	@Override
	public final synchronized void reset() {
		super.reset();
	}

	/**
	 * if it's time to flush data (or if forced==true) calls abstract method flushBuffer() and cleans those bytes from
	 * own buffer
	 */
	private final void checkFlushBuffer(boolean forced) {
		while (forced || count >= size) {
			int nb = size;
			if (nb > count)
				nb = count;
			if (nb == 0)
				return;
			flushBuffer(buf, nb);
			int bytesleft = count - nb;
			count = bytesleft;
			if (bytesleft > 0)
				System.arraycopy(buf, nb, buf, 0, bytesleft);
		}
	}

	public abstract void flushBuffer(byte[] b, int n);
}