Skip to content

Commit

Permalink
Use Unsafe.Add for PSQT() (#1153)
Browse files Browse the repository at this point in the history
- Use `Unsafe.Add` to properly avoid bound checks when querying PSQTs (if we're going unsafe, let's do it 'right' in the most performant way)
- Add Assert to for manually verify bounds in debug mode
  • Loading branch information
eduherminio authored Nov 12, 2024
1 parent 89fc772 commit e25b07c
Showing 1 changed file with 4 additions and 7 deletions.
11 changes: 4 additions & 7 deletions src/Lynx/PSQT.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using Lynx.Model;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using static Lynx.TunableEvalParameters;

namespace Lynx;
Expand Down Expand Up @@ -99,16 +101,11 @@ static EvaluationPSQTs()
public static int PSQT(int friendEnemy, int bucket, int piece, int square)
{
var index = PSQTIndex(friendEnemy, bucket, piece, square);
Debug.Assert(index >= 0 && index < _packedPSQT.Length);

unsafe
{
// Since _tt is a pinned array
// This is no-op pinning as it does not influence the GC compaction
// https://tooslowexception.com/pinned-object-heap-in-net-5/
fixed (int* psqtPtr = &_packedPSQT[0])
{
return psqtPtr[index];
}
return Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_packedPSQT), index);
}
}

Expand Down

0 comments on commit e25b07c

Please sign in to comment.