| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package org.tukaani.xz; |
| 6 |
|
| 7 |
import java.io.IOException; |
| 8 |
import org.tukaani.xz.delta.DeltaEncoder; |
| 9 |
|
| 10 |
class DeltaOutputStream extends FinishableOutputStream { |
| 11 |
private static final int FILTER_BUF_SIZE = 4096; |
| 12 |
|
| 13 |
private FinishableOutputStream out; |
| 14 |
private final DeltaEncoder delta; |
| 15 |
private final byte[] filterBuf = new byte[FILTER_BUF_SIZE]; |
| 16 |
|
| 17 |
private boolean finished = false; |
| 18 |
private IOException exception = null; |
| 19 |
|
| 20 |
private final byte[] tempBuf = new byte[1]; |
| 21 |
|
| 22 |
static int getMemoryUsage() { |
| 23 |
return 1 + FILTER_BUF_SIZE / 1024; |
| 24 |
} |
| 25 |
|
| 26 |
DeltaOutputStream(FinishableOutputStream out, DeltaOptions options) { |
| 27 |
this.out = out; |
| 28 |
delta = new DeltaEncoder(options.getDistance()); |
| 29 |
} |
| 30 |
|
| 31 |
@Override |
| 32 |
public void write(int b) throws IOException { |
| 33 |
tempBuf[0] = (byte)b; |
| 34 |
write(tempBuf, 0, 1); |
| 35 |
} |
| 36 |
|
| 37 |
@Override |
| 38 |
public void write(byte[] buf, int off, int len) throws IOException { |
| 39 |
if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length) |
| 40 |
throw new IndexOutOfBoundsException(); |
| 41 |
|
| 42 |
if (exception != null) |
| 43 |
throw exception; |
| 44 |
|
| 45 |
if (finished) |
| 46 |
throw new XZIOException("Stream finished"); |
| 47 |
|
| 48 |
try { |
| 49 |
while (len > FILTER_BUF_SIZE) { |
| 50 |
delta.encode(buf, off, FILTER_BUF_SIZE, filterBuf); |
| 51 |
out.write(filterBuf); |
| 52 |
off += FILTER_BUF_SIZE; |
| 53 |
len -= FILTER_BUF_SIZE; |
| 54 |
} |
| 55 |
|
| 56 |
delta.encode(buf, off, len, filterBuf); |
| 57 |
out.write(filterBuf, 0, len); |
| 58 |
} catch (IOException e) { |
| 59 |
exception = e; |
| 60 |
throw e; |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
@Override |
| 65 |
public void flush() throws IOException { |
| 66 |
if (exception != null) |
| 67 |
throw exception; |
| 68 |
|
| 69 |
if (finished) |
| 70 |
throw new XZIOException("Stream finished or closed"); |
| 71 |
|
| 72 |
try { |
| 73 |
out.flush(); |
| 74 |
} catch (IOException e) { |
| 75 |
exception = e; |
| 76 |
throw e; |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
@Override |
| 81 |
public void finish() throws IOException { |
| 82 |
if (!finished) { |
| 83 |
if (exception != null) |
| 84 |
throw exception; |
| 85 |
|
| 86 |
try { |
| 87 |
out.finish(); |
| 88 |
} catch (IOException e) { |
| 89 |
exception = e; |
| 90 |
throw e; |
| 91 |
} |
| 92 |
|
| 93 |
finished = true; |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
@Override |
| 98 |
public void close() throws IOException { |
| 99 |
if (out != null) { |
| 100 |
try { |
| 101 |
out.close(); |
| 102 |
} catch (IOException e) { |
| 103 |
if (exception == null) |
| 104 |
exception = e; |
| 105 |
} |
| 106 |
|
| 107 |
out = null; |
| 108 |
} |
| 109 |
|
| 110 |
if (exception != null) |
| 111 |
throw exception; |
| 112 |
} |
| 113 |
} |