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 System.Runtime.CompilerServices; 21 using System.Text; 22 using Grpc.Core.Api.Utils; 23 24 namespace Grpc.Core.Internal 25 { 26 /// <summary> 27 /// Useful methods for native/managed marshalling. 28 /// </summary> 29 internal static class MarshalUtils 30 { 31 static readonly Encoding EncodingUTF8 = System.Text.Encoding.UTF8; 32 33 /// <summary> 34 /// Converts <c>IntPtr</c> pointing to a UTF-8 encoded byte array to <c>string</c>. 35 /// </summary> 36 [MethodImpl(MethodImplOptions.AggressiveInlining)] PtrToStringUTF8(IntPtr ptr, int len)37 public static string PtrToStringUTF8(IntPtr ptr, int len) 38 { 39 return EncodingUTF8.GetString(ptr, len); 40 } 41 42 /// <summary> 43 /// UTF-8 encodes the given string into a buffer of sufficient size 44 /// </summary> GetBytesUTF8(string str, byte* destination, int destinationLength)45 public static unsafe int GetBytesUTF8(string str, byte* destination, int destinationLength) 46 { 47 int charCount = str.Length; 48 if (charCount == 0) return 0; 49 fixed (char* source = str) 50 { 51 return EncodingUTF8.GetBytes(source, charCount, destination, destinationLength); 52 } 53 } 54 55 /// <summary> 56 /// Returns the maximum number of bytes required to encode a given string. 57 /// </summary> 58 [MethodImpl(MethodImplOptions.AggressiveInlining)] GetMaxByteCountUTF8(string str)59 public static int GetMaxByteCountUTF8(string str) 60 { 61 return EncodingUTF8.GetMaxByteCount(str.Length); 62 } 63 64 /// <summary> 65 /// Returns the actual number of bytes required to encode a given string. 66 /// </summary> 67 [MethodImpl(MethodImplOptions.AggressiveInlining)] GetByteCountUTF8(string str)68 public static int GetByteCountUTF8(string str) 69 { 70 return EncodingUTF8.GetByteCount(str); 71 } 72 } 73 } 74