001/*
002 * Copyright (C) 2009-2020 the original author(s).
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.fusesource.jansi.io;
017
018import java.io.FilterOutputStream;
019import java.io.IOException;
020import java.io.OutputStream;
021
022/**
023 * A simple buffering output stream with no synchronization.
024 */
025public class FastBufferedOutputStream extends FilterOutputStream {
026
027    protected final byte buf[] = new byte[8192];
028    protected int count;
029
030    public FastBufferedOutputStream(OutputStream out) {
031        super(out);
032    }
033
034    @Override
035    public void write(int b) throws IOException {
036        if (count >= buf.length) {
037            flushBuffer();
038        }
039        buf[count++] = (byte) b;
040    }
041
042    @Override
043    public void write(byte b[], int off, int len) throws IOException {
044        if (len >= buf.length) {
045            flushBuffer();
046            out.write(b, off, len);
047            return;
048        }
049        if (len > buf.length - count) {
050            flushBuffer();
051        }
052        System.arraycopy(b, off, buf, count, len);
053        count += len;
054    }
055
056    private void flushBuffer() throws IOException {
057        if (count > 0) {
058            out.write(buf, 0, count);
059            count = 0;
060        }
061    }
062
063    @Override
064    public void flush() throws IOException {
065        flushBuffer();
066        out.flush();
067    }
068
069}