| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.store; |
| 7 |
|
| 8 |
import java.io.OutputStream; |
| 9 |
import java.util.Arrays; |
| 10 |
|
| 11 |
import org.h2.engine.Constants; |
| 12 |
import org.h2.tools.CompressTool; |
| 13 |
|
| 14 |
/** |
| 15 |
* An output stream that is backed by a file store. |
| 16 |
*/ |
| 17 |
public class FileStoreOutputStream extends OutputStream { |
| 18 |
private FileStore store; |
| 19 |
private final Data page; |
| 20 |
private final String compressionAlgorithm; |
| 21 |
private final CompressTool compress; |
| 22 |
private final byte[] buffer = { 0 }; |
| 23 |
|
| 24 |
public FileStoreOutputStream(FileStore store, String compressionAlgorithm) { |
| 25 |
this.store = store; |
| 26 |
if (compressionAlgorithm != null) { |
| 27 |
this.compress = CompressTool.getInstance(); |
| 28 |
this.compressionAlgorithm = compressionAlgorithm; |
| 29 |
} else { |
| 30 |
this.compress = null; |
| 31 |
this.compressionAlgorithm = null; |
| 32 |
} |
| 33 |
page = Data.create(Constants.FILE_BLOCK_SIZE); |
| 34 |
} |
| 35 |
|
| 36 |
@Override |
| 37 |
public void write(int b) { |
| 38 |
buffer[0] = (byte) b; |
| 39 |
write(buffer); |
| 40 |
} |
| 41 |
|
| 42 |
@Override |
| 43 |
public void write(byte[] buff) { |
| 44 |
write(buff, 0, buff.length); |
| 45 |
} |
| 46 |
|
| 47 |
@Override |
| 48 |
public void write(byte[] buff, int off, int len) { |
| 49 |
if (len > 0) { |
| 50 |
page.reset(); |
| 51 |
if (compress != null) { |
| 52 |
if (off != 0 || len != buff.length) { |
| 53 |
buff = Arrays.copyOfRange(buff, off, off + len); |
| 54 |
off = 0; |
| 55 |
} |
| 56 |
int uncompressed = len; |
| 57 |
buff = compress.compress(buff, compressionAlgorithm); |
| 58 |
len = buff.length; |
| 59 |
page.checkCapacity(2 * Integer.BYTES + len); |
| 60 |
page.writeInt(len); |
| 61 |
page.writeInt(uncompressed); |
| 62 |
page.write(buff, off, len); |
| 63 |
} else { |
| 64 |
page.checkCapacity(Integer.BYTES + len); |
| 65 |
page.writeInt(len); |
| 66 |
page.write(buff, off, len); |
| 67 |
} |
| 68 |
page.fillAligned(); |
| 69 |
store.write(page.getBytes(), 0, page.length()); |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
@Override |
| 74 |
public void close() { |
| 75 |
if (store != null) { |
| 76 |
try { |
| 77 |
store.close(); |
| 78 |
} finally { |
| 79 |
store = null; |
| 80 |
} |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
} |