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 System.Buffers; 21 using System.Threading; 22 using Grpc.Core.Utils; 23 24 namespace Grpc.Core.Internal 25 { 26 internal class DefaultDeserializationContext : DeserializationContext 27 { 28 static readonly ThreadLocal<DefaultDeserializationContext> threadLocalInstance = 29 new ThreadLocal<DefaultDeserializationContext>(() => new DefaultDeserializationContext(), false); 30 31 IBufferReader bufferReader; 32 int payloadLength; 33 ReusableSliceBuffer cachedSliceBuffer = new ReusableSliceBuffer(); 34 DefaultDeserializationContext()35 public DefaultDeserializationContext() 36 { 37 Reset(); 38 } 39 40 public override int PayloadLength => payloadLength; 41 PayloadAsNewBuffer()42 public override byte[] PayloadAsNewBuffer() 43 { 44 var buffer = new byte[payloadLength]; 45 PayloadAsReadOnlySequence().CopyTo(buffer); 46 return buffer; 47 } 48 PayloadAsReadOnlySequence()49 public override ReadOnlySequence<byte> PayloadAsReadOnlySequence() 50 { 51 var sequence = cachedSliceBuffer.PopulateFrom(bufferReader); 52 GrpcPreconditions.CheckState(sequence.Length == payloadLength); 53 return sequence; 54 } 55 Initialize(IBufferReader bufferReader)56 public void Initialize(IBufferReader bufferReader) 57 { 58 this.bufferReader = GrpcPreconditions.CheckNotNull(bufferReader); 59 this.payloadLength = bufferReader.TotalLength.Value; // payload must not be null 60 } 61 Reset()62 public void Reset() 63 { 64 this.bufferReader = null; 65 this.payloadLength = 0; 66 this.cachedSliceBuffer.Invalidate(); 67 } 68 GetInitializedThreadLocal(IBufferReader bufferReader)69 public static DefaultDeserializationContext GetInitializedThreadLocal(IBufferReader bufferReader) 70 { 71 var instance = threadLocalInstance.Value; 72 instance.Initialize(bufferReader); 73 return instance; 74 } 75 } 76 } 77