using ln.collections; using System; using System.Collections.Generic; using System.Text; namespace ln.objects.storage { class BinaryObjectCache { BTree> firstLevel = new BTree>(); public BinaryObjectCache() { } BTree GetSecondLevel(Guid uid) { if (!firstLevel.TryGet(uid,out BTree secondLevel)) { secondLevel = new BTree(); firstLevel.Add(uid, secondLevel); } return secondLevel; } bool TryGetSecondLevel(Guid uid, out BTree secondLevel) => firstLevel.TryGet(uid, out secondLevel) && !secondLevel.Empty; public void Add(BinaryObject binaryObject) { BTree secondLevel = GetSecondLevel(binaryObject.UID); secondLevel.Add(binaryObject.Version, binaryObject); } public void Remove(BinaryObject binaryObject) { BTree secondLevel = GetSecondLevel(binaryObject.UID); secondLevel.Remove(binaryObject.Version); } public bool Contains(Guid uid) => GetSecondLevel(uid).ContainsKey(uid); public IEnumerable UIDs => firstLevel.Keys; public IEnumerable GetBinaryObjects(Guid uid) => GetSecondLevel(uid).Values; public BinaryObject GetLatestBinaryObject(Guid uid) { BTree secondLevel = GetSecondLevel(uid); return secondLevel.LastValue(); } public BinaryObject GetBinaryObject(Guid uid, int version) => GetSecondLevel(uid)[version]; public bool TryGetBinaryObjects(Guid uid,out IEnumerable binaryObjects) { if (!TryGetSecondLevel(uid,out BTree secondLevel)) { binaryObjects = null; return false; } binaryObjects = secondLevel.Values; return true; } public bool TryGetBinaryObject(Guid uid, int version, out BinaryObject binaryObject) { if (TryGetSecondLevel(uid, out BTree secondLevel)) { if (version == -1) { if (secondLevel.TryGetLastValue(out binaryObject)) return true; } else { if (secondLevel.TryGet(version, out binaryObject)) return true; } } binaryObject = null; return false; } public bool TryGetLatestBinaryObject(Guid uid, out BinaryObject binaryObject) => GetSecondLevel(uid).TryGetLastValue(out binaryObject); public bool TryGetFirstBinaryObject(Guid uid, out BinaryObject binaryObject) => GetSecondLevel(uid).TryGetFirstValue(out binaryObject); } }