Skip to content

Uses Int32.LeadingZeroCount on .NET 7.0 or greater #24

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
4 changes: 2 additions & 2 deletions src/Nanoid/Nanoid.cs
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ private static string GenerateImpl(Random random, string alphabet = Alphabets.De
// mistake security-wise.

// Use `Int32.LeadingZeroCount` on .net7 and above
#if NET7_0
#if NET7_0_OR_GREATER
var mask = (2 << 31 - Int32.LeadingZeroCount(alphabet.Length - 1 | 1)) - 1;
#else
var mask = (2 << 31 - Clz32((alphabet.Length - 1) | 1)) - 1;
Expand Down Expand Up @@ -298,7 +298,7 @@ private static string GenerateImpl(Random random, string alphabet = Alphabets.De
}

// On dotnet7 and above we use `Int32.LeadingZeroCount` instead of this.
#if !NET7_0
#if !NET7_0_OR_GREATER
/// <summary>
/// Counts leading zeros of <paramref name="x"/>.
/// </summary>
Expand Down
4 changes: 2 additions & 2 deletions test/Nanoid.Test/NanoidTest.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using System.Linq;

namespace NanoidDotNet.Test
{
Expand Down Expand Up @@ -136,7 +136,7 @@ public void TestMask()
for (var length = 1; length < 256; length++)
{
var mask1 = (2 << (int)Math.Floor(Math.Log(length - 1) / Math.Log(2))) - 1;
#if NET7_0
#if NET7_0_OR_GREATER
var mask2 = (2 << 31 - Int32.LeadingZeroCount((length - 1) | 1)) - 1;
#else
var mask2 = (2 << 31 - Nanoid.Clz32((length - 1) | 1)) - 1;
Expand Down