|
5 | 5 | using System; |
6 | 6 | using System.Linq; |
7 | 7 | using System.Reflection; |
| 8 | +using System.Runtime.CompilerServices; |
8 | 9 | using System.Text; |
9 | 10 | using Microsoft.Toolkit.HighPerformance.Buffers; |
10 | 11 | using Microsoft.VisualStudio.TestTools.UnitTesting; |
@@ -126,6 +127,40 @@ public void Test_StringPool_Add_Misc() |
126 | 127 | Assert.AreSame(windowsCommunityToolkit, windowsCommunityToolkit2); |
127 | 128 | } |
128 | 129 |
|
| 130 | + [TestCategory("StringPool")] |
| 131 | + [TestMethod] |
| 132 | + public void Test_StringPool_Add_Overwrite() |
| 133 | + { |
| 134 | + var pool = new StringPool(); |
| 135 | + |
| 136 | + var today = DateTime.Today; |
| 137 | + |
| 138 | + var text1 = ToStringNoInlining(today); |
| 139 | + |
| 140 | + pool.Add(text1); |
| 141 | + |
| 142 | + Assert.IsTrue(pool.TryGet(text1.AsSpan(), out string? result)); |
| 143 | + |
| 144 | + Assert.AreSame(text1, result); |
| 145 | + |
| 146 | + var text2 = ToStringNoInlining(today); |
| 147 | + |
| 148 | + pool.Add(text2); |
| 149 | + |
| 150 | + Assert.IsTrue(pool.TryGet(text2.AsSpan(), out result)); |
| 151 | + |
| 152 | + Assert.AreNotSame(text1, result); |
| 153 | + Assert.AreSame(text2, result); |
| 154 | + } |
| 155 | + |
| 156 | + // Separate method just to ensure the JIT can't optimize things away |
| 157 | + // and make the test fail because different string instances are interned |
| 158 | + [MethodImpl(MethodImplOptions.NoInlining)] |
| 159 | + private static string ToStringNoInlining(object obj) |
| 160 | + { |
| 161 | + return obj.ToString(); |
| 162 | + } |
| 163 | + |
129 | 164 | [TestCategory("StringPool")] |
130 | 165 | [TestMethod] |
131 | 166 | public void Test_StringPool_GetOrAdd_String_Empty() |
|
0 commit comments