From 5a94c716e3fdfc8392682571e0ef38ae338d97ab Mon Sep 17 00:00:00 2001 From: hzhang Date: Fri, 28 Jun 2024 20:29:48 +0800 Subject: [PATCH] fix errors --- src/DataStructure/CacheItem.cs | 54 ++++++++++++++++++++++++++++++---- 1 file changed, 48 insertions(+), 6 deletions(-) diff --git a/src/DataStructure/CacheItem.cs b/src/DataStructure/CacheItem.cs index 45ae10f..dc06044 100644 --- a/src/DataStructure/CacheItem.cs +++ b/src/DataStructure/CacheItem.cs @@ -1,17 +1,23 @@ +using System.Diagnostics; + namespace Skeleton.DataStructure; /// /// store value from calculation to avoid redundant computations /// -public abstract class CacheItem +public class CacheItem { + + public CacheItem(Func cal) => ProxyCalculator = cal; + + public static readonly CacheItem Null = new CacheItem(x => false); /// /// if the item needs update /// public bool Expired { get; protected set; } = true; internal HashSet References { get; set; } = new(); internal HashSet Dependencies { get; set; } = new(); - + private Func Calculator => () => ProxyCalculator(this); /// /// tag the item and all dependencies as out dated /// @@ -22,6 +28,32 @@ public abstract class CacheItem if (!c.Expired) c.Expire(); } + + public TObject Get() => (this as CacheItem)!.Get; + private object? Value { get; set; } + public void Assign(object o) => UpdateCalculation(x => o); + public object Get() + { + if (Expired) + { + Value = Calculator(); + Expired = false; + } + return Value!; + } + + public TObject GetFrom(CacheItem item) => (this as CacheItem)!.GetFrom(item); + + public object GetFrom(CacheItem item) + { + References.Add(item); + item.Dependencies.Add(this); + return Get(); + } + + public Func ProxyCalculator { get; internal set; } + + public void UpdateCalculation(Func a) => ProxyCalculator = a; } /// @@ -31,12 +63,15 @@ public class CacheItem : CacheItem /// construct by provide a method to update the value /// /// - public CacheItem(Func rec) => ProxyCalculator = rec; + public CacheItem(Func rec) : base(x => rec(x)) + { + } + private TObject? Value { get; set; } /// /// return cached/updated value when reference is not used to calculate another cache item /// - public TObject Get + public new TObject Get { get { @@ -49,16 +84,21 @@ public class CacheItem : CacheItem } } private Func Calculator => () => ProxyCalculator(this); + /// /// provide trace information while calculating /// - public Func ProxyCalculator { get; internal set; } + public new Func ProxyCalculator + { + get => x => (TObject)base.ProxyCalculator(x); + set => base.ProxyCalculator = x => value(x)!; + } /// /// trace the dependency and return cached value/updated value /// /// /// - public TObject GetFrom(CacheItem d) + public new TObject GetFrom(CacheItem d) { References.Add(d); d.Dependencies.Add(this); @@ -78,5 +118,7 @@ public class CacheItem : CacheItem } + public void Assign(TObject b) => UpdateCalculation(x => b); + }