001/* 002 * Shredzone Commons 003 * 004 * Copyright (C) 2014 Richard "Shred" Körber 005 * http://commons.shredzone.org 006 * 007 * This program is free software: you can redistribute it and/or modify 008 * it under the terms of the GNU Library General Public License as 009 * published by the Free Software Foundation, either version 3 of the 010 * License, or (at your option) any later version. 011 * 012 * This program is distributed in the hope that it will be useful, 013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 015 * GNU General Public License for more details. 016 * 017 * You should have received a copy of the GNU Library General Public License 018 * along with this program. If not, see <http://www.gnu.org/licenses/>. 019 */ 020package org.shredzone.commons.text.utils; 021 022import java.io.IOException; 023import java.io.Writer; 024 025import edu.umd.cs.findbugs.annotations.Nullable; 026 027/** 028 * A fast String writer that does not synchronize. 029 * 030 * @author Richard "Shred" Körber 031 */ 032public class FastStringWriter extends Writer { 033 034 private final StringBuilder sb; 035 036 /** 037 * Creates a new {@link FastStringWriter}. 038 */ 039 public FastStringWriter() { 040 sb = new StringBuilder(); 041 } 042 043 /** 044 * Creates a new {@link FastStringWriter}. 045 * 046 * @param capacity 047 * Initial capacity of the collector 048 */ 049 public FastStringWriter(int capacity) { 050 sb = new StringBuilder(capacity); 051 } 052 053 @Override 054 public void write(@Nullable char[] cbuf, int off, int len) throws IOException { 055 if (cbuf != null) { 056 sb.append(cbuf, off, len); 057 } 058 } 059 060 @Override 061 public void write(int c) throws IOException { 062 // superclass synchronizes 063 sb.append((char) c); 064 } 065 066 @Override 067 public void write(@Nullable String str, int off, int len) throws IOException { 068 // superclass synchronizes 069 if (str != null) { 070 sb.append(str, off, len); 071 } 072 } 073 074 @Override 075 public void flush() throws IOException { 076 // do nothing 077 } 078 079 @Override 080 public void close() throws IOException { 081 // do nothing 082 } 083 084 @Override 085 public String toString() { 086 return sb.toString(); 087 } 088 089 /** 090 * Returns a {@link StringBuilder} with the contents. 091 */ 092 public StringBuilder toStringBuilder() { 093 return sb; 094 } 095 096}