package com.atlassian.bitbucket.mesh.io;

import javax.annotation.Nullable;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;

import static java.util.Objects.requireNonNull;

public class NullTerminatedReader implements Closeable {

    private final BufferedReader reader;
    private final StringBuilder buffer;

    public NullTerminatedReader(BufferedReader reader) {
        this.reader = requireNonNull(reader, "reader");

        buffer = new StringBuilder();
    }

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

    @Nullable
    public String readSegment() throws IOException {
        buffer.setLength(0);
        int read;
        while ((read = reader.read()) != -1) {
            if (read == '\0') {
                break;
            }

            buffer.append((char) read);
        }
        if (read == -1) {
            return null;
        }
        return buffer.toString();
    }
}
