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
49 lines (41 loc) · 1.05 KB
/
EncodingHelpers.cs
File metadata and controls
49 lines (41 loc) · 1.05 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
#if NET45 || NET471 || NETSTANDARD || NETCOREAPP2_1
using System.Buffers;
#endif
using System.Text;
#if NET40
using PolyfillsForOldDotNet.System.Buffers;
#endif
namespace JavaScriptEngineSwitcher.ChakraCore.Helpers
{
/// <summary>
/// Encoding helpers
/// </summary>
internal static class EncodingHelpers
{
public static string UnicodeToAnsi(string value, out int byteCount)
{
if (string.IsNullOrEmpty(value))
{
byteCount = 0;
return value;
}
Encoding utf8Encoding = Encoding.UTF8;
Encoding ansiEncoding = Encoding.GetEncoding(0);
var byteArrayPool = ArrayPool<byte>.Shared;
int bufferLength = utf8Encoding.GetByteCount(value);
byte[] buffer = byteArrayPool.Rent(bufferLength);
unsafe
{
fixed (char* pValue = value)
fixed (byte* pBuffer = buffer)
{
utf8Encoding.GetBytes(pValue, value.Length, pBuffer, bufferLength);
}
}
string result = ansiEncoding.GetString(buffer, 0, bufferLength);
byteCount = ansiEncoding.GetByteCount(result);
byteArrayPool.Return(buffer);
return result;
}
}
}