Exemple #1
0
 private static void Initialize()
 {
     var init = new ResourceTestSystemInitiation();
     var res = init.CreateResources(ResourceSpaceDescriptions.Count);
     ResourceSpaceDescriptions.ResourceAssembly = res;
     AppDomain.CurrentDomain.AssemblyResolve +=
         (e, a) =>
             {
                 if (a.Name.Contains("TestResources"))
                     return res;
                 throw new Exception();
             };
     var store = new Store();
    
     _upnode1 = new CacheNode("Client1",res,store);
     _upnode2 = new CacheNode("Client2",res,store);
     _upnode3 = new CacheNode("Client3", res, store);
     _upnode4 = new CacheNode("Client4", res, store);
     _centnode = new CacheNode("Central", res, store);
     _upnode1.ConnectToDownNode(_centnode,TimeSpan.FromMilliseconds(30));
     _upnode2.ConnectToDownNode(_centnode, TimeSpan.FromMilliseconds(30));
     _upnode3.ConnectToDownNode(_centnode, TimeSpan.FromMilliseconds(30));
     _upnode4.ConnectToDownNode(_centnode, TimeSpan.FromMilliseconds(30));
     _upnode1.Start();
     _upnode2.Start();
     _upnode3.Start();
     _upnode4.Start();
     _centnode.Start();
 }
 public void Add2Test()
 {
     var node = new CacheNode<int, int>(10, 10, 0, Comparer<int>.Default);
     int depth = 0;
     node.AddNode(9, 9, 0, 0);
     Assert.AreEqual(9, node.FindNode(9, 0, out depth));
     Assert.AreEqual(depth, 1);
 }
 public void DumbTest()
 {
     
     var node = new CacheNode<int, int>(10, 10,0,  Comparer<int>.Default);
     int depth = 0;
     Assert.AreEqual(10, node.FindNode(10, 0, out depth));
     Assert.AreEqual(0, depth);
     Assert.AreEqual(0, node.FindNode(9, 0, out depth));
     Assert.AreEqual(0, node.FindNode(11, 0, out depth));
 }
 private CacheNode<int, double> BuildAndBalanceTree(int[] frequences, out float expectedFrequency, int maxFixedBranchDepth = 0)
 {
     var root = BuildTree(frequences, maxFixedBranchDepth);          
     var balancer = new CacheNode<int, double>.HeavyRebalancer(root, frequences.Length, 0, 1);         
     var watch = Stopwatch.StartNew();
     expectedFrequency = balancer.Rebalance();
     watch.Stop();
     Debug.Print("{0} balancing was", watch.Elapsed);
     root = balancer.ConstructNewTreeAfterCalculation();
     return root;
 }
Exemple #5
0
 private static void Administration(CacheNode node,int amount)
 {
     for (var i = 0; i < amount; i++)
     {
         node.PostResourceFromScratch();
         node.PostResourceFromScratch("Client1");
         node.PostResourceFromScratch("Client2");
         node.PostResourceFromScratch("Client3");
         node.PostResourceFromScratch("Client4");       
         node.QueryResourceByOtherResource();
         node.GetQueriedResource();
         node.PostResourceFromScratch();
     }
     node.ClearMemory(0);
 }
 private CacheNode<int, double> BuildTree(int[] frequences,  int maxFixedBranchDepth = 0)
 {
     var freqSum = frequences.Sum();
     
     var root = new CacheNode<int, double>(0, (double)frequences[0] / freqSum, maxFixedBranchDepth, Comparer<int>.Default, probabilityCalc: k => (float)k);
     var frs = Enumerable.Range(0, frequences.Length).ToList();
     var rnd = new Random();
     for (int i = 1; i < frequences.Length; i++)
     {
         var t = rnd.Next(frs.Count - 1) + 1;
         var key = frs[t];
         root.AddNode(key, (double)frequences[key] / freqSum, maxFixedBranchDepth, 0);
         frs.RemoveAt(t);
     }
     return root;
 }
 public void Set(string key, string value)
 {
     if ((!_memCache.ContainsKey(key)) && (_memCache.Count == _maxNumElements))
     {
         Evict();
     }
     PQNode pNode = null;
     if (!_memCache.ContainsKey(key))
     {
         pNode = _priorityQueue.Insert(key);
     }
     else
     {
         pNode = _memCache[key].PriorityNode;
         _priorityQueue.IncreasePriority(pNode);
     }
     _memCache[key] = new CacheNode { Value = value, PriorityNode = pNode };
 }
 public void AddWithCollectingTest()
 {
    
     var node = new CacheNode<int, int>(10, 10, 0, Comparer<int>.Default);
     node.AddNode(11, 11, 0, 0);
     node.AddNode(9, 9, 0, 0);
     int depth;
     Assert.AreEqual(9, node.FindNode(9, 0, out depth));
     Assert.AreEqual(1, depth);;
     Assert.AreEqual(11, node.FindNode(11, 0, out depth));
     Assert.AreEqual(1, depth);
     GC.Collect(2,GCCollectionMode.Forced);
     GC.Collect(2, GCCollectionMode.Forced);
     GC.Collect(2, GCCollectionMode.Forced);
     GC.WaitForPendingFinalizers();
     Assert.AreEqual(0, node.FindNode(9, 0, out depth));
     Assert.AreEqual(0, node.FindNode(11, 0, out depth));
 }
