1 #region Copyright notice and license 2 3 // Copyright 2015 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.Utils; 21 22 namespace Grpc.Core 23 { 24 /// <summary> 25 /// Encapsulates the logic for serializing and deserializing messages. 26 /// </summary> 27 public class Marshaller<T> 28 { 29 readonly Func<T, byte[]> serializer; 30 readonly Func<byte[], T> deserializer; 31 32 /// <summary> 33 /// Initializes a new marshaller. 34 /// </summary> 35 /// <param name="serializer">Function that will be used to serialize messages.</param> 36 /// <param name="deserializer">Function that will be used to deserialize messages.</param> Marshaller(Func<T, byte[]> serializer, Func<byte[], T> deserializer)37 public Marshaller(Func<T, byte[]> serializer, Func<byte[], T> deserializer) 38 { 39 this.serializer = GrpcPreconditions.CheckNotNull(serializer, "serializer"); 40 this.deserializer = GrpcPreconditions.CheckNotNull(deserializer, "deserializer"); 41 } 42 43 /// <summary> 44 /// Gets the serializer function. 45 /// </summary> 46 public Func<T, byte[]> Serializer 47 { 48 get 49 { 50 return this.serializer; 51 } 52 } 53 54 /// <summary> 55 /// Gets the deserializer function. 56 /// </summary> 57 public Func<byte[], T> Deserializer 58 { 59 get 60 { 61 return this.deserializer; 62 } 63 } 64 } 65 66 /// <summary> 67 /// Utilities for creating marshallers. 68 /// </summary> 69 public static class Marshallers 70 { 71 /// <summary> 72 /// Creates a marshaller from specified serializer and deserializer. 73 /// </summary> Create(Func<T, byte[]> serializer, Func<byte[], T> deserializer)74 public static Marshaller<T> Create<T>(Func<T, byte[]> serializer, Func<byte[], T> deserializer) 75 { 76 return new Marshaller<T>(serializer, deserializer); 77 } 78 79 /// <summary> 80 /// Returns a marshaller for <c>string</c> type. This is useful for testing. 81 /// </summary> 82 public static Marshaller<string> StringMarshaller 83 { 84 get 85 { 86 return new Marshaller<string>(System.Text.Encoding.UTF8.GetBytes, 87 System.Text.Encoding.UTF8.GetString); 88 } 89 } 90 } 91 } 92