001/*
002 * Shredzone Commons
003 *
004 * Copyright (C) 2012 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;
021
022import java.util.function.Function;
023
024/**
025 * A text filter modifies a text in a defined manner. It should be highly optimized for
026 * speed.
027 * <p>
028 * Text filters are thread safe unless stated otherwise.
029 * <p>
030 * Text filters are stateless unless stated otherwise.
031 *
032 * @author Richard "Shred" Körber
033 */
034@FunctionalInterface
035public interface TextFilter extends Function<CharSequence, CharSequence> {
036
037    /**
038     * Applies the filter on a {@link CharSequence} and returns a new {@link CharSequence}
039     * with the modified text.
040     *
041     * @param t
042     *            {@link CharSequence} with the contents to be filtered. If this is a
043     *            {@link StringBuilder} instance, its contents <em>may</em> have changed
044     *            after invocation, and this instance should not be used any more.
045     * @return {@link CharSequence} with the filtered text.
046     */
047    @Override
048    CharSequence apply(CharSequence t);
049
050    /**
051     * Returns a {@link StringBuilder} for the given {@link CharSequence}. If the
052     * {@link CharSequence} is a {@link StringBuilder} instance, it will be reused.
053     *
054     * @param text
055     *            {@link CharSequence} to get a {@link StringBuilder} from
056     * @return {@link StringBuilder} instance
057     */
058    default StringBuilder toStringBuilder(CharSequence text) {
059        if (text instanceof StringBuilder) {
060            return (StringBuilder) text;
061        } else {
062            return new StringBuilder(text);
063        }
064    }
065
066}