1 #region Copyright notice and license 2 3 // Copyright 2018 The gRPC Authors 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 17 #endregion 18 19 using System; 20 using Grpc.Core; 21 using Grpc.Core.Internal; 22 using Grpc.Core.Utils; 23 using NUnit.Framework; 24 25 using System.Runtime.InteropServices; 26 27 namespace Grpc.Core.Internal.Tests 28 { 29 public class SliceTest 30 { 31 [TestCase(0)] 32 [TestCase(1)] 33 [TestCase(10)] 34 [TestCase(100)] 35 [TestCase(1000)] SliceFromNativePtr_Copy(int bufferLength)36 public void SliceFromNativePtr_Copy(int bufferLength) 37 { 38 var origBuffer = GetTestBuffer(bufferLength); 39 var gcHandle = GCHandle.Alloc(origBuffer, GCHandleType.Pinned); 40 try 41 { 42 var slice = new Slice(gcHandle.AddrOfPinnedObject(), origBuffer.Length); 43 Assert.AreEqual(bufferLength, slice.Length); 44 45 var newBuffer = new byte[bufferLength]; 46 slice.ToSpanUnsafe().CopyTo(newBuffer); 47 CollectionAssert.AreEqual(origBuffer, newBuffer); 48 } 49 finally 50 { 51 gcHandle.Free(); 52 } 53 } 54 55 // create a buffer of given size and fill it with some data GetTestBuffer(int length)56 private byte[] GetTestBuffer(int length) 57 { 58 var testBuffer = new byte[length]; 59 for (int i = 0; i < testBuffer.Length; i++) 60 { 61 testBuffer[i] = (byte) i; 62 } 63 return testBuffer; 64 } 65 } 66 } 67