DragonECS/src/Utils/ArrayUtility.cs

65 lines
2.0 KiB
C#
Raw Normal View History

2024-01-05 23:49:29 +08:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
2023-12-24 18:11:20 +08:00
using System.Runtime.InteropServices;
namespace DCFApixels.DragonECS.Utils
2023-04-08 00:47:35 +08:00
{
internal static class ArrayUtility
{
public static void Fill<T>(T[] array, T value, int startIndex = 0, int length = -1)
{
if (length < 0)
length = array.Length;
else
length = startIndex + length;
for (int i = startIndex; i < length; i++)
array[i] = value;
}
}
2023-12-24 18:11:20 +08:00
internal static unsafe class UnmanagedArrayUtility
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2023-12-31 17:58:20 +08:00
public static T* New<T>(int capacity) where T : unmanaged
2023-12-24 18:11:20 +08:00
{
2023-12-31 17:58:20 +08:00
return (T*)Marshal.AllocHGlobal(Marshal.SizeOf<T>() * capacity).ToPointer();
2023-12-24 18:11:20 +08:00
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2023-12-31 17:58:20 +08:00
public static T* NewAndInit<T>(int capacity) where T : unmanaged
2023-12-24 18:11:20 +08:00
{
int newSize = Marshal.SizeOf(typeof(T)) * capacity;
byte* newPointer = (byte*)Marshal.AllocHGlobal(newSize).ToPointer();
for (int i = 0; i < newSize; i++)
*(newPointer + i) = 0;
2023-12-31 17:58:20 +08:00
return (T*)newPointer;
2023-12-24 18:11:20 +08:00
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Free(void* pointer)
{
Marshal.FreeHGlobal(new IntPtr(pointer));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2023-12-31 17:58:20 +08:00
public static T* Resize<T>(void* oldPointer, int newCount) where T : unmanaged
2023-12-24 18:11:20 +08:00
{
2023-12-31 17:58:20 +08:00
return (T*)(Marshal.ReAllocHGlobal(
2023-12-24 18:11:20 +08:00
new IntPtr(oldPointer),
new IntPtr(Marshal.SizeOf(typeof(T)) * newCount))).ToPointer();
}
}
2024-01-05 23:49:29 +08:00
public static class EntitiesCollectionUtility
{
public static string AutoToString(IEnumerable<int> range, string name)
{
return $"{name}({range.Count()}) {{{string.Join(", ", range.OrderBy(o => o))}}})";
}
}
2023-04-08 00:47:35 +08:00
}