Ryujinx/Ryujinx.HLE/HOS/Kernel/KContextIdManager.cs

83 lines
2 KiB
C#
Raw Normal View History

using Ryujinx.Common;
using System;
namespace Ryujinx.HLE.HOS.Kernel
{
class KContextIdManager
{
private const int IdMasksCount = 8;
2018-12-01 21:01:59 +01:00
private int[] _idMasks;
2018-12-01 21:01:59 +01:00
private int _nextFreeBitHint;
public KContextIdManager()
{
2018-12-01 21:01:59 +01:00
_idMasks = new int[IdMasksCount];
}
public int GetId()
{
2018-12-01 21:01:59 +01:00
lock (_idMasks)
{
2018-12-01 21:01:59 +01:00
int id = 0;
2018-12-01 21:01:59 +01:00
if (!TestBit(_nextFreeBitHint))
{
2018-12-01 21:01:59 +01:00
id = _nextFreeBitHint;
}
else
{
2018-12-01 21:01:59 +01:00
for (int index = 0; index < IdMasksCount; index++)
{
2018-12-01 21:01:59 +01:00
int mask = _idMasks[index];
2018-12-01 21:01:59 +01:00
int firstFreeBit = BitUtils.CountLeadingZeros32((mask + 1) & ~mask);
2018-12-01 21:01:59 +01:00
if (firstFreeBit < 32)
{
2018-12-01 21:01:59 +01:00
int baseBit = index * 32 + 31;
2018-12-01 21:01:59 +01:00
id = baseBit - firstFreeBit;
break;
}
2018-12-01 21:01:59 +01:00
else if (index == IdMasksCount - 1)
{
throw new InvalidOperationException("Maximum number of Ids reached!");
}
}
}
2018-12-01 21:01:59 +01:00
_nextFreeBitHint = id + 1;
2018-12-01 21:01:59 +01:00
SetBit(id);
2018-12-01 21:01:59 +01:00
return id;
}
}
2018-12-01 21:01:59 +01:00
public void PutId(int id)
{
2018-12-01 21:01:59 +01:00
lock (_idMasks)
{
2018-12-01 21:01:59 +01:00
ClearBit(id);
}
}
2018-12-01 21:01:59 +01:00
private bool TestBit(int bit)
{
2018-12-01 21:01:59 +01:00
return (_idMasks[_nextFreeBitHint / 32] & (1 << (_nextFreeBitHint & 31))) != 0;
}
2018-12-01 21:01:59 +01:00
private void SetBit(int bit)
{
2018-12-01 21:01:59 +01:00
_idMasks[_nextFreeBitHint / 32] |= (1 << (_nextFreeBitHint & 31));
}
2018-12-01 21:01:59 +01:00
private void ClearBit(int bit)
{
2018-12-01 21:01:59 +01:00
_idMasks[_nextFreeBitHint / 32] &= ~(1 << (_nextFreeBitHint & 31));
}
}
}