Created
July 25, 2025 17:25
-
-
Save Hafune/45a150e13a184197b7374e535a454f88 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Runtime.CompilerServices; | |
namespace Core.Lib | |
{ | |
public readonly struct KeyValueCache<T, V> | |
{ | |
private readonly Dictionary<T, V> _cache; | |
private readonly Func<T, V> _getValue; | |
public KeyValueCache(Func<T, V> getValue) | |
{ | |
_getValue = getValue; | |
_cache = new Dictionary<T, V>(); | |
} | |
[MethodImpl(MethodImplOptions.AggressiveInlining)] | |
public V Get(T key) | |
{ | |
if (!_cache.TryGetValue(key, out var fullKey)) | |
_cache[key] = fullKey = _getValue(key); | |
return fullKey; | |
} | |
} | |
public readonly struct IntValueCache<V> | |
{ | |
private readonly Glossary<V> _cache; | |
private readonly Func<int, V> _getValue; | |
public IntValueCache(Func<int, V> getValue) | |
{ | |
_getValue = getValue; | |
_cache = new Glossary<V>(); | |
} | |
[MethodImpl(MethodImplOptions.AggressiveInlining)] | |
public V Get(int key) | |
{ | |
if (!_cache.TryGetValue(key, out var fullKey)) | |
_cache.Add(key, fullKey = _getValue(key)); | |
return fullKey; | |
} | |
public void Clear() => _cache.Clear(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment