|
| 1 | +// _ __ __ |
| 2 | +// ___ ___ ___ _ __ __| | __ _ | \/ | |
| 3 | +// / __|/ __| / _ \| '_ \ / _` | / _` || |\/| | |
| 4 | +// \__ \\__ \| __/| | | || (_| || (_| || | | | |
| 5 | +// |___/|___/ \___||_| |_| \__,_| \__,_||_| |_| |
| 6 | +// | |
| 7 | +// Copyright 2021-2022 Łukasz "JustArchi" Domeradzki |
| 8 | + |
| 9 | +// | |
| 10 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 11 | +// you may not use this file except in compliance with the License. |
| 12 | +// You may obtain a copy of the License at |
| 13 | +// | |
| 14 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 15 | +// | |
| 16 | +// Unless required by applicable law or agreed to in writing, software |
| 17 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 18 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 19 | +// See the License for the specific language governing permissions and |
| 20 | +// limitations under the License. |
| 21 | + |
| 22 | +#if !NETSTANDARD2_1_OR_GREATER |
| 23 | +using System.Runtime.InteropServices; |
| 24 | +using JetBrains.Annotations; |
| 25 | +using JustArchiNET.Madness.Helpers; |
| 26 | + |
| 27 | +// ReSharper disable once CheckNamespace - we intentionally declare this namespace |
| 28 | +namespace System.Runtime.CompilerServices; |
| 29 | + |
| 30 | +[MadnessType(EMadnessType.Implementation)] |
| 31 | +[PublicAPI] |
| 32 | +public static class RuntimeHelpers { |
| 33 | + public static int OffsetToStringData { |
| 34 | + get { |
| 35 | + switch (RuntimeInformation.ProcessArchitecture) { |
| 36 | + case Architecture.Arm: |
| 37 | + case Architecture.X86: |
| 38 | + return 8; |
| 39 | + default: |
| 40 | + return 12; |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + /// <summary> |
| 46 | + /// Slices the specified array using the specified range. |
| 47 | + /// </summary> |
| 48 | + public static T[] GetSubArray<T>(T[] array, Range range) { |
| 49 | + if (array == null) { |
| 50 | + throw new ArgumentNullException(nameof(array)); |
| 51 | + } |
| 52 | + |
| 53 | + (int offset, int length) = range.GetOffsetAndLength(array.Length); |
| 54 | + |
| 55 | + T[] dest; |
| 56 | + |
| 57 | + if (typeof(T).IsValueType || (typeof(T[]) == array.GetType())) { |
| 58 | + // We know the type of the array to be exactly T[]. |
| 59 | + |
| 60 | + if (length == 0) { |
| 61 | + return Array.Empty<T>(); |
| 62 | + } |
| 63 | + |
| 64 | + dest = new T[length]; |
| 65 | + Array.Copy(array, offset, dest, 0, length); |
| 66 | + } else { |
| 67 | + // The array is actually a U[] where U:T. |
| 68 | + dest = (T[]) Array.CreateInstance(array.GetType().GetElementType()!, length); |
| 69 | + Array.Copy(array, offset, dest, 0, length); |
| 70 | + } |
| 71 | + |
| 72 | + return dest; |
| 73 | + } |
| 74 | +} |
| 75 | +#endif |
0 commit comments