dev.codeflush.baseencoder.BaseEncoder Maven / Gradle / Ivy
 The newest version!
        
        package dev.codeflush.baseencoder;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
public class BaseEncoder extends OutputStream {
    private final BaseEncoding encoding;
    private final Writer out;
    private int bitBlockIndex;
    private int charIndex;
    public BaseEncoder(BaseEncoding encoding, Writer out) {
        this.encoding = encoding;
        this.out = out;
        this.bitBlockIndex = 0;
        this.charIndex = 0;
    }
    @Override
    public void write(int b) throws IOException {
        consume((byte) b);
    }
    @Override
    public void write(byte[] bytes) throws IOException {
        write(bytes, 0, bytes.length);
    }
    @Override
    public void write(byte[] bytes, int offset, int length) throws IOException {
        for (int i = 0; i < length; i++) {
            consume(bytes[offset + i]);
        }
    }
    @Override
    public void flush() throws IOException {
        this.out.flush();
    }
    @Override
    public void close() throws IOException {
        if (this.bitBlockIndex > 0) {
            this.out.write(this.encoding.get(this.charIndex));
        }
        this.out.close();
    }
    private void consume(byte b) throws IOException {
        for (int bitIndex = Byte.SIZE - 1; bitIndex >= 0; bitIndex--) {
            if (getBit(b, bitIndex)) {
                this.charIndex |= 1 << (this.encoding.bitBlockSize() - this.bitBlockIndex - 1);
            }
            this.bitBlockIndex++;
            if (this.bitBlockIndex >= this.encoding.bitBlockSize()) {
                this.out.write(this.encoding.get(this.charIndex));
                this.bitBlockIndex = 0;
                this.charIndex = 0;
            }
        }
    }
    private static boolean getBit(byte b, int n) {
        return (b & (1 << n)) != 0;
    }
}
    © 2015 - 2025 Weber Informatics LLC | Privacy Policy