Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed an off by 1 issue related to maxmium GeneratorId. #62

Merged
merged 2 commits into from
May 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions IdGen/IdGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ public IdGenerator(int generatorId, IdGeneratorOptions options)
_generatorid = generatorId;
Options = options ?? throw new ArgumentNullException(nameof(options));

var maxgeneratorid = 1U << Options.IdStructure.GeneratorIdBits;
var maxgeneratorid = (1U << Options.IdStructure.GeneratorIdBits) - 1;

if (_generatorid < 0 || _generatorid >= maxgeneratorid)
if (_generatorid < 0 || _generatorid > maxgeneratorid)
{
throw new ArgumentOutOfRangeException(nameof(generatorId), $"GeneratorId must be between 0 and {maxgeneratorid - 1}.");
throw new ArgumentOutOfRangeException(nameof(generatorId), $"GeneratorId must be from 0 to {maxgeneratorid}.");
}

// Precalculate some values
Expand Down
26 changes: 23 additions & 3 deletions IdGenTests/IdGeneratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,16 +78,36 @@ public void GeneratorId_ShouldBeMasked_WhenReadFromProperty()
Assert.AreEqual((1 << g.Options.IdStructure.GeneratorIdBits) - 1, g.Id);
}

[TestMethod]
public void Constructor_DoesNotThrow_OnMaxGeneratorId()
{
var structure = new IdStructure(41, 10, 12);
// 1023 is the max generator id for 10 bits.
var maxgeneratorid = 1023;
new IdGenerator(maxgeneratorid, new IdGeneratorOptions(structure));
}

[TestMethod]
public void Constructor_DoesNotThrow_OnGeneratorId_0()
{
new IdGenerator(0, new IdGeneratorOptions(new IdStructure(41, 10, 12)));
}

[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Constructor_Throws_OnNull_Options()
=> new IdGenerator(1024, null!);


[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void Constructor_Throws_OnInvalidGeneratorId_Positive()
=> new IdGenerator(1024, new IdGeneratorOptions(new IdStructure(41, 10, 12)));
public void Constructor_Throws_OnInvalidGeneratorId_Positive_MaxPlusOne()
{
var structure = new IdStructure(41, 10, 12);
// 1023 is the max generator id for 10 bits.
var maxgeneratorid = 1023;
int maxPlusOne = maxgeneratorid + 1;
new IdGenerator(maxPlusOne, new IdGeneratorOptions(structure));
}

[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
Expand Down