aboutsummaryrefslogtreecommitdiffstats
path: root/vespaclient-container-plugin/src/main/java/com/yahoo/vespa/http/server/util/ByteLimitedInputStream.java
blob: 52c97213a84d0662471d2c1a22feebd808777adf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.http.server.util;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Einar M R Rosenvinge
 */
public class ByteLimitedInputStream extends InputStream {

    private final InputStream wrappedStream;
    private int remaining;
    private int remainingWhenMarked;

    public ByteLimitedInputStream(InputStream wrappedStream, int limit) {
        this.wrappedStream = wrappedStream;
        if (limit < 0) {
            throw new IllegalArgumentException("limit cannot be 0");
        }
        this.remaining = limit;
    }

    @Override
    public int read() throws IOException {
        if (remaining <= 0) {
            return -1;
        }
        int retval = wrappedStream.read();
        if (retval < 0) {
            remaining = 0;
        } else {
            --remaining;
        }
        return retval;
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        if (b == null) {
            throw new NullPointerException();
        } else if (off < 0 || len < 0 || len > b.length - off) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return 0;
        }

        if (remaining <= 0) {
            return -1;
        }

        int bytesToRead = Math.min(remaining, len);
        int retval = wrappedStream.read(b, off, bytesToRead);

        if (retval < 0) {
            //end of underlying stream was reached, and nothing was read.
            remaining = 0;
        } else {
            remaining -= retval;
        }
        return retval;
    }

    @Override
    public int available() throws IOException {
        return remaining;
    }

    @Override
    public void close() throws IOException {
        //we will never close the underlying stream
        if (remaining <= 0) {
            return;
        }
        while (remaining > 0) {
            skip(remaining);
        }
    }

    @Override
    public synchronized void mark(int readlimit) {
        wrappedStream.mark(readlimit);
        remainingWhenMarked = remaining;
    }

    @Override
    public synchronized void reset() throws IOException {
        wrappedStream.reset();
        remaining = remainingWhenMarked;
    }

    @Override
    public boolean markSupported() {
        return wrappedStream.markSupported();
    }

}