    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
    025 * range can be read.
    026 * @ThreadSafe
    027 * @since 1.21
    028 */
    029public class BoundedSeekableByteChannelInputStream extends BoundedArchiveInputStream {
    030
    031    private final SeekableByteChannel channel;
    032
    033    /**
    034     * Create 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,
    041            final SeekableByteChannel channel) {
    042        super(start, remaining);
    043        this.channel = channel;
    044    }
    045
    046    @Override
    047    protected int read(final long pos, final ByteBuffer buf) throws IOException {
    048        int read;
    049        synchronized (channel) {
    050            channel.position(pos);
    051            read = channel.read(buf);
    052        }
    053        buf.flip();
    054        return read;
    055    }
    056}