forked from Taritsyn/JavaScriptEngineSwitcher
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncodingHelpers.cs
More file actions
53 lines (48 loc) · 1.11 KB
/
EncodingHelpers.cs
File metadata and controls
53 lines (48 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#if NET471 || NETSTANDARD
using System;
using System.Runtime.InteropServices;
#endif
using System.Text;
namespace JavaScriptEngineSwitcher.ChakraCore.Helpers
{
/// <summary>
/// Encoding helpers
/// </summary>
internal static class EncodingHelpers
{
#if NET471 || NETSTANDARD
public static unsafe string UnicodeToUtf8(string value, out int byteCount)
#else
public static string UnicodeToUtf8(string value, out int byteCount)
#endif
{
if (string.IsNullOrEmpty(value))
{
byteCount = 0;
return value;
}
string result;
#if NET471 || NETSTANDARD
byteCount = Encoding.UTF8.GetByteCount(value);
IntPtr bufferPtr = Marshal.AllocHGlobal(byteCount);
try
{
fixed (char* pValue = value)
{
Encoding.UTF8.GetBytes(pValue, value.Length, (byte*)bufferPtr, byteCount);
}
result = Encoding.GetEncoding(0).GetString((byte*)bufferPtr, byteCount);
}
finally
{
Marshal.FreeHGlobal(bufferPtr);
}
#else
byte[] bytes = Encoding.UTF8.GetBytes(value);
byteCount = bytes.Length;
result = Encoding.GetEncoding(0).GetString(bytes);
#endif
return result;
}
}
}