Exemple #9
0
 private static void Work(CacheNode node,string rootResName)
 {
     node.QueryResourceByNode(rootResName);
     node.GetAllQueriedResource();          
     node.GetResource();
     node.PostResourceFromMemory();
     node.QueryResourceByNodeAndOtherResource();
     node.GetAllQueriedResource();
     for (int i = 0; i < 20;i++ )
         node.PostResourceFromMemory(node.Name);
     node.QueryResourceByOtherResource();
     node.QueryResourceByOtherResource();
     node.QueryResourceByOtherResource();
     node.GetAllQueriedResource();
     node.PostResourceFromScratch();
     node.GetResource();
     node.ClearMemory(300);
 }
Exemple #10
0
        /// <summary> Remove a specific entry from the table. Returns true if the
        /// entry was found.
        /// </summary>
        public virtual bool remove(DNSEntry entry)
        {
            lock (this)
            {
                CacheNode node = (CacheNode)hashtable[entry.Name];
                if (node != null)
                {
                    if (node.Value == entry)
                    {
                        if (node.Next == null)
                        {
                            hashtable.Remove(entry.Name);
                        }
                        else
                        {
                            hashtable[entry.Name] = node.Next;
                        }
                        size--;
                        return(true);
                    }

                    CacheNode previous = node;
                    node = node.Next;
                    while (node != null)
                    {
                        if (node.Value == entry)
                        {
                            previous.Next = node.Next;
                            size--;
                            return(true);
                        }
                        previous = node;
                        node     = node.Next;
                    }
                    ;
                }
                return(false);
            }
        }
Exemple #11
0
        public void Put(int key, int value)
        {
            if (this.dict.ContainsKey(key))
            {
                CacheNode n = this.dict[key];
                this.dict[key].Value = value;

                n.Pre.Next = n.Next;
                n.Next.Pre = n.Pre;

                this.tail.Pre.Next = n;
                n.Pre         = this.tail.Pre;
                this.tail.Pre = n;
                n.Next        = this.tail;
            }
            else
            {
                CacheNode newNode = new CacheNode(key, value);

                if (count < this.Capacity)
                {
                    count += 1;
                }
                else
                {
                    dict.Remove(this.head.Next.Key);
                    this.head     = this.head.Next;
                    this.head.Pre = null;
                }

                this.tail.Pre.Next = newNode;
                newNode.Pre        = this.tail.Pre;
                this.tail.Pre      = newNode;
                newNode.Next       = this.tail;

                dict.Add(key, newNode);
            }
        }
Exemple #12
0
 /// <summary>
 /// A least recently used cache with a time to live.
 /// </summary>
 /// <param name="capacity">
 /// The number of entries the cache will hold
 /// </param>
 /// <param name="hours">The number of hours in the TTL</param>
 /// <param name="minutes">The number of minutes in the TTL</param>
 /// <param name="seconds">The number of seconds in the TTL</param>
 /// <param name="refreshEntries">
 /// Whether the TTL should be refreshed upon retrieval
 /// </param>
 public LRUCache(
     int capacity,
     int hours           = 0,
     int minutes         = 0,
     int seconds         = 0,
     bool refreshEntries = true)
 {
     Capacity        = capacity;
     _entries        = new Dictionary <K, CacheNode>(Capacity);
     _head           = null;
     _tail           = null;
     _count          = 0;
     _ttl            = new TimeSpan(hours, minutes, seconds);
     _refreshEntries = refreshEntries;
     if (_ttl > TimeSpan.Zero)
     {
         _timer = new Timer(
             Purge,
             null,
             (int)_ttl.TotalMilliseconds,
             5000); // 5 seconds
     }
 }
