| 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.fs; |
| 7 |
|
| 8 |
import java.io.IOException; |
| 9 |
import java.nio.ByteBuffer; |
| 10 |
import java.nio.channels.FileChannel; |
| 11 |
|
| 12 |
/** |
| 13 |
* Default implementation of the slow operations that need synchronization because they |
| 14 |
* involve the file position. |
| 15 |
*/ |
| 16 |
public abstract class FileBaseDefault extends FileBase { |
| 17 |
|
| 18 |
private long position = 0; |
| 19 |
|
| 20 |
@Override |
| 21 |
public final synchronized long position() throws IOException { |
| 22 |
return position; |
| 23 |
} |
| 24 |
|
| 25 |
@Override |
| 26 |
public final synchronized FileChannel position(long newPosition) throws IOException { |
| 27 |
if (newPosition < 0) { |
| 28 |
throw new IllegalArgumentException(); |
| 29 |
} |
| 30 |
position = newPosition; |
| 31 |
return this; |
| 32 |
} |
| 33 |
|
| 34 |
@Override |
| 35 |
public final synchronized int read(ByteBuffer dst) throws IOException { |
| 36 |
int read = read(dst, position); |
| 37 |
if (read > 0) { |
| 38 |
position += read; |
| 39 |
} |
| 40 |
return read; |
| 41 |
} |
| 42 |
|
| 43 |
@Override |
| 44 |
public final synchronized int write(ByteBuffer src) throws IOException { |
| 45 |
int written = write(src, position); |
| 46 |
if (written > 0) { |
| 47 |
position += written; |
| 48 |
} |
| 49 |
return written; |
| 50 |
} |
| 51 |
|
| 52 |
@Override |
| 53 |
public final synchronized FileChannel truncate(long newLength) throws IOException { |
| 54 |
implTruncate(newLength); |
| 55 |
if (newLength < position) { |
| 56 |
position = newLength; |
| 57 |
} |
| 58 |
return this; |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* The truncate implementation. |
| 63 |
* |
| 64 |
* @param size the new size |
| 65 |
* @throws IOException on failure |
| 66 |
*/ |
| 67 |
protected abstract void implTruncate(long size) throws IOException; |
| 68 |
} |