using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Umbraco.Core.Cache { /// /// Implements on top of a concurrent dictionary. /// public class DictionaryAppCache : IAppCache { /// /// Gets the internal items dictionary, for tests only! /// internal readonly ConcurrentDictionary Items = new ConcurrentDictionary(); /// public virtual object Get(string key) { return Items.TryGetValue(key, out var value) ? value : null; } /// public virtual object Get(string key, Func factory) { return Items.GetOrAdd(key, _ => factory()); } /// public virtual IEnumerable SearchByKey(string keyStartsWith) { var items = new List(); foreach (var (key, value) in Items) if (key.InvariantStartsWith(keyStartsWith)) items.Add(value); return items; } /// public IEnumerable SearchByRegex(string regex) { var compiled = new Regex(regex, RegexOptions.Compiled); var items = new List(); foreach (var (key, value) in Items) if (compiled.IsMatch(key)) items.Add(value); return items; } /// public virtual void Clear() { Items.Clear(); } /// public virtual void Clear(string key) { Items.TryRemove(key, out _); } /// public virtual void ClearOfType(string typeName) { Items.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType().ToString().InvariantEquals(typeName)); } /// public virtual void ClearOfType() { var typeOfT = typeof(T); Items.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType() == typeOfT); } /// public virtual void ClearOfType(Func predicate) { var typeOfT = typeof(T); Items.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType() == typeOfT && predicate(kvp.Key, (T)kvp.Value)); } /// public virtual void ClearByKey(string keyStartsWith) { Items.RemoveAll(kvp => kvp.Key.InvariantStartsWith(keyStartsWith)); } /// public virtual void ClearByRegex(string regex) { var compiled = new Regex(regex, RegexOptions.Compiled); Items.RemoveAll(kvp => compiled.IsMatch(kvp.Key)); } } }