Exemple #13
0
        /// <summary>
        /// Sets the specified name.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="item">The item.</param>
        /// <param name="keepAlive">The keep alive.</param>
        public void Set(string name, object item, TimeSpan?keepAlive = null)
        {
            lock (this)
            {
                PurgeExpiredItems();

                keepAlive = keepAlive ?? TimeSpan.Zero;

                var node = GetNode(name);
                if (node != null && ReferenceEquals(node.Data, item))
                {
                    node.KeepAlive = keepAlive.Value;
                    node.ResetCachedDateTime();
                }
                else
                {
                    Remove(name);

                    var preName = PrepareObjectName(name);
                    CacheContainer[preName] = new CacheNode(preName, item, keepAlive.Value);
                }
            }
        }
Exemple #14
0
        public void Put(int key, int value)
        {
            CacheNode node = null;

            if (map.ContainsKey(key))
            {
                node       = map[key];
                node.Value = value;
                cache.Remove(node);
            }
            else
            {
                node = new CacheNode(key, value);
            }

            cache.AddLast(node);
            map[key] = node;
            if (cache.Count > capacity)
            {
                map.Remove(cache.First.Value.Key);
                cache.RemoveFirst();
            }
        }
Exemple #15
0
 private void RemoveNode(CacheNode node)
 {
     if (node.PrevNode == null && node.NextNode == null)
     {
         this.Head = null;
         this.Tail = null;
     }
     else if (node.PrevNode == null)
     {
         this.Head          = node.NextNode;
         this.Head.PrevNode = null;
     }
     else if (node.NextNode == null)
     {
         this.Tail = node.PrevNode;
         node.PrevNode.NextNode = null;
     }
     else
     {
         node.PrevNode.NextNode = node.NextNode;
         node.NextNode.PrevNode = node.PrevNode;
     }
 }
        ///
        ///<summary>The remove method takes a CacheNode type input cacheNode. If cacheNode has a previous node, then
        /// assigns cacheNode's next node as previous node's next node. If cacheNode has not got a previous node, then
        /// assigns its next node as head node. Moreover, if cacheNode has a next node, then assigns cacheNode's
        /// previous node as next node's previous node; if not assigns tail node's previous node as tail. By doing so
        /// it removes the cacheNode from doubly {@link java.util.LinkedList}.</summary>
        ///
        ///<param name="cacheNode"> {@link CacheNode} type input to remove.</param>
        ///
        public void Remove(CacheNode <TKey, TData> cacheNode)
        {
            var previous = cacheNode.GetPrevious();
            var next     = cacheNode.GetNext();

            if (previous != null)
            {
                previous.SetNext(next);
            }
            else
            {
                _head = _head.GetNext();
            }

            if (next != null)
            {
                next.SetPrevious(previous);
            }
            else
            {
                _tail = _tail.GetPrevious();
            }
        }
    public void Put(int key, int value)
    {
        if (dictPrev.ContainsKey(key))
        {
            dictPrev[key].next.val = value;
            Get(key);
            return;
        }
        if (dictPrev.Count == capacity)
        {
            dictPrev.Remove(head.next.key);
            head.next = head.next.next;
            if (head.next != null)
            {
                dictPrev[head.next.key] = head;
            }
        }
        CacheNode node = new CacheNode(key, value);

        dictPrev[key] = tail;
        tail.next     = node;
        tail          = node;
    }
Exemple #18
0
        private void RemoveCacheNodeFromList(CacheNode node)
        {
            var next     = node.Next;
            var previous = node.Previous;

            if (null != next)
            {
                next.Previous = node.Previous;
            }
            if (null != previous)
            {
                previous.Next = node.Next;
            }

            if (this._head == node)
            {
                this._head = next;
            }

            if (this._tail == node)
            {
                this._tail = previous;
            }
        }
Exemple #19
0
            public override void Push(int item)
            {
                this.stack.Push(item);

                if (!this.cache.IsEmpty)
                {
                    CacheNode node = cache.Peek();
                    if (node.Value == item)
                    {
                        node.Count++;
                        return;
                    }
                    else if (node.Value > item)
                    {
                        return;
                    }
                }

                CacheNode newNode = new CacheNode {
                    Count = 1, Value = item
                };

                this.cache.Push(newNode);
            }
Exemple #20
0
        public T get(K key)
        {
            int placementSet             = hashKey(key);
            CacheNode <K, T> head        = setHeads[placementSet];
            CacheNode <K, T> currentNode = head;

            // The following loop checks the nodes in the set that the key
            // hashes to. On a hit, the node matching the key is set as the new
            // head and removed from its former placement.
            while (currentNode.key != null)
            {
                if (currentNode.key.Equals(key))
                {
                    head.prev = currentNode;
                    setHeads[placementSet] = currentNode;
                    currentNode.removeNode();
                    return(currentNode.value);
                }
                currentNode = currentNode.next;
            }

            // On a miss, the cache returns null.
            return(default(T));
        }
