Merge pull request #245 from hulkhan22/fix/duplicate-ids-during-inventory-lootgen

fix: Ensure unique MongoIDs
This commit is contained in:
Chomp
2025-05-07 14:30:50 +01:00
committed by GitHub
3 changed files with 35 additions and 2 deletions
@@ -28,7 +28,7 @@ public partial class HashUtil(RandomUtil _randomUtil)
objectId[3] = (byte) timestamp;
// Random value (5 bytes)
_randomUtil.Random.NextBytes(objectId.Slice(4, 5));
_randomUtil.NextBytes(objectId.Slice(4, 5));
// Incrementing counter (3 bytes)
// 24-bit counter
@@ -35,7 +35,7 @@ public class RandomUtil(ISptLogger<RandomUtil> _logger, ICloner _cloner)
max -= 1;
}
return max > min ? Random.Next(min, exclusive ? max : max + 1) : min;
return max > min ? Random.Shared.Next(min, exclusive ? max : max + 1) : min;
}
/// <summary>
@@ -64,6 +64,11 @@ public class RandomUtil(ISptLogger<RandomUtil> _logger, ICloner _cloner)
return Random.Next(0, 2) == 1;
}
public void NextBytes(Span<byte> bytes)
{
Random.Shared.NextBytes(bytes);
}
/// <summary>
/// Calculates the percentage of a given number and returns the result.
/// </summary>
+28
View File
@@ -1,3 +1,5 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using SPTarkov.Server.Core.Utils;
using SPTarkov.Server.Core.Utils.Cloners;
using UnitTests.Mock;
@@ -63,4 +65,30 @@ public class HashUtilTests
failMessage
);
}
[TestMethod]
public void MultiThreadedMongoIDGenerationTest()
{
var concurrentBag = new ConcurrentBag<string>();
var random = new Random();
var stopwatch = new Stopwatch();
stopwatch.Start();
Parallel.For(0, 1000, i =>
{
Thread.Sleep(random.Next(0, 10));
var mongoId = _hashUtil.Generate();
concurrentBag.Add(mongoId);
});
stopwatch.Stop();
Console.WriteLine($"Elapsed time: {stopwatch.ElapsedMilliseconds} ms");
var uniqueCount = concurrentBag.Distinct().Count();
var totalCount = concurrentBag.Count;
Assert.AreEqual(
totalCount,
uniqueCount,
$"Expected all generated MongoId's to be unique, but found {totalCount - uniqueCount} duplicates."
);
}
}