1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.conscrypt;
18
19import java.io.ByteArrayOutputStream;
20
21public final class OpenSSLBIOSink {
22    private final long ctx;
23    private final ByteArrayOutputStream buffer;
24    private int position;
25
26    public static OpenSSLBIOSink create() {
27        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
28        return new OpenSSLBIOSink(buffer);
29    }
30
31    private OpenSSLBIOSink(ByteArrayOutputStream buffer) {
32        ctx = NativeCrypto.create_BIO_OutputStream(buffer);
33        this.buffer = buffer;
34    }
35
36    public int available() {
37        return buffer.size() - position;
38    }
39
40    public void reset() {
41        buffer.reset();
42        position = 0;
43    }
44
45    public long skip(long byteCount) {
46        int maxLength = Math.min(available(), (int) byteCount);
47        position += maxLength;
48        if (position == buffer.size()) {
49            reset();
50        }
51        return maxLength;
52    }
53
54    public long getContext() {
55        return ctx;
56    }
57
58    public byte[] toByteArray() {
59        return buffer.toByteArray();
60    }
61
62    public int position() {
63        return position;
64    }
65
66    @Override
67    protected void finalize() throws Throwable {
68        try {
69            NativeCrypto.BIO_free_all(ctx);
70        } finally {
71            super.finalize();
72        }
73    }
74}
75