001package io.jstach.jstachio;
002
003import java.io.IOException;
004import java.io.UncheckedIOException;
005
006/**
007 * Renders models of type {@code T} by writing to an Appendable. <em>Implementations
008 * should be generally stateless and threadsafe.</em>
009 *
010 * @param <T> the model type
011 */
012@FunctionalInterface
013public interface Renderer<T> {
014
015        /**
016         * Renders the passed in model.
017         * @param model a model assumed never to be <code>null</code>.
018         * @param appendable the appendable to write to.
019         * @throws IOException if there is an error writing to the appendable
020         */
021        public void execute(T model, Appendable appendable) throws IOException;
022
023        /**
024         * A convenience method that does not throw {@link IOException} when using
025         * StringBuilder.
026         * @param model a model assumed never to be null.
027         * @param sb should never be null.
028         * @return the passed in {@link StringBuilder}.
029         */
030        default StringBuilder execute(T model, StringBuilder sb) {
031                try {
032                        execute(model, (Appendable) sb);
033                        return sb;
034                }
035                catch (IOException e) {
036                        throw new UncheckedIOException(e);
037                }
038        }
039
040        /**
041         * Convenience method that directly renders the model as a String.
042         * @param model never null.
043         * @return the rendered model.
044         */
045        default String execute(T model) {
046                StringBuilder sb = new StringBuilder();
047                execute(model, sb);
048                return sb.toString();
049        }
050
051}