1 #region Copyright notice and license
3 // Copyright 2018 The gRPC Authors
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
9 // http://www.apache.org/licenses/LICENSE-2.0
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.
20 using System.Collections.Generic;
21 using System.Runtime.InteropServices;
22 using System.Threading.Tasks;
24 using Grpc.Core.Internal;
25 using Grpc.Core.Utils;
27 namespace Grpc.Core.Internal.Tests
29 // Creates instances of fake IBufferReader. All created instances will become invalid once Dispose is called.
30 internal class FakeBufferReaderManager : IDisposable
32 List<GCHandle> pinnedHandles = new List<GCHandle>();
33 bool disposed = false;
34 public IBufferReader CreateSingleSegmentBufferReader(byte[] data)
36 return CreateMultiSegmentBufferReader(new List<byte[]> { data });
39 public IBufferReader CreateMultiSegmentBufferReader(IEnumerable<byte[]> dataSegments)
41 GrpcPreconditions.CheckState(!disposed);
42 GrpcPreconditions.CheckNotNull(dataSegments);
43 var segments = new List<GCHandle>();
44 foreach (var data in dataSegments)
46 GrpcPreconditions.CheckNotNull(data);
47 segments.Add(GCHandle.Alloc(data, GCHandleType.Pinned));
49 pinnedHandles.AddRange(segments); // all the allocated GCHandles will be freed on Dispose()
50 return new FakeBufferReader(segments);
53 public IBufferReader CreateNullPayloadBufferReader()
55 GrpcPreconditions.CheckState(!disposed);
56 return new FakeBufferReader(null);
64 for (int i = 0; i < pinnedHandles.Count; i++)
66 pinnedHandles[i].Free();
71 private class FakeBufferReader : IBufferReader
73 readonly List<GCHandle> bufferSegments;
74 readonly int? totalLength;
75 readonly IEnumerator<GCHandle> segmentEnumerator;
77 public FakeBufferReader(List<GCHandle> bufferSegments)
79 this.bufferSegments = bufferSegments;
80 this.totalLength = ComputeTotalLength(bufferSegments);
81 this.segmentEnumerator = bufferSegments?.GetEnumerator();
84 public int? TotalLength => totalLength;
86 public bool TryGetNextSlice(out Slice slice)
88 GrpcPreconditions.CheckNotNull(bufferSegments);
89 if (!segmentEnumerator.MoveNext())
91 slice = default(Slice);
95 var segment = segmentEnumerator.Current;
96 int sliceLen = ((byte[]) segment.Target).Length;
97 slice = new Slice(segment.AddrOfPinnedObject(), sliceLen);
101 static int? ComputeTotalLength(List<GCHandle> bufferSegments)
103 if (bufferSegments == null)
109 foreach (var segment in bufferSegments)
111 var data = (byte[]) segment.Target;