aboutsummaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/io/LazyInputStream.java
blob: 0f084870de299dc03fd1b1b770600aadd3846081 (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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.io;

import java.io.IOException;
import java.io.InputStream;
import java.util.function.Supplier;

/**
 * Input stream wrapping an input stream supplier, which doesn't have content yet at declaration time.
 *
 * @author jonmv
 */
public class LazyInputStream extends InputStream {

    private Supplier<InputStream> source;
    private InputStream delegate;

    public LazyInputStream(Supplier<InputStream> source) {
        this.source = source;
    }

    private InputStream in() {
        if (delegate == null) {
            delegate = source.get();
            source = null;
        }
        return delegate;
    }

    @Override
    public int read() throws IOException { return in().read(); }

    @Override
    public int read(byte[] b, int off, int len) throws IOException { return in().read(b, off, len); }

    @Override
    public long skip(long n) throws IOException { return in().skip(n); }

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

    @Override
    public void close() throws IOException { in().close(); }

    @Override
    public synchronized void mark(int readlimit) { in().mark(readlimit); }

    @Override
    public synchronized void reset() throws IOException { in().reset(); }

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

}