-
Notifications
You must be signed in to change notification settings - Fork 681
Expand file tree
/
Copy pathEncodingExtensions.cs
More file actions
69 lines (60 loc) · 1.63 KB
/
EncodingExtensions.cs
File metadata and controls
69 lines (60 loc) · 1.63 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#if !NET
namespace System.Text;
internal static class EncodingExtensions
{
/// <summary>
/// Gets the number of bytes required to encode the specified characters.
/// </summary>
public static int GetByteCount(this Encoding encoding, ReadOnlySpan<char> chars)
{
if (chars.IsEmpty)
{
return 0;
}
unsafe
{
fixed (char* charsPtr = chars)
{
return encoding.GetByteCount(charsPtr, chars.Length);
}
}
}
/// <summary>
/// Encodes the specified characters into the specified byte span.
/// </summary>
public static int GetBytes(this Encoding encoding, ReadOnlySpan<char> chars, Span<byte> bytes)
{
if (chars.IsEmpty)
{
return 0;
}
unsafe
{
fixed (char* charsPtr = chars)
fixed (byte* bytesPtr = bytes)
{
return encoding.GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length);
}
}
}
/// <summary>
/// Decodes all the bytes in the specified span into a string.
/// </summary>
public static string GetString(this Encoding encoding, ReadOnlySpan<byte> bytes)
{
if (bytes.IsEmpty)
{
return string.Empty;
}
unsafe
{
fixed (byte* bytesPtr = bytes)
{
return encoding.GetString(bytesPtr, bytes.Length);
}
}
}
}
#endif