jtulach@67: package api; jtulach@67: jtulach@67: import java.io.IOException; jtulach@67: jtulach@67: /** jtulach@67: * jtulach@67: * @author Jaroslav Tulach jtulach@67: */ jtulach@67: final class SimpleBuffer implements Writer.ImplSeq { jtulach@67: private final Writer out; jtulach@67: private final StringBuffer sb = new StringBuffer(); jtulach@67: jtulach@67: public SimpleBuffer(Writer out) { jtulach@67: this.out = out; jtulach@67: } jtulach@67: jtulach@67: public void close() throws IOException { jtulach@67: flush(); jtulach@67: out.close(); jtulach@67: } jtulach@67: jtulach@67: public void flush() throws IOException { jtulach@67: if (sb.length() > 0) { jtulach@67: out.write(sb.toString()); jtulach@67: sb.setLength(0); jtulach@67: out.flush(); jtulach@67: } jtulach@67: } jtulach@67: jtulach@67: public void write(CharSequence seq) throws IOException { jtulach@210: if (shouldBufferAsTheSequenceIsNotTooBig(seq)) { jtulach@67: sb.append(seq); jtulach@67: } else { jtulach@67: flush(); jtulach@67: out.append(seq); jtulach@67: } jtulach@67: } jtulach@67: jtulach@210: /** At the end the purpose of BufferedWriter is to buffer writes, this jtulach@210: * method is here to decide when it is OK to prefer buffering and when jtulach@210: * it is better to delegate directly into the underlaying stream. jtulach@210: * jtulach@210: * @param csq the seqence to evaluate jtulach@210: * @return true if buffering from super class should be used jtulach@210: */ jtulach@210: private static boolean shouldBufferAsTheSequenceIsNotTooBig(CharSequence csq) { jtulach@210: if (csq == null) { jtulach@210: return false; jtulach@210: } jtulach@210: // as buffers are usually bigger than 1024, it makes sense to jtulach@210: // pay the penalty of converting the sequence to string, but buffering jtulach@210: // the write jtulach@210: if (csq.length() < 1024) { jtulach@210: return true; jtulach@210: } else { jtulach@210: // otherwise, just directly write down the char sequence jtulach@210: return false; jtulach@210: } jtulach@210: } jtulach@210: jtulach@67: }