Exemple #21
0
        private void RemoveFromLL(CacheNode entry)
        {
            var next = entry.Next;
            var prev = entry.Prev;

            if (null != next)
            {
                next.Prev = entry.Prev;
            }
            if (null != prev)
            {
                prev.Next = entry.Next;
            }

            if (_head == entry)
            {
                _head = next;
            }

            if (_tail == entry)
            {
                _tail = prev;
            }
        }
Exemple #22
0
        public void Put(int key, int value)
        {
            if (dic.TryGetValue(key, out var node))
            {
                node.val = value;
                MoveToTail(node);
            }
            else
            {
                dic[key] = node = new CacheNode {
                    key = key, val = value
                };
                if (tail == null)
                {
                    head = tail = node;
                }
                else
                {
                    tail.next = node;
                    node.prev = tail;
                    tail      = node;
                }
            }

            while (dic.Count > capacity)
            {
                dic.Remove(head.key);
                head = head.next;
                if (head == null)
                {
                    break;
                }

                head.prev = null;
            }
        }
        public void DeepAddWithCollectingWithNonZeroFixedBranchLengthTest()
        {

            var node = new CacheNode<int, int>(10, 10,1, Comparer<int>.Default);
            #region Prepare
            node.AddNode(8, 8, 1, 0);
            node.AddNode(7, 7, 1, 0);
            node.AddNode(9, 9, 1, 0);
            node.AddNode(12, 12, 1, 0);
            node.AddNode(11, 11, 1, 0);
            node.AddNode(13, 13, 1, 0);
            int depth = 0;
            Assert.AreEqual(7, node.FindNode(7, 0, out depth));
            Assert.AreEqual(2, depth);
            depth = 0;
            Assert.AreEqual(8, node.FindNode(8, 0, out depth));
            Assert.AreEqual(1, depth);
            depth = 0;
            Assert.AreEqual(9, node.FindNode(9, 0, out depth));
            Assert.AreEqual(2, depth);
            depth = 0;
            Assert.AreEqual(10, node.FindNode(10, 0, out depth));
            Assert.AreEqual(0, depth);
            depth = 0;
            Assert.AreEqual(11, node.FindNode(11, 0, out depth));
            Assert.AreEqual(2, depth);
            depth = 0;
            Assert.AreEqual(12, node.FindNode(12, 0, out depth));
            Assert.AreEqual(1, depth);
            depth = 0;
            Assert.AreEqual(13, node.FindNode(13, 0, out depth));
            Assert.AreEqual(2, depth);
            depth = 0;
            #endregion

            #region First collection
            GC.Collect(2, GCCollectionMode.Forced);
            GC.WaitForPendingFinalizers();
            Assert.AreEqual(0, node.FindNode(7, 0, out depth));
            depth = 0;
            Assert.AreEqual(8, node.FindNode(8, 0, out depth));
            Assert.AreEqual(1, depth);
            depth = 0;
            Assert.AreEqual(0, node.FindNode(9, 0, out depth));
            depth = 0;
            Assert.AreEqual(10, node.FindNode(10, 0, out depth));
            Assert.AreEqual(0, depth);
            depth = 0;
            Assert.AreEqual(0, node.FindNode(11, 0, out depth));
            depth = 0;
            Assert.AreEqual(12, node.FindNode(12, 0, out depth));
            Assert.AreEqual(1, depth);
            depth = 0;
            Assert.AreEqual(0, node.FindNode(13, 0, out depth));
            #endregion

            GC.Collect(2, GCCollectionMode.Forced);
            GC.WaitForPendingFinalizers();
            Assert.AreEqual(0, node.FindNode(7, 0, out depth));
            Assert.AreEqual(8, node.FindNode(8, 0, out depth));
            Assert.AreEqual(0, node.FindNode(9, 0, out depth));
            depth = 0;
            Assert.AreEqual(10, node.FindNode(10, 0, out depth));
            Assert.AreEqual(0, depth);
            Assert.AreEqual(0, node.FindNode(11, 0, out depth));
            Assert.AreEqual(12, node.FindNode(12, 0, out depth));
            Assert.AreEqual(0, node.FindNode(13, 0, out depth));
        }
