001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import java.util.Optional;
005import java.util.concurrent.TimeUnit;
006import java.util.regex.Pattern;
007
008import org.apache.commons.jcs3.access.CacheAccess;
009import org.apache.commons.jcs3.engine.ElementAttributes;
010import org.apache.commons.jcs3.engine.behavior.IElementAttributes;
011import org.openstreetmap.josm.data.cache.JCSCacheManager;
012import org.openstreetmap.josm.spi.preferences.Config;
013
014/**
015 * A class that caches compiled patterns.
016 * @author Taylor Smock
017 * @since 18475
018 */
019public final class PatternUtils {
020    /** A string that is highly unlikely to appear in regexes to split a regex from its flags */
021    private static final String MAGIC_STRING = "========";
022    /** A cache for Java Patterns (no flags) */
023    private static final CacheAccess<String, Pattern> cache = JCSCacheManager.getCache("java:pattern",
024            Config.getPref().getInt("java.pattern.cache", 1024), 0, null);
025
026    static {
027        // We don't want to keep these around forever, so set a reasonablish max idle life.
028        final IElementAttributes defaultAttributes = Optional.ofNullable(cache.getDefaultElementAttributes()).orElseGet(
029                ElementAttributes::new);
030        defaultAttributes.setIdleTime(TimeUnit.HOURS.toSeconds(1));
031        cache.setDefaultElementAttributes(defaultAttributes);
032    }
033
034    private PatternUtils() {
035        // Hide the constructor
036    }
037
038    /**
039     * Compile a regex into a pattern. This may return a {@link Pattern} used elsewhere. This is safe.
040     * @param regex The regex to compile
041     * @return The immutable {@link Pattern}.
042     * @see Pattern#compile(String)
043     */
044    public static Pattern compile(final String regex) {
045        return compile(regex, 0);
046    }
047
048    /**
049     * Compile a regex into a pattern. This may return a {@link Pattern} used elsewhere. This is safe.
050     * @param regex The regex to compile
051     * @param flags The flags from {@link Pattern} to apply
052     * @return The immutable {@link Pattern}.
053     * @see Pattern#compile(String, int)
054     */
055    public static Pattern compile(String regex, int flags) {
056        // Right now, the maximum value of flags is 511 (3 characters). This should avoid unnecessary array copying.
057        final StringBuilder sb = new StringBuilder(3 + MAGIC_STRING.length() + regex.length());
058        return cache.get(sb.append(flags).append(MAGIC_STRING).append(regex).toString(), () -> Pattern.compile(regex, flags));
059    }
060}