| 1 | // SPDX-License-Identifier: 0BSD |
| 2 | // SPDX-FileCopyrightText: The XZ for Java authors and contributors |
| 3 | // SPDX-FileContributor: Lasse Collin <[email protected]> |
| 4 | |
| 5 | package org.tukaani.xz; |
| 6 | |
| 7 | import java.io.InputStream; |
| 8 | import java.io.IOException; |
| 9 | |
| 10 | /** |
| 11 | * Input stream with random access support. |
| 12 | */ |
| 13 | public abstract class SeekableInputStream extends InputStream { |
| 14 | /** |
| 15 | * Seeks {@code n} bytes forward in this stream. |
| 16 | * <p> |
| 17 | * This will not seek past the end of the file. If the current position |
| 18 | * is already at or past the end of the file, this doesn't seek at all |
| 19 | * and returns {@code 0}. Otherwise, if skipping {@code n} bytes |
| 20 | * would cause the position to exceed the stream size, this will do |
| 21 | * equivalent of {@code seek(length())} and the return value will |
| 22 | * be adjusted accordingly. |
| 23 | * <p> |
| 24 | * If {@code n} is negative, the position isn't changed and |
| 25 | * the return value is {@code 0}. It doesn't seek backward |
| 26 | * because it would conflict with the specification of |
| 27 | * {@link java.io.InputStream#skip(long) InputStream.skip}. |
| 28 | * |
| 29 | * @return {@code 0} if {@code n} is negative, |
| 30 | * less than {@code n} if skipping {@code n} |
| 31 | * bytes would seek past the end of the file, |
| 32 | * {@code n} otherwise |
| 33 | * |
| 34 | * @throws IOException might be thrown by {@link #seek(long)} |
| 35 | */ |
| 36 | public long skip(long n) throws IOException { |
| 37 | if (n <= 0) |
| 38 | return 0; |
| 39 | |
| 40 | long size = length(); |
| 41 | long pos = position(); |
| 42 | if (pos >= size) |
| 43 | return 0; |
| 44 | |
| 45 | if (size - pos < n) |
| 46 | n = size - pos; |
| 47 | |
| 48 | seek(pos + n); |
| 49 | return n; |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * Gets the size of the stream. |
| 54 | */ |
| 55 | public abstract long length() throws IOException; |
| 56 | |
| 57 | /** |
| 58 | * Gets the current position in the stream. |
| 59 | */ |
| 60 | public abstract long position() throws IOException; |
| 61 | |
| 62 | /** |
| 63 | * Seeks to the specified absolute position in the stream. |
| 64 | * <p> |
| 65 | * Seeking past the end of the file should be supported by the subclasses |
| 66 | * unless there is a good reason to do otherwise. If one has seeked |
| 67 | * past the end of the stream, {@code read} will return |
| 68 | * {@code -1} to indicate end of stream. |
| 69 | * |
| 70 | * @param pos new read position in the stream |
| 71 | * |
| 72 | * @throws IOException if {@code pos} is negative or if |
| 73 | * a stream-specific I/O error occurs |
| 74 | */ |
| 75 | public abstract void seek(long pos) throws IOException; |
| 76 | } |