1 #region Copyright notice and license 2 // Copyright 2019 The gRPC Authors 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 #endregion 16 17 using System; 18 using System.Runtime.CompilerServices; 19 using System.Text; 20 21 namespace Grpc.Core.Api.Utils 22 { 23 24 internal static class EncodingExtensions 25 { 26 #if NET45 // back-fill over a method missing in NET45 27 /// <summary> 28 /// Converts <c>byte*</c> pointing to an encoded byte array to a <c>string</c> using the provided <c>Encoding</c>. 29 /// </summary> GetString(this Encoding encoding, byte* source, int byteCount)30 public static unsafe string GetString(this Encoding encoding, byte* source, int byteCount) 31 { 32 if (byteCount == 0) return ""; // most callers will have already checked, but: make sure 33 34 // allocate a right-sized string and decode into it 35 int charCount = encoding.GetCharCount(source, byteCount); 36 string s = new string('\0', charCount); 37 fixed (char* cPtr = s) 38 { 39 encoding.GetChars(source, byteCount, cPtr, charCount); 40 } 41 return s; 42 } 43 #endif 44 /// <summary> 45 /// Converts <c>IntPtr</c> pointing to a encoded byte array to a <c>string</c> using the provided <c>Encoding</c>. 46 /// </summary> 47 [MethodImpl(MethodImplOptions.AggressiveInlining)] GetString(this Encoding encoding, IntPtr ptr, int len)48 public static unsafe string GetString(this Encoding encoding, IntPtr ptr, int len) 49 { 50 return len == 0 ? "" : encoding.GetString((byte*)ptr.ToPointer(), len); 51 } 52 } 53 54 } 55