microsoft/teams.net

Public

mirrored fromhttps://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
aacebo/mcp-client

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

Libraries/Microsoft.Teams.Common/Storage/LocalStorage.cs

115lines · modecode

1namespace Microsoft.Teams.Common.Storage;
2
3/// <summary>
4/// a local in-memory `IStorage` implementation
5/// </summary>
6/// <typeparam name="TValue">the value type</typeparam>
7public class LocalStorage<TValue> : IStorage<string, TValue>
8{
9 protected Dictionary<string, TValue> _store = [];
10 protected IList<string> _keys = [];
11 protected int? _max;
12
13 /// <summary>
14 /// the number of items in the storage
15 /// </summary>
16 public int Size => _store.Count;
17
18 /// <summary>
19 /// get the list of storage keys
20 /// </summary>
21 public IList<string> Keys => _store.Keys.ToList();
22
23 public LocalStorage(int? max = null)
24 {
25 _max = max;
26 }
27
28 public LocalStorage(IDictionary<string, TValue> data, int? max)
29 {
30 _store = new Dictionary<string, TValue>(data);
31 _keys = data.Keys.ToList();
32 _max = max;
33 }
34
35 public bool Exists(string key) => _store.ContainsKey(key);
36 public Task<bool> ExistsAsync(string key) => Task.FromResult(Exists(key));
37
38 public TValue? Get(string key)
39 {
40 Hit(key);
41 return _store.TryGetValue(key, out var value) ? value : default;
42 }
43
44 public T? Get<T>(string key) where T : TValue
45 {
46 var value = Get(key);
47 return (T?)value;
48 }
49
50 public Task<TValue?> GetAsync(string key)
51 {
52 return Task.FromResult(Get(key));
53 }
54
55 public async Task<T?> GetAsync<T>(string key) where T : TValue
56 {
57 var value = await GetAsync(key);
58 return (T?)value;
59 }
60
61 public void Set(string key, TValue value)
62 {
63 if (!Hit(key)) _keys.Add(key);
64 if (_max is not null)
65 {
66 if (_keys.Count > _max)
67 {
68 var toRemove = _keys.ElementAt(0);
69 _keys.RemoveAt(0);
70 _store.Remove(toRemove);
71 }
72 }
73
74 _store[key] = value;
75 }
76
77 public Task SetAsync(string key, TValue value)
78 {
79 return Task.Run(() => Set(key, value));
80 }
81
82 public void Delete(string key)
83 {
84 var index = _keys.IndexOf(key);
85
86 if (index == -1) return;
87
88 _keys.RemoveAt(index);
89 _store.Remove(key);
90 }
91
92 public Task DeleteAsync(string key)
93 {
94 return Task.Run(() => Delete(key));
95 }
96
97 protected bool Hit(string key)
98 {
99 if (!Exists(key)) return false;
100 if (Keys.Last() == key) return true;
101
102 var index = _keys.IndexOf(key);
103
104 if (index < 0) return false;
105
106 for (var i = index + 1; i < _keys.Count; i++)
107 {
108 var tmp = _keys[i - 1];
109 _keys[i - 1] = _keys[i];
110 _keys[i] = tmp;
111 }
112
113 return true;
114 }
115}