FunctionCache.java
/*
MIT License
Copyright (c) 2019 Gleethos
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
package neureka.math;
import neureka.backend.api.BackendContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* This class is part of a given {@link BackendContext} instance
* responsible for caching {@link Function} references based on
* their {@link String} representation generated by {@link Object#toString()}
* as well as caching of results for active functions.
*/
public final class FunctionCache
{
private final static int CAPACITY = 1024;
private final Logger _LOG = LoggerFactory.getLogger( FunctionCache.class );
private final Map<String, Function> _functionCache = new LinkedHashMap<String, Function>() {
@Override
protected boolean removeEldestEntry(final Map.Entry eldest) {
return size() > CAPACITY;
}
};
public void put( Function function ) {
if ( function == null ) {
_LOG.error("Null reference passed to '"+getClass().getSimpleName()+"'!");
return;
}
boolean doAD = function.isDoingAD();
_functionCache.put(
( ( (doAD) ? "d" : "" ) + "(" + function + ")" ).intern(), // Make the String unique!
function
);
}
public Function get( String expression, boolean doesAD ) {
String k = ( doesAD ? "d" + expression : expression );
return _functionCache.get( k );
}
public boolean has( String expression, boolean doesAD ) {
String k = ( doesAD ? "d" + expression : expression );
return _functionCache.containsKey( k );
}
public String toString() { return this.getClass().getSimpleName()+"[size="+_functionCache.size()+"]"; }
}