Rev | Line | |
---|
[12503] | 1 | using System;
|
---|
| 2 | using System.Collections.Generic;
|
---|
| 3 | using System.Linq;
|
---|
| 4 | using System.Text;
|
---|
| 5 | using System.Diagnostics.Contracts;
|
---|
| 6 |
|
---|
| 7 | namespace Microsoft.Research.DynamicDataDisplay.Common
|
---|
| 8 | {
|
---|
| 9 | /// <summary>
|
---|
| 10 | /// Represents a dictionary with automatic removal of old values.
|
---|
| 11 | /// </summary>
|
---|
| 12 | /// <typeparam name="T"></typeparam>
|
---|
| 13 | public sealed class RingDictionary<T>
|
---|
| 14 | {
|
---|
| 15 | private int startGeneration = 0;
|
---|
| 16 | private int generation;
|
---|
| 17 | private readonly Dictionary<int, T> dict = new Dictionary<int, T>();
|
---|
| 18 | private readonly int maxElements = 5;
|
---|
| 19 |
|
---|
| 20 | public RingDictionary(int maxElements = 5)
|
---|
| 21 | {
|
---|
| 22 | Contract.Assert(maxElements >= 1);
|
---|
| 23 |
|
---|
| 24 | this.maxElements = maxElements;
|
---|
| 25 | }
|
---|
| 26 |
|
---|
| 27 | public int Generation
|
---|
| 28 | {
|
---|
| 29 | get { return generation; }
|
---|
| 30 | }
|
---|
| 31 |
|
---|
| 32 | public int StartGeneration
|
---|
| 33 | {
|
---|
| 34 | get { return startGeneration; }
|
---|
| 35 | }
|
---|
| 36 |
|
---|
| 37 | public bool ContainsValue(T value)
|
---|
| 38 | {
|
---|
| 39 | return dict.ContainsValue(value);
|
---|
| 40 | }
|
---|
| 41 |
|
---|
| 42 | public void AddValue(T value)
|
---|
| 43 | {
|
---|
| 44 | Contract.Assert(value != null);
|
---|
| 45 |
|
---|
| 46 | dict.Add(generation++, value);
|
---|
| 47 | Cleanup();
|
---|
| 48 | }
|
---|
| 49 |
|
---|
| 50 | public int Count
|
---|
| 51 | {
|
---|
| 52 | get { return dict.Count; }
|
---|
| 53 | }
|
---|
| 54 |
|
---|
| 55 | private void Cleanup()
|
---|
| 56 | {
|
---|
| 57 | while ((generation - startGeneration) > maxElements)
|
---|
| 58 | {
|
---|
| 59 | dict.Remove(startGeneration);
|
---|
| 60 | startGeneration++;
|
---|
| 61 | }
|
---|
| 62 | }
|
---|
| 63 | }
|
---|
| 64 | }
|
---|
Note: See
TracBrowser
for help on using the repository browser.