namespace ZB.MOM.NatsNet.Server.Internal; /// /// A pointer that can be toggled between weak and strong references, allowing /// the garbage collector to reclaim the target when weakened. /// Mirrors the Go elastic.Pointer[T] type. /// /// The type of the referenced object. Must be a reference type. public sealed class ElasticPointer where T : class { private WeakReference? _weak; private T? _strong; /// /// Creates a new holding a weak reference to . /// public static ElasticPointer Make(T value) { return new ElasticPointer { _weak = new WeakReference(value) }; } /// /// Updates the target. If the pointer is currently strengthened, the strong reference is updated too. /// public void Set(T value) { _weak = new WeakReference(value); if (_strong != null) _strong = value; } /// /// Promotes to a strong reference, preventing the GC from collecting the target. /// No-op if already strengthened or if the weak target has been collected. /// public void Strengthen() { if (_strong != null) return; if (_weak != null && _weak.TryGetTarget(out var target)) _strong = target; } /// /// Reverts to a weak reference, allowing the GC to reclaim the target. /// No-op if already weakened. /// public void Weaken() { _strong = null; } /// /// Returns the target value, or if the weak reference has been collected. /// public T? Value() { if (_strong != null) return _strong; if (_weak != null && _weak.TryGetTarget(out var target)) return target; return null; } }