package com.github.mustachejava.util;

import com.github.mustachejava.MustacheException;
import java.io.IOException;
import java.io.Writer;
import java.util.concurrent.CountDownLatch;

/* JADX INFO: loaded from: classes.dex */
public class LatchedWriter extends Writer {
    private volatile Throwable e;
    private final Writer writer;
    private final CountDownLatch latch = new CountDownLatch(1);
    private final StringBuilder buffer = new StringBuilder();

    public LatchedWriter(Writer writer) {
        this.writer = writer;
    }

    public synchronized void done() throws IOException {
        this.writer.append((CharSequence) this.buffer);
        this.latch.countDown();
    }

    public void failed(Throwable th) {
        this.e = th;
        this.latch.countDown();
    }

    @Override // java.io.Writer
    public synchronized void write(char[] cArr, int i, int i2) throws IOException {
        checkException();
        if (this.latch.getCount() == 0) {
            this.writer.write(cArr, i, i2);
        } else {
            this.buffer.append(cArr, i, i2);
        }
    }

    private void checkException() throws IOException {
        if (this.e != null) {
            if (this.e instanceof IOException) {
                throw ((IOException) this.e);
            }
            throw new IOException(this.e);
        }
    }

    @Override // java.io.Writer, java.io.Flushable
    public void flush() throws IOException {
        checkException();
        if (this.latch.getCount() == 0) {
            synchronized (this) {
                this.writer.flush();
            }
        }
    }

    @Override // java.io.Writer, java.io.Closeable, java.lang.AutoCloseable
    public void close() throws IOException {
        checkException();
        await();
        flush();
        this.writer.close();
    }

    public void await() {
        try {
            this.latch.await();
        } catch (InterruptedException e) {
            throw new MustacheException("Interrupted while waiting for completion", e);
        }
    }
}
