1 // Licensed to the .NET Foundation under one or more agreements. 2 // The .NET Foundation licenses this file to you under the MIT license. 3 // See the LICENSE file in the project root for more information. 4 5 using Xunit; 6 using System.Runtime.CompilerServices; 7 using System.Runtime.InteropServices; 8 9 namespace System.SpanTests 10 { 11 public static partial class SpanTests 12 { 13 [Fact] NonPortableCastUIntToUShort()14 public static void NonPortableCastUIntToUShort() 15 { 16 uint[] a = { 0x44332211, 0x88776655 }; 17 Span<uint> span = new Span<uint>(a); 18 Span<ushort> asUShort = span.NonPortableCast<uint, ushort>(); 19 20 Assert.True(Unsafe.AreSame<ushort>(ref Unsafe.As<uint, ushort>(ref MemoryMarshal.GetReference(span)), ref MemoryMarshal.GetReference(asUShort))); 21 asUShort.Validate<ushort>(0x2211, 0x4433, 0x6655, 0x8877); 22 } 23 24 [Fact] NonPortableCastShortToLong()25 public static void NonPortableCastShortToLong() 26 { 27 short[] a = { 0x1234, 0x2345, 0x3456, 0x4567, 0x5678 }; 28 Span<short> span = new Span<short>(a); 29 Span<long> asLong = span.NonPortableCast<short, long>(); 30 31 Assert.True(Unsafe.AreSame<long>(ref Unsafe.As<short, long>(ref MemoryMarshal.GetReference(span)), ref MemoryMarshal.GetReference(asLong))); 32 asLong.Validate<long>(0x4567345623451234); 33 } 34 35 [Fact] NonPortableCastOverflow()36 public static unsafe void NonPortableCastOverflow() 37 { 38 Span<TestHelpers.TestStructExplicit> span = new Span<TestHelpers.TestStructExplicit>(null, Int32.MaxValue); 39 40 TestHelpers.AssertThrows<OverflowException, TestHelpers.TestStructExplicit>(span, (_span) => _span.NonPortableCast<TestHelpers.TestStructExplicit, byte>().DontBox()); 41 TestHelpers.AssertThrows<OverflowException, TestHelpers.TestStructExplicit>(span, (_span) => _span.NonPortableCast<TestHelpers.TestStructExplicit, ulong>().DontBox()); 42 } 43 44 [Fact] NonPortableCastToTypeContainsReferences()45 public static void NonPortableCastToTypeContainsReferences() 46 { 47 Span<uint> span = new Span<uint>(Array.Empty<uint>()); 48 TestHelpers.AssertThrows<ArgumentException, uint>(span, (_span) => _span.NonPortableCast<uint, StructWithReferences>().DontBox()); 49 } 50 51 [Fact] NonPortableCastFromTypeContainsReferences()52 public static void NonPortableCastFromTypeContainsReferences() 53 { 54 Span<StructWithReferences> span = new Span<StructWithReferences>(Array.Empty<StructWithReferences>()); 55 TestHelpers.AssertThrows<ArgumentException, StructWithReferences>(span, (_span) => _span.NonPortableCast<StructWithReferences, uint>().DontBox()); 56 } 57 } 58 } 59