| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Buffers; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.Reflection.Metadata; |
| | | 7 | | using System.Runtime.InteropServices; |
| | | 8 | | |
| | | 9 | | namespace System.Reflection.Internal |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// Provides helpers to decode strings from unmanaged memory to System.String while avoiding |
| | | 13 | | /// intermediate allocation. |
| | | 14 | | /// </summary> |
| | | 15 | | internal static unsafe class EncodingHelper |
| | | 16 | | { |
| | | 17 | | public static string DecodeUtf8(byte* bytes, int byteCount, byte[]? prefix, MetadataStringDecoder utf8Decoder) |
| | 0 | 18 | | { |
| | 0 | 19 | | Debug.Assert(utf8Decoder != null); |
| | | 20 | | |
| | 0 | 21 | | if (prefix != null) |
| | 0 | 22 | | { |
| | 0 | 23 | | return DecodeUtf8Prefixed(bytes, byteCount, prefix, utf8Decoder); |
| | | 24 | | } |
| | | 25 | | |
| | 0 | 26 | | if (byteCount == 0) |
| | 0 | 27 | | { |
| | 0 | 28 | | return string.Empty; |
| | | 29 | | } |
| | | 30 | | |
| | 0 | 31 | | return utf8Decoder.GetString(bytes, byteCount); |
| | 0 | 32 | | } |
| | | 33 | | |
| | | 34 | | private static string DecodeUtf8Prefixed(byte* bytes, int byteCount, byte[] prefix, MetadataStringDecoder utf8De |
| | 0 | 35 | | { |
| | 0 | 36 | | Debug.Assert(utf8Decoder != null); |
| | | 37 | | |
| | 0 | 38 | | int prefixedByteCount = byteCount + prefix.Length; |
| | | 39 | | |
| | 0 | 40 | | if (prefixedByteCount == 0) |
| | 0 | 41 | | { |
| | 0 | 42 | | return string.Empty; |
| | | 43 | | } |
| | | 44 | | |
| | 0 | 45 | | byte[] buffer = ArrayPool<byte>.Shared.Rent(prefixedByteCount); |
| | | 46 | | |
| | 0 | 47 | | prefix.CopyTo(buffer, 0); |
| | 0 | 48 | | Marshal.Copy((IntPtr)bytes, buffer, prefix.Length, byteCount); |
| | | 49 | | |
| | | 50 | | string result; |
| | 0 | 51 | | fixed (byte* prefixedBytes = &buffer[0]) |
| | 0 | 52 | | { |
| | 0 | 53 | | result = utf8Decoder.GetString(prefixedBytes, prefixedByteCount); |
| | 0 | 54 | | } |
| | | 55 | | |
| | 0 | 56 | | ArrayPool<byte>.Shared.Return(buffer); |
| | 0 | 57 | | return result; |
| | 0 | 58 | | } |
| | | 59 | | } |
| | | 60 | | } |
| | | 61 | | |