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 *
017 */
018package org.apache.commons.compress.utils;
019
020import java.io.IOException;
021import java.nio.ByteBuffer;
022import java.nio.channels.SeekableByteChannel;
023
024/**
025 * InputStream that delegates requests to the underlying SeekableByteChannel, making sure that only bytes from a certain
026 * range can be read.
027 * @ThreadSafe
028 * @since 1.21
029 */
030public class BoundedSeekableByteChannelInputStream extends BoundedArchiveInputStream {
031
032    private final SeekableByteChannel channel;
033
034    /**
035     * Create a bounded stream on the underlying {@link SeekableByteChannel}
036     *
037     * @param start     Position in the stream from where the reading of this bounded stream starts
038     * @param remaining Amount of bytes which are allowed to read from the bounded stream
039     * @param channel   Channel which the reads will be delegated to
040     */
041    public BoundedSeekableByteChannelInputStream(final long start, final long remaining,
042            final SeekableByteChannel channel) {
043        super(start, remaining);
044        this.channel = channel;
045    }
046
047    @Override
048    protected int read(long pos, ByteBuffer buf) throws IOException {
049        int read;
050        synchronized (channel) {
051            channel.position(pos);
052            read = channel.read(buf);
053        }
054        buf.flip();
055        return read;
056    }
057}