Exemple #24
0
 private void RemoveCacheNode(CacheNode node)
 {
     RemoveCacheNodeFromList(node);
     this._entries.Remove(node.Key);
     this._count--;
 }
 /// <summary>
 /// Creates a new store management node.
 /// </summary>
 /// <param name="backingNode">The underlying <see cref="CacheNode"/> containing the cache information.</param>
 /// <param name="manageForm">The form hosting the management UI.</param>
 public StoreManageNode(CacheNode backingNode, StoreManageForm manageForm)
 {
     BackingNode = backingNode ?? throw new ArgumentNullException(nameof(backingNode));
     _manageForm = manageForm ?? throw new ArgumentNullException(nameof(manageForm));
 }
    //删除节点比较复杂,需要考虑两个prev节点和两个next节点,单独写个方法
    public void DeleteNode(CacheNode node)
    {
        //Debug.Log("DeleteNode==" + node.fullPath);
        //注意!!!!!!
        //这里被我自己坑了,在插入cacheDic是倒着插入的
        //所以如果删除的是头结点的话,头结点指向的是链表的末尾,而不是开头,查了好久...
        if (node.prevOfPath == null && node.nextOfPath == null)
        {
            //如果移除的是cacheDic的最后一个,则直接从容器中移除
            cacheDic.Remove(node.fullPath);
        }
        else
        {
            if (node.nextOfPath == null)
            {
            }
            else
            {
                node.nextOfPath.prevOfPath = node.prevOfPath;
            }
            if (node.prevOfPath == null)
            {
                cacheDic[node.fullPath] = node.nextOfPath;
            }
            else
            {
                node.prevOfPath.nextOfPath = node.nextOfPath;
            }
        }

        bool isHead = false;
        bool isTail = false;

        if (node.prevOfAll == null)
        {
            //如果没有全局前置节点,则代表是全局头结点
            isHead = true;
        }
        else
        {
            node.prevOfAll.nextOfAll = node.nextOfAll;
        }
        if (node.nextOfAll == null)
        {
            isTail = true;
        }
        else
        {
            node.nextOfAll.prevOfAll = node.prevOfAll;
        }

        if (isHead && isTail)
        {
            head = null;
            tail = null;
        }
        else if (isHead)
        {
            head = head.nextOfAll;
        }
        else if (isTail)
        {
            tail = tail.prevOfAll;
        }
        size--;
    }
Exemple #27
0
		/// <summary> Adds an entry to the table.</summary>
		public virtual void  add(DNSEntry entry)
		{
			lock (this)
			{
				//logger.log("DNSCache.add("+entry.getName()+")");
				CacheNode newValue = new CacheNode(entry);
				CacheNode node = (CacheNode) hashtable[entry.Name];
				if (node == null)
				{
					hashtable[entry.Name] = newValue;
				}
				else
				{
					newValue.Next = node.Next;
					node.Next = newValue;
				}
				size++;
			}
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="CacheNode{TValue}"/> class.
 /// </summary>
 /// <param name="tag">The tag.</param>
 /// <param name="value">The value.</param>
 public CacheNode(int tag, TValue value)
 {
     Value    = new CacheEntry <TValue>(tag, value);
     Previous = null;
     Next     = null;
 }
Exemple #29
0
            public override int Pop()
            {
                CacheNode node = this.stack.Pop();

                return(node.Value);
            }
Exemple #30
0
        KeyValuePair <K, T> mruAlgorithm(CacheNode <K, T> head)
        {
            var pair = new KeyValuePair <K, T>(head.key, head.value);

            return(pair);
        }
        private void Add(CacheNode entry)
        {
            // Avoid name collisions by incrementing suffix
            while (Nodes.Contains(entry.Name)) entry.SuffixCounter++;

            Nodes.Add(entry);
        }
            public override void Push(int item)
            {
                this.stack.Push(item);

                if(!this.cache.IsEmpty)
                {
                    CacheNode node = cache.Peek();
                    if (node.Value == item)
                    {
                        node.Count++;
                        return;
                    }
                    else if (node.Value > item)
                        return;
                }

                CacheNode newNode = new CacheNode { Count = 1, Value = item };
                this.cache.Push(newNode);
            }
 ///
 ///<summary>Setter for the previous CacheNode.</summary>
 ///
 ///<param name="previous"> CacheNode.</param>
 ///
 public void SetPrevious(CacheNode <TKey, TData> previous)
 {
     this._previous = previous;
 }
Exemple #34
0
 private bool IsEqual(ISnapshot snapshot, CacheNode node)
 {
     return(node.Snapshot.Owner == snapshot.Owner &&
            node.Snapshot.Direction == snapshot.Direction &&
            node.Time.Subtract(DateTime.Now) < delay);
 }
Exemple #35
0
        public BigInteger Pow(BigInteger[] exponents)
        {
            if (bases.Length != exponents.Length)
            {
                throw new ArithmeticException("Same number of bases and exponents expected");
            }

            int[][] exps;
            int     maxExpLen;

            ExtractAligned(exponents, out exps, out maxExpLen);

            var  accum      = new int[modulusMagnitude.Length + 1];
            var  a          = new int[modulusMagnitude.Length];
            var  gi         = new int[modulusMagnitude.Length];
            bool foundFirst = false;

            for (int i = 0; i < maxExpLen; ++i)
            {
                for (int bit = 31; bit >= 0; --bit)
                {
                    bool nonZero = false;
                    var  mask    = 1 << bit;

                    var node = rootNode;
                    for (int e = 0; e < exponents.Length; ++e)
                    {
                        if ((exps[e][i] & mask) != 0)
                        {
                            CacheNode next;
                            if (!node.next.TryGetValue(e, out next))
                            {
                                next = new CacheNode {
                                    length = node.length + 1
                                };
                                next.number = (int[])node.number.Clone();
                                MultiplyMonty(accum, next.number, bases[e]);
                                node.next[e] = next;
                            }

                            node = next;
                            if (node.length == MaxChainLength)
                            {
                                if (nonZero)
                                {
                                    MultiplyMonty(accum, gi, node.number);
                                }
                                else
                                {
                                    Buffer.BlockCopy(node.number, 0, gi, 0, modulusMagnitude.Length * 4);
                                    nonZero = true;
                                }

                                node = rootNode;
                            }
                        }
                    }

                    if (node != rootNode)
                    {
                        if (nonZero)
                        {
                            MultiplyMonty(accum, gi, node.number);
                        }
                        else
                        {
                            Buffer.BlockCopy(node.number, 0, gi, 0, modulusMagnitude.Length * 4);
                            nonZero = true;
                        }
                    }

                    if (foundFirst)
                    {
                        MultiplyMonty(accum, a, a);
                    }

                    if (nonZero)
                    {
                        if (!foundFirst)
                        {
                            Buffer.BlockCopy(gi, 0, a, 0, modulusMagnitude.Length * 4);
                            foundFirst = true;
                        }
                        else
                        {
                            MultiplyMonty(accum, a, gi);
                        }
                    }
                }
            }

            Array.Clear(gi, 0, gi.Length);
            gi[gi.Length - 1] = 1;
            MultiplyMonty(accum, a, gi);

            BigInteger result = FromData(a);

            return(result);
        }
 ///
 ///<summary>Setter for the next CacheNode.</summary>
 ///
 ///<param name="next"> CacheNode.</param>
 ///
 public void SetNext(CacheNode <TKey, TData> next)
 {
     this._next = next;
 }
Exemple #37
0
 private static void MaintanceWork(CacheNode node)
 {
     node.QueryAllOfSomeResource();
     node.GetAllQueriedResource();          
     node.GetResource();
     node.PostResourceFromMemory();
     node.QueryResourceByOtherResource();
     node.GetAllQueriedResource(); 
     node.PostResourceFromMemory();
     node.PostResourceFromMemory();
     node.PostResourceFromMemory();
     node.PostResourceFromMemory();
     node.PostResourceFromScratch();
     node.GetResource();
     node.QueryResourceByOtherResource();              
     node.GetAllQueriedResource(); 
     node.PostResourceFromMemory();
     node.PostResourceFromMemory();
     node.ClearMemory(500);
 }
Exemple #38
0
        /// <summary>
        /// Sets the item being stored to the supplied value.
        /// </summary>
        /// <param name="key">The cache key.</param>
        /// <param name="value">The value to set in the cache.</param>
        /// <returns>True if the set was successful. False otherwise.</returns>
        public bool TryAdd(K key, V value)
        {
            CacheNode entry;

            if (!this._entries.TryGetValue(key, out entry))
            {
                // Add the entry
                lock (this)
                {
                    if (!this._entries.TryGetValue(key, out entry))
                    {
                        if (this.IsFull)
                        {
                            // Re-use the CacheNode entry
                            entry = this._tail;
                            _entries.Remove(this._tail.Key);

                            // Reset with new values
                            entry.Key          = key;
                            entry.Value        = value;
                            entry.LastAccessed = DateTime.UtcNow;

                            // Next and Prev don't need to be reset.
                            // Move to front will do the right thing.
                        }
                        else
                        {
                            this._count++;
                            entry = new CacheNode()
                            {
                                Key          = key,
                                Value        = value,
                                LastAccessed = DateTime.UtcNow
                            };
                        }
                        _entries.Add(key, entry);
                    }
                }
            }
            else
            {
                // If V is a nonprimitive Value type (struct) then sets are
                // not atomic, therefore we need to lock on the entry.
                lock (entry)
                {
                    entry.Value = value;
                }
            }

            MoveToHead(entry);

            // We don't need to lock here because two threads at this point
            // can both happily perform this check and set, since they are
            // both atomic.
            if (null == this._tail)
            {
                this._tail = this._head;
            }

            return(true);
        }
Exemple #39
0
        public BigInteger Pow(BigInteger[] exponents)
        {
            if (bases.Length != exponents.Length)
            throw new ArithmeticException("Same number of bases and exponents expected");

              int[][] exps;
              int maxExpLen;
              ExtractAligned(exponents, out exps, out maxExpLen);

              var accum = new int[modulusMagnitude.Length + 1];
              var a = new int[modulusMagnitude.Length];
              var gi = new int[modulusMagnitude.Length];
              bool foundFirst = false;

              for (int i = 0; i < maxExpLen; ++i)
              {
            for (int bit = 31; bit >= 0; --bit)
            {
              bool nonZero = false;
              var mask = 1 << bit;

              var node = rootNode;
              for(int e = 0; e < exponents.Length; ++e)
            if ((exps[e][i] & mask) != 0)
            {
              CacheNode next;
              if (!node.next.TryGetValue(e, out next))
              {
                next = new CacheNode { length = node.length + 1 };
                next.number = (int[])node.number.Clone();
                MultiplyMonty(accum, next.number, bases[e]);
                node.next[e] = next;
              }

              node = next;
              if (node.length == MaxChainLength)
              {
                if (nonZero)
                  MultiplyMonty(accum, gi, node.number);
                else
                {
                  Buffer.BlockCopy(node.number, 0, gi, 0, modulusMagnitude.Length * 4);
                  nonZero = true;
                }

                node = rootNode;
              }
            }

              if(node != rootNode)
            if (nonZero)
              MultiplyMonty(accum, gi, node.number);
            else
            {
              Buffer.BlockCopy(node.number, 0, gi, 0, modulusMagnitude.Length * 4);
              nonZero = true;
            }

              if (foundFirst)
            MultiplyMonty(accum, a, a);

              if (nonZero)
              {
            if (!foundFirst)
            {
              Buffer.BlockCopy(gi, 0, a, 0, modulusMagnitude.Length * 4);
              foundFirst = true;
            }
            else
              MultiplyMonty(accum, a, gi);
              }
            }
              }

              Array.Clear(gi, 0, gi.Length);
              gi[gi.Length - 1] = 1;
              MultiplyMonty(accum, a, gi);

              BigInteger result = FromData(a);
              return result;
        }
            public override void Push(int item)
            {
                CacheNode node = new CacheNode { Value = item };

                if (this.stack.IsEmpty)
                    node.Max = item;
                else
                {
                    CacheNode tail = this.stack.Peek();
                    node.Max = Math.Max(item, tail.Max);
                }

                stack.Push(node);
            }
    public void Put(string fullPath, GameObject obj)
    {
        //Debug.Log("Put==" + fullPath);
        //Debug.Log("obj==" + obj);
        //Debug.Log("size==" + size);
        //Debug.Log("isContain=" + AssetManager.LoadBase.AssetDic.ContainsKey(fullPath));
        //如果缓存最大容量为0,则直接卸载,不做任何处理
        if (capacity <= 0)
        {
            AssetManager.AssetLoad.UnLoadAsset(fullPath);
            GameObject.Destroy(obj);
            return;
        }

        //如果达到上限,则清理掉缓存的头结点
        if (size == capacity && head != null)
        {
            //Debug.Log("卸载==" + head.fullPath + ", name =" + head.value.name);
            GameObject.Destroy(head.value);
            string headPath = head.fullPath;
            DeleteNode(head);
            if (!cacheDic.ContainsKey(headPath) && fullPath != headPath)
            {
                AssetManager.AssetLoad.UnLoadAsset(headPath);
            }
        }

        CacheNode node = new CacheNode();

        node.fullPath          = fullPath;
        node.value             = obj;
        obj.transform.position = new Vector3(1000, 1000, 1000);
        //obj.SetActive(false);
        if (cacheDic.ContainsKey(fullPath))
        {
            //这里插入链表时,不用非插入到最后一个,直接插入到第一个
            cacheDic[fullPath].prevOfPath = node;
            node.nextOfPath    = cacheDic[fullPath];
            cacheDic[fullPath] = node;
        }
        else
        {
            cacheDic.Add(fullPath, node);
        }
        if (size == 0)
        {
            head = node;
            tail = head;
        }
        else
        {
            node.prevOfAll = tail;
            tail.nextOfAll = node;
            tail           = node;
        }
        size++;
        //      if(headPath == "")
        //{
        //          return;
        //}
        //      string str = "";
        //      CacheNode tmpNode = head;
        //      while (tmpNode != null)
        //      {
        //          int len = tmpNode.fullPath.Length;
        //          int last = tmpNode.fullPath.LastIndexOf('/');
        //          str += (tmpNode.fullPath.Substring(last, len - last) + ",");
        //          tmpNode = tmpNode.nextOfAll;
        //      }
        //      string str2 = "";
        //      CacheNode tmpNode2 = head;
        //      while (tmpNode2 != null)
        //      {
        //          int len = tmpNode2.fullPath.Length;
        //          int last = tmpNode2.fullPath.LastIndexOf('/');
        //          str2 += (tmpNode2.fullPath.Substring(last, len - last) + ",");
        //          tmpNode2 = tmpNode2.nextOfPath;
        //      }
        //      string str3 = "";
        //      CacheNode tmpNode3 = node;
        //      while (tmpNode3 != null)
        //      {
        //          int len = tmpNode3.fullPath.Length;
        //          int last = tmpNode3.fullPath.LastIndexOf('/');
        //          str3 += (tmpNode3.fullPath.Substring(last, len - last) + ",");
        //          tmpNode3 = tmpNode3.nextOfPath;
        //      }
        //      Debug.Log("UnLoadAsset==" + headPath);
        //      Debug.Log("str==" + str);
        //      Debug.Log("str2==" + str2);
        //      Debug.Log("str3==" + str3);
    }
        public void DeepAddWithCollectingWithNonZeroFixedBranchLengthTest()
        {
            var node = new CacheNode <int, int>(10, 10, 1, Comparer <int> .Default);

            #region Prepare
            node.AddNode(8, 8, 1, 0);
            node.AddNode(7, 7, 1, 0);
            node.AddNode(9, 9, 1, 0);
            node.AddNode(12, 12, 1, 0);
            node.AddNode(11, 11, 1, 0);
            node.AddNode(13, 13, 1, 0);
            int depth = 0;
            Assert.AreEqual(7, node.FindNode(7, 0, out depth));
            Assert.AreEqual(2, depth);
            depth = 0;
            Assert.AreEqual(8, node.FindNode(8, 0, out depth));
            Assert.AreEqual(1, depth);
            depth = 0;
            Assert.AreEqual(9, node.FindNode(9, 0, out depth));
            Assert.AreEqual(2, depth);
            depth = 0;
            Assert.AreEqual(10, node.FindNode(10, 0, out depth));
            Assert.AreEqual(0, depth);
            depth = 0;
            Assert.AreEqual(11, node.FindNode(11, 0, out depth));
            Assert.AreEqual(2, depth);
            depth = 0;
            Assert.AreEqual(12, node.FindNode(12, 0, out depth));
            Assert.AreEqual(1, depth);
            depth = 0;
            Assert.AreEqual(13, node.FindNode(13, 0, out depth));
            Assert.AreEqual(2, depth);
            depth = 0;
            #endregion

            #region First collection
            GC.Collect(2, GCCollectionMode.Forced);
            GC.WaitForPendingFinalizers();
            Assert.AreEqual(0, node.FindNode(7, 0, out depth));
            depth = 0;
            Assert.AreEqual(8, node.FindNode(8, 0, out depth));
            Assert.AreEqual(1, depth);
            depth = 0;
            Assert.AreEqual(0, node.FindNode(9, 0, out depth));
            depth = 0;
            Assert.AreEqual(10, node.FindNode(10, 0, out depth));
            Assert.AreEqual(0, depth);
            depth = 0;
            Assert.AreEqual(0, node.FindNode(11, 0, out depth));
            depth = 0;
            Assert.AreEqual(12, node.FindNode(12, 0, out depth));
            Assert.AreEqual(1, depth);
            depth = 0;
            Assert.AreEqual(0, node.FindNode(13, 0, out depth));
            #endregion

            GC.Collect(2, GCCollectionMode.Forced);
            GC.WaitForPendingFinalizers();
            Assert.AreEqual(0, node.FindNode(7, 0, out depth));
            Assert.AreEqual(8, node.FindNode(8, 0, out depth));
            Assert.AreEqual(0, node.FindNode(9, 0, out depth));
            depth = 0;
            Assert.AreEqual(10, node.FindNode(10, 0, out depth));
            Assert.AreEqual(0, depth);
            Assert.AreEqual(0, node.FindNode(11, 0, out depth));
            Assert.AreEqual(12, node.FindNode(12, 0, out depth));
            Assert.AreEqual(0, node.FindNode(13, 0, out depth));
        }