Files
whitemagic/WhiteMagicTest/MarshalCacheTests.cs
T
2026-07-21 22:30:10 +02:00

112 lines
2.8 KiB
C#

using System.Runtime.InteropServices;
using WhiteMagic;
namespace WhiteMagicTest;
/// <summary>
/// Tests for <see cref="MarshalCache{T}"/>: blittable size, marshal-required flag,
/// IsIntPtr, and computed-once behavior.
/// </summary>
public class MarshalCacheTests
{
[Fact]
public void Size_for_int_is_4()
{
Assert.Equal(4, MarshalCache<int>.Size);
}
[Fact]
public void Size_for_byte_is_1()
{
Assert.Equal(1, MarshalCache<byte>.Size);
}
[Fact]
public void Size_for_IntPtr_matches_native_pointer_size()
{
Assert.Equal(IntPtr.Size, MarshalCache<IntPtr>.Size);
}
[Fact]
public void Size_for_bool_is_1()
{
Assert.Equal(1, MarshalCache<bool>.Size);
}
[Fact]
public void Size_for_enum_matches_underlying_type()
{
Assert.Equal(4, MarshalCache<DayOfWeek>.Size);
}
[Fact]
public void Size_for_blittable_struct_is_accurate()
{
Assert.Equal(8, MarshalCache<BlittableStruct>.Size);
}
[Fact]
public void TypeRequiresMarshal_is_false_for_blittable_types()
{
Assert.False(MarshalCache<int>.TypeRequiresMarshal);
Assert.False(MarshalCache<long>.TypeRequiresMarshal);
Assert.False(MarshalCache<BlittableStruct>.TypeRequiresMarshal);
}
[Fact]
public void TypeRequiresMarshal_is_true_for_types_with_MarshalAs_field()
{
Assert.True(MarshalCache<MarshalAsStruct>.TypeRequiresMarshal);
}
[Fact]
public void IsIntPtr_is_true_for_IntPtr()
{
Assert.True(MarshalCache<IntPtr>.IsIntPtr);
}
[Fact]
public void IsIntPtr_is_false_for_non_IntPtr_types()
{
Assert.False(MarshalCache<int>.IsIntPtr);
Assert.False(MarshalCache<long>.IsIntPtr);
Assert.False(MarshalCache<BlittableStruct>.IsIntPtr);
}
[Fact]
public void All_properties_are_computed_once_and_cached()
{
int size1 = MarshalCache<int>.Size;
bool marshal1 = MarshalCache<int>.TypeRequiresMarshal;
bool intPtr1 = MarshalCache<int>.IsIntPtr;
int size2 = MarshalCache<int>.Size;
bool marshal2 = MarshalCache<int>.TypeRequiresMarshal;
bool intPtr2 = MarshalCache<int>.IsIntPtr;
Assert.Equal(size1, size2);
Assert.Equal(marshal1, marshal2);
Assert.Equal(intPtr1, intPtr2);
}
[Fact]
public void SizeU_matches_Size_as_uint()
{
Assert.Equal((uint)MarshalCache<int>.Size, MarshalCache<int>.SizeU);
}
[StructLayout(LayoutKind.Sequential)]
private struct BlittableStruct
{
public int X;
public int Y;
}
[StructLayout(LayoutKind.Sequential)]
private struct MarshalAsStruct
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] Data;
}
}