Files
Misaki.HighPerformance/Misaki.HighPerformance.LowLevel/Collections/ReadOnlyUnsafeCollection.cs
Misaki 49e1171781
Some checks failed
Publish NuGet Packages / publish (push) Failing after 3m12s
Refactor and enhance math and utility libraries
Refactored `sincos` usage across `quaternion` and `random` to use `out` parameters for improved performance. Enhanced `random` struct with updated random direction generation methods.

Added new benchmarks in `MathematicsBenchmark` for vector operations, including SIMD-based `f4` struct. Downgraded target framework to `net9.0` for compatibility.

Introduced `ReadOnlyUnsafeCollection` for low-level memory management. Added utility methods in `CollectionUtility` for span creation and optimized list operations.

Renamed `MemoryUtilities` to `MemoryUtility` and updated all references. Enhanced `ObjectPool` with `Rent` and `TryRent` methods. Enabled `AllowUnsafeBlocks` and AOT compatibility in project configuration.

Performed general code cleanup, including removal of unused methods, improved formatting, and alignment with modern coding practices.
2025-11-04 14:53:01 +09:00

119 lines
4.1 KiB
C#

using Misaki.HighPerformance.LowLevel.Utilities;
using System.Collections;
using System.Runtime.CompilerServices;
namespace Misaki.HighPerformance.LowLevel.Collections;
/// <summary>
/// Provides a read-only, unsafe view over a contiguous region of unmanaged memory as an array of elements of type T.
/// Enables efficient, low-level access to memory without copying or additional safety checks.
/// </summary>
/// <remarks>
/// This read only collection does not own the memory it points to. The user is responsible for ensuring the memory remains valid for the lifetime of this structure.
/// The goal of this struc is similar to <see cref="ReadOnlySpan{T}"/>, but it can be used in contexts where spans are not allowed, such as fields in structs and shared across threads.
/// </remarks>
/// <typeparam name="T">The type of elements in the collection. Must be an unmanaged type.</typeparam>
public readonly unsafe struct ReadOnlyUnsafeCollection<T> : IEnumerable<T>
where T : unmanaged
{
public struct Enumerator : IEnumerator<T>
{
private readonly ReadOnlyUnsafeCollection<T> _collection;
private int _index;
private T _value;
public readonly T Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _value;
}
readonly object IEnumerator.Current => Current;
public Enumerator(ref readonly ReadOnlyUnsafeCollection<T> array)
{
_collection = array;
_index = -1;
_value = default;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
_index++;
if (_index < _collection.Count)
{
_value = UnsafeUtility.ReadArrayElement<T>(_collection._buffer, _index);
return true;
}
_value = default;
return false;
}
public void Reset()
{
_index = -1;
}
public void Dispose()
{
}
}
private readonly T* _buffer;
private readonly int _count;
public readonly int Count => _count;
public readonly T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => UnsafeUtility.ReadArrayElement<T>(_buffer, index);
}
public readonly T this[uint index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => UnsafeUtility.ReadArrayElement<T>(_buffer, index);
}
public IEnumerator<T> GetEnumerator() => new Enumerator(in this);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public ReadOnlyUnsafeCollection(T* buffer, int count)
{
_buffer = buffer;
_count = count;
}
/// <summary>
/// Returns a read-only span that represents the valid elements in the underlying buffer.
/// </summary>
/// <returns>A <see cref="ReadOnlySpan{T}"/> containing the elements of the buffer up to the current count.</returns>
public ReadOnlySpan<T> AsSpan()
{
return new ReadOnlySpan<T>(_buffer, _count);
}
/// <summary>
/// Reinterprets the underlying collection as a read-only collection of a different unmanaged type without copying the data.
/// </summary>
/// <typeparam name="U">The unmanaged type to reinterpret the collection elements as.</typeparam>
/// <returns>A new ReadOnlyUnsafeCollection<U> that provides a read-only view of the same memory, interpreted as elements of type U.</returns>
/// <exception cref="InvalidOperationException">Thrown if the total size of the underlying collection is not a multiple of the size of type U, making the reinterpretation invalid.</exception>
public ReadOnlyUnsafeCollection<U> Reinterpret<U>()
where U : unmanaged
{
var totalSize = (nuint)(Count * sizeof(T));
if (totalSize % (nuint)sizeof(U) != 0)
{
throw new InvalidOperationException("Cannot reinterpret collection: size mismatch.");
}
var newCount = (int)(totalSize / (nuint)sizeof(U));
return new ReadOnlyUnsafeCollection<U>((U*)_buffer, newCount);
}
}