forked from grpc/grpc
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
make use of Encoding.GetString(byte*, int) when available; poly-fill …
…when not available (NET45); move related logic to extension class
- Loading branch information
Showing
3 changed files
with
45 additions
and
31 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
using System; | ||
using System.Text; | ||
|
||
namespace Grpc.Core.Api.Utils | ||
{ | ||
|
||
internal static class EncodingExtensions | ||
{ | ||
#if NET45 // back-fill over a method missing in NET45 | ||
/// <summary> | ||
/// Converts <c>byte*</c> pointing to an encoded byte array to a <c>string</c> using the provided <c>Encoding</c>. | ||
/// </summary> | ||
public static unsafe string GetString(this Encoding encoding, byte* source, int byteCount) | ||
{ | ||
if (byteCount == 0) return ""; // most callers will have already checked, but: make sure | ||
|
||
// allocate a right-sized string and decode into it | ||
int charCount = encoding.GetCharCount(source, byteCount); | ||
string s = new string('\0', charCount); | ||
fixed (char* cPtr = s) | ||
{ | ||
encoding.GetChars(source, byteCount, cPtr, charCount); | ||
} | ||
return s; | ||
} | ||
#endif | ||
/// <summary> | ||
/// Converts <c>IntPtr</c> pointing to a encoded byte array to a <c>string</c> using the provided <c>Encoding</c>. | ||
/// </summary> | ||
public static unsafe string GetString(this Encoding encoding, IntPtr ptr, int len) | ||
{ | ||
return len == 0 ? "" : encoding.GetString((byte*)ptr.ToPointer(), len); | ||
} | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters