1/****************************************************************
2 * Licensed to the Apache Software Foundation (ASF) under one   *
3 * or more contributor license agreements.  See the NOTICE file *
4 * distributed with this work for additional information        *
5 * regarding copyright ownership.  The ASF licenses this file   *
6 * to you under the Apache License, Version 2.0 (the            *
7 * "License"); you may not use this file except in compliance   *
8 * with the License.  You may obtain a copy of the License at   *
9 *                                                              *
10 *   http://www.apache.org/licenses/LICENSE-2.0                 *
11 *                                                              *
12 * Unless required by applicable law or agreed to in writing,   *
13 * software distributed under the License is distributed on an  *
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
15 * KIND, either express or implied.  See the License for the    *
16 * specific language governing permissions and limitations      *
17 * under the License.                                           *
18 ****************************************************************/
19
20
21package org.apache.james.mime4j.util;
22
23import java.io.InputStream;
24import java.io.IOException;
25
26public class PartialInputStream extends PositionInputStream {
27    private final long limit;
28
29    public PartialInputStream(InputStream inputStream, long offset, long length) throws IOException {
30        super(inputStream);
31        inputStream.skip(offset);
32        this.limit = offset + length;
33    }
34
35    public int available() throws IOException {
36        return Math.min(super.available(), getBytesLeft());
37    }
38
39    public int read() throws IOException {
40        if (limit > position)
41            return super.read();
42        else
43            return -1;
44    }
45
46    public int read(byte b[]) throws IOException {
47        return read(b, 0, b.length);
48    }
49
50    public int read(byte b[], int off, int len) throws IOException {
51        len = Math.min(len, getBytesLeft());
52        return super.read(b, off, len);    //To change body of overridden methods use File | Settings | File Templates.
53    }
54
55    public long skip(long n) throws IOException {
56        n = Math.min(n, getBytesLeft());
57        return super.skip(n);    //To change body of overridden methods use File | Settings | File Templates.
58    }
59
60    private int getBytesLeft() {
61        return (int)Math.min(Integer.MAX_VALUE, limit - position);
62    }
63}
64