diff src/nabble/naml/compiler/BlockWrapper.java @ 0:7ecd1a4ef557

add content
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 21 Mar 2019 19:15:52 -0600
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/nabble/naml/compiler/BlockWrapper.java	Thu Mar 21 19:15:52 2019 -0600
@@ -0,0 +1,70 @@
+package nabble.naml.compiler;
+
+import java.io.StringWriter;
+import nabble.model.Init;
+
+
+class BlockWrapper {
+	private static final int blockWriterLimit = Init.get("blockWriterLimit",10 * 1024 * 1024);
+
+	private final Chunk block;
+	private final RunState runState;
+
+	BlockWrapper(Chunk block,RunState runState) {
+		this.block = block;
+		this.runState = runState;
+	}
+
+	private static class BlockWriter extends TemplatePrintWriter {
+		private final StringWriter sw;
+		private boolean isNull = false;
+
+		BlockWriter(StringWriter sw) {
+			super(sw);
+			this.sw = sw;
+		}
+
+		public void print(Object obj) {
+			if( obj == null && sw.getBuffer().length() == 0 && !isNull ) {
+				isNull = true;
+				return;
+			}
+			super.print(obj);
+			checkSize();
+		}
+
+		public void print(String s) {
+			if( s == null && sw.getBuffer().length() == 0 && !isNull ) {
+				isNull = true;
+				return;
+			}
+			super.print(s);
+			checkSize();
+		}
+
+		private void checkSize() {
+			if( sw.getBuffer().length() > blockWriterLimit )
+				throw new RuntimeException("BlockWriter too big");
+		}
+
+		String value() {
+			if( isNull ) {
+				if( sw.getBuffer().length() > 0 )
+					throw new NullPointerException("null written to stream");
+				return null;
+			}
+			return sw.toString();
+		}
+	}
+
+	public final String toString() {
+		BlockWriter out = new BlockWriter(new StringWriter());
+		printTo(out);
+		out.close();
+		return out.value();
+	}
+
+	void printTo(IPrintWriter out) {
+		block.run(out,runState);
+	}
+}