001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one or more
003 *  contributor license agreements.  See the NOTICE file distributed with
004 *  this work for additional information regarding copyright ownership.
005 *  The ASF licenses this file to You under the Apache License, Version 2.0
006 *  (the "License"); you may not use this file except in compliance with
007 *  the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 *  Unless required by applicable law or agreed to in writing, software
012 *  distributed under the License is distributed on an "AS IS" BASIS,
013 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 *  See the License for the specific language governing permissions and
015 *  limitations under the License.
016 */
017package org.apache.commons.compress.utils;
018
019import java.io.IOException;
020import java.nio.ByteBuffer;
021import java.nio.channels.SeekableByteChannel;
022
023/**
024 * InputStream that delegates requests to the underlying SeekableByteChannel, making sure that only bytes from a certain range can be read.
025 *
026 * @ThreadSafe
027 * @since 1.21
028 */
029public class BoundedSeekableByteChannelInputStream extends BoundedArchiveInputStream {
030
031    private final SeekableByteChannel channel;
032
033    /**
034     * Constructs a bounded stream on the underlying {@link SeekableByteChannel}
035     *
036     * @param start     Position in the stream from where the reading of this bounded stream starts
037     * @param remaining Amount of bytes which are allowed to read from the bounded stream
038     * @param channel   Channel which the reads will be delegated to
039     */
040    public BoundedSeekableByteChannelInputStream(final long start, final long remaining, final SeekableByteChannel channel) {
041        super(start, remaining);
042        this.channel = channel;
043    }
044
045    @Override
046    protected int read(final long pos, final ByteBuffer buf) throws IOException {
047        int read;
048        synchronized (channel) {
049            channel.position(pos);
050            read = channel.read(buf);
051        }
052        buf.flip();
053        return read;
054    }
055}