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