< Summary

Class:DataCache[T]
Assembly:DataCache
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Helpers/DataCache/DataCache.cs
Covered lines:6
Uncovered lines:24
Coverable lines:30
Total lines:77
Line coverage:20% (6 of 30)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
DataCache()0%110100%
Add(...)0%6200%
TryGet(...)0%6200%
Forget(...)0%6200%
Dispose()0%2.022083.33%
RemoveCache()0%20400%

File(s)

/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Helpers/DataCache/DataCache.cs

#LineLine coverage
 1using System.Collections;
 2using System.Collections.Generic;
 3using UnityEngine;
 4
 5public class DataCache<T> : IDataCache<T>
 6{
 7    private class CacheType
 8    {
 9        public T value;
 10        public float lastUpdate;
 11        public float maxAge;
 12        public Coroutine expireCacheRoutine;
 13    }
 14
 24415    private readonly Dictionary<string, CacheType> cache = new Dictionary<string, CacheType>();
 16
 17    public void Add(string key, T value, float maxAge)
 18    {
 019        if (cache.TryGetValue(key, out CacheType storedCache))
 20        {
 021            CoroutineStarter.Stop(storedCache.expireCacheRoutine);
 22        }
 23        else
 24        {
 025            storedCache = new CacheType();
 026            cache[key] = storedCache;
 27        }
 28
 029        storedCache.value = value;
 030        storedCache.maxAge = maxAge;
 031        storedCache.lastUpdate = Time.unscaledTime;
 032        storedCache.expireCacheRoutine = CoroutineStarter.Start(RemoveCache(key, storedCache.maxAge));
 033    }
 34
 35    public bool TryGet(string key, out T value, out float lastUpdate)
 36    {
 037        value = default(T);
 038        lastUpdate = 0;
 39
 040        if (cache.TryGetValue(key, out CacheType storedCache))
 41        {
 042            value = storedCache.value;
 043            lastUpdate = storedCache.lastUpdate;
 044            return true;
 45        }
 46
 047        return false;
 48    }
 49
 50    public void Forget(string key)
 51    {
 052        if (cache.TryGetValue(key, out CacheType storedCache))
 53        {
 054            CoroutineStarter.Stop(storedCache.expireCacheRoutine);
 055            cache.Remove(key);
 56        }
 057    }
 58
 59    public void Dispose()
 60    {
 24461        using (var iterator = cache.GetEnumerator())
 62        {
 24463            while (iterator.MoveNext())
 64            {
 065                CoroutineStarter.Stop(iterator.Current.Value.expireCacheRoutine);
 66            }
 24467        }
 68
 24469        cache.Clear();
 24470    }
 71
 72    private IEnumerator RemoveCache(string key, float delay)
 73    {
 074        yield return WaitForSecondsCache.Get(delay);
 075        cache?.Remove(key);
 076    }
 77}