Example #1
0
        public void ReadWriteSpanArray_RoundTrip()
        {
            using var buffer = new HGlobalBuffer(200);

            int[] intArray = new int[] { 11, 22, 33, 44 };
            TestArray(intArray);
            TestSpan <int>(intArray);

            TestStruct[] structArray = new TestStruct[]
            {
                new TestStruct {
                    I = 11, L = 22, D = 33
                },
                new TestStruct {
                    I = 44, L = 55, D = 66
                },
                new TestStruct {
                    I = 77, L = 88, D = 99
                },
                new TestStruct {
                    I = 100, L = 200, D = 300
                },
            };
            TestArray(structArray);
            TestSpan <TestStruct>(structArray);

            void TestArray <T>(T[] data)
                where T : struct
            {
                T[] destination = new T[data.Length];
                buffer.WriteArray(0, data, 0, data.Length);
                buffer.ReadArray(0, destination, 0, data.Length);
                Assert.Equal(data, destination);
            }

            void TestSpan <T>(ReadOnlySpan <T> data)
                where T : unmanaged
            {
                Span <T> destination = stackalloc T[data.Length];

                buffer.WriteSpan(0, data);
                buffer.ReadSpan(0, destination);
                for (int i = 0; i < data.Length; i++)
                {
                    Assert.Equal(data[i], destination[i]);
                }
            }
        }