Skip to content

Commit 2ef1a2b

Browse files
committed
added extension method for System.Text.Encoding to support better use of spans in modern frameworks
1 parent 2523e09 commit 2ef1a2b

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using System;
2+
using System.Text;
3+
4+
namespace SysadminsLV.Asn1Parser.Utils.CLRExtensions;
5+
6+
/// <summary>
7+
/// Provides extension methods for the <see cref="System.Text.Encoding"/> class to enhance its functionality.
8+
/// </summary>
9+
static class EncodingExtensions {
10+
/// <summary>
11+
/// Decodes a sequence of bytes from the specified <see cref="ReadOnlyMemory{T}"/> into a string using the provided <see cref="System.Text.Encoding"/>.
12+
/// </summary>
13+
/// <param name="encoding">The <see cref="System.Text.Encoding"/> to use for decoding the byte sequence.</param>
14+
/// <param name="bytes">The byte sequence to decode, represented as a <see cref="ReadOnlyMemory{T}"/> of <see cref="Byte"/>.</param>
15+
/// <returns>A <see cref="String"/> that contains the decoded characters from the byte sequence.</returns>
16+
/// <exception cref="ArgumentNullException">Thrown if <paramref name="encoding"/> is <c>null</c>.</exception>
17+
public static String GetString(this Encoding encoding, ReadOnlyMemory<Byte> bytes) {
18+
#if NET8_0_OR_GREATER
19+
return encoding.GetString(bytes.Span);
20+
#else
21+
return encoding.GetString(bytes.ToArray());
22+
#endif
23+
}
24+
}

0 commit comments

Comments
 (0)