Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of Dread v1.6.1
BepInEx/plugins/elytraking-Dread/Dread.dll
Decompiled a week ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Threading; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Dread.Config; using Dread.Systems; using HarmonyLib; using Microsoft.CodeAnalysis; using NVorbis; using UnityEngine; using UnityEngine.AI; using UnityEngine.Networking; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("Dread")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+49218814e949aff1f8c5034f59e79d37d90a0126")] [assembly: AssemblyProduct("Dread")] [assembly: AssemblyTitle("Dread")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [CompilerGenerated] internal sealed class <>z__ReadOnlyArray<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T> { int ICollection.Count => _items.Length; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection<T>.Count => _items.Length; T IReadOnlyList<T>.this[int index] => _items[index]; int ICollection<T>.Count => _items.Length; bool ICollection<T>.IsReadOnly => true; T IList<T>.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } public <>z__ReadOnlyArray(T[] items) { _items = items; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { ((ICollection)_items).CopyTo(array, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return ((IList)_items).Contains(value); } int IList.IndexOf(object value) { return ((IList)_items).IndexOf(value); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return ((IEnumerable<T>)_items).GetEnumerator(); } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T item) { return ((ICollection<T>)_items).Contains(item); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { ((ICollection<T>)_items).CopyTo(array, arrayIndex); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } int IList<T>.IndexOf(T item) { return ((IList<T>)_items).IndexOf(item); } void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Dread { [BepInPlugin("elytraking.dread", "Dread", "1.6.1")] public class Plugin : BaseUnityPlugin { public const string GUID = "elytraking.dread"; public const string NAME = "Dread"; public const string VERSION = "1.6.1"; internal static ManualLogSource Logger; private readonly Harmony _harmony = new Harmony("elytraking.dread"); private EventHandler? _logLevelHandler; internal static Harmony HarmonyInstance { get; private set; } private static bool MonsterPatchesEnabled { get { if (DreadConfig.MonsterAggressionEnabled.Value) { return !DreadConfig.CompatibilityMode.Value; } return false; } } private void Awake() { PluginDependencyResolver.Register(); Logger = ((BaseUnityPlugin)this).Logger; HarmonyInstance = _harmony; DreadConfig.Initialize(((BaseUnityPlugin)this).Config); LoggingService.Initialize(DreadConfig.LogLevelEntry.Value); _logLevelHandler = delegate { LoggingService.SetLevel(DreadConfig.LogLevelEntry.Value); }; DreadConfig.LogLevelEntry.SettingChanged += _logLevelHandler; ApplyMonsterPatches(); if (DreadConfig.CrouchSpeedBoostEnabled.Value) { PlayerControllerAwakePatch.Apply(_harmony); } if (DreadConfig.DebugConsoleGuardEnabled.Value) { DebugConsoleGuardPatch.Apply(_harmony); } DreadConfig.MonsterAggressionEnabled.SettingChanged += delegate { ApplyMonsterPatches(); }; DreadConfig.CompatibilityMode.SettingChanged += delegate { ApplyMonsterPatches(); }; DreadConfig.CrouchSpeedBoostEnabled.SettingChanged += delegate { if (DreadConfig.CrouchSpeedBoostEnabled.Value) { PlayerControllerAwakePatch.Apply(_harmony); } else { PlayerControllerAwakePatch.Remove(_harmony); } }; DreadConfig.DebugConsoleGuardEnabled.SettingChanged += delegate { if (DreadConfig.DebugConsoleGuardEnabled.Value) { DebugConsoleGuardPatch.Apply(_harmony); } else { DebugConsoleGuardPatch.Remove(_harmony); } }; LoggingService.PrintAsciiArt(); LoggingService.LogInfo("Dread v1.6.1 loaded."); SceneManager.sceneLoaded += OnSceneLoaded; } private void ApplyMonsterPatches() { if (MonsterPatchesEnabled) { EnemyNavMeshAgentAwakePatch.Apply(_harmony); EnemyDirectorSetInvestigatePatch.Apply(_harmony); } else { EnemyNavMeshAgentAwakePatch.Remove(_harmony); EnemyDirectorSetInvestigatePatch.Remove(_harmony); } } private void Start() { RepoConfigCompat.TryApply(_harmony); } private static void OnSceneLoaded(Scene scene, LoadSceneMode mode) { if (DreadSystemInitializer.TryInitialize()) { SceneManager.sceneLoaded -= OnSceneLoaded; } } private void OnDestroy() { if (_logLevelHandler != null) { DreadConfig.LogLevelEntry.SettingChanged -= _logLevelHandler; } } } } namespace Dread.Systems { public static class AudioClipLoader { [CompilerGenerated] private sealed class <>c__DisplayClass6_0 { public AudioClip clip; internal void <LoadClips>b__0(AudioClip? c) { clip = c; } } [CompilerGenerated] private sealed class <LoadClip>d__5 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public string fileName; public Action<AudioClip?> onLoaded; private UnityWebRequest <req>5__2; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <LoadClip>d__5(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <req>5__2 = null; <>1__state = -2; } private bool MoveNext() { //IL_013c: Unknown result type (might be due to invalid IL or missing references) bool result; try { switch (<>1__state) { default: result = false; break; case 0: { <>1__state = -1; if (Cache.TryGetValue(fileName, out AudioClip value)) { onLoaded(value); result = false; break; } string fullPath = Path.GetFullPath(Path.Combine(AudioDirectory, fileName)); if (!File.Exists(fullPath)) { LoggingService.LogWarning("[AudioClipLoader] Missing audio file: " + fileName); onLoaded(null); result = false; break; } if (TryLoadWithNvorbis(fullPath, fileName, out AudioClip clip)) { Cache[fileName] = clip; onLoaded(clip); result = false; break; } if (!UnityWebRequestCompat.IsUsable) { LoggingService.LogWarning("[AudioClipLoader] NVorbis failed and UnityWebRequest is unavailable for " + fileName); onLoaded(null); result = false; break; } string text2 = ToFileUri(fullPath); <req>5__2 = UnityWebRequestMultimedia.GetAudioClip(text2, (AudioType)0); <>1__state = -3; <>2__current = <req>5__2.SendWebRequest(); <>1__state = 1; result = true; break; } case 1: <>1__state = -3; if ((int)<req>5__2.result == 0) { AudioClip content = DownloadHandlerAudioClip.GetContent(<req>5__2); content.name = fileName; Cache[fileName] = content; onLoaded(content); } else { string requestHandlerError = GetRequestHandlerError(<req>5__2); string text = ((!string.IsNullOrEmpty(<req>5__2.error)) ? <req>5__2.error : ((!string.IsNullOrEmpty(requestHandlerError)) ? requestHandlerError : "no error details")); LoggingService.LogWarning("[AudioClipLoader] Failed to load " + fileName + ": " + text); onLoaded(null); } result = false; <>m__Finally1(); break; } } catch { //try-fault ((IDisposable)this).Dispose(); throw; } return result; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<req>5__2 != null) { ((IDisposable)<req>5__2).Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class <LoadClips>d__6 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public IEnumerable<string> fileNames; public Action<string, AudioClip?> onLoaded; private <>c__DisplayClass6_0 <>8__1; private IEnumerator<string> <>7__wrap1; private string <name>5__3; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <LoadClips>d__6(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <>8__1 = null; <>7__wrap1 = null; <name>5__3 = null; <>1__state = -2; } private bool MoveNext() { try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = fileNames.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; onLoaded(<name>5__3, <>8__1.clip); <>8__1 = null; <name>5__3 = null; break; } if (<>7__wrap1.MoveNext()) { <name>5__3 = <>7__wrap1.Current; <>8__1 = new <>c__DisplayClass6_0(); <>8__1.clip = null; <>2__current = LoadClip(<name>5__3, delegate(AudioClip? c) { <>8__1.clip = c; }); <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { <>7__wrap1.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private static readonly Dictionary<string, AudioClip> Cache; public static string AudioDirectory { get; } static AudioClipLoader() { Cache = new Dictionary<string, AudioClip>(); AudioDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "audio"); } [IteratorStateMachine(typeof(<LoadClip>d__5))] public static IEnumerator LoadClip(string fileName, Action<AudioClip?> onLoaded) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <LoadClip>d__5(0) { fileName = fileName, onLoaded = onLoaded }; } [IteratorStateMachine(typeof(<LoadClips>d__6))] public static IEnumerator LoadClips(IEnumerable<string> fileNames, Action<string, AudioClip?> onLoaded) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <LoadClips>d__6(0) { fileNames = fileNames, onLoaded = onLoaded }; } public static void ClearCache() { Cache.Clear(); } public static string ToFileUri(string path) { path = Path.GetFullPath(path); if (path.Length > 0 && path[0] == '/') { path = "Z:" + path.Replace('/', Path.DirectorySeparatorChar); } return "file:///" + path.Replace('\\', '/'); } internal static bool TryLoadWithNvorbis(string path, string clipName, out AudioClip clip) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Expected O, but got Unknown //IL_011b: Expected O, but got Unknown clip = null; try { VorbisReader val = new VorbisReader(path); try { int channels = val.Channels; int sampleRate = val.SampleRate; if (channels <= 0 || sampleRate <= 0) { return false; } float[] array = new float[Math.Max(channels * 2048, sampleRate / 10 * channels)]; List<float> list = new List<float>(Math.Max(channels * 4096, (int)Math.Min(val.TotalSamples, 2000000L))); int num; while ((num = val.ReadSamples(array, 0, array.Length)) > 0) { for (int i = 0; i < num; i++) { list.Add(array[i]); } } int count = list.Count; if (count < channels) { return false; } int num2 = count / channels; float[] pcm = list.ToArray(); int pcmReadPos = 0; clip = AudioClip.Create(Path.GetFileNameWithoutExtension(clipName), num2, channels, sampleRate, false, (PCMReaderCallback)delegate(float[] data) { int num4 = pcm.Length - pcmReadPos; if (num4 <= 0) { for (int j = 0; j < data.Length; j++) { data[j] = 0f; } } else { int num5 = Math.Min(data.Length, num4); Array.Copy(pcm, pcmReadPos, data, 0, num5); pcmReadPos += num5; for (int k = num5; k < data.Length; k++) { data[k] = 0f; } } }, (PCMSetPositionCallback)delegate(int position) { int num3 = position * channels; if (num3 < 0) { num3 = 0; } else if (num3 > pcm.Length) { num3 = pcm.Length; } pcmReadPos = num3; }); clip.name = clipName; return true; } finally { ((IDisposable)val)?.Dispose(); } } catch (Exception ex) { LoggingService.LogVerbose("[AudioClipLoader] NVorbis failed for " + clipName + ": " + ex.Message); return false; } } internal static string? GetDownloadHandlerError(object? handler) { if (handler == null) { return null; } return handler.GetType().GetProperty("error")?.GetValue(handler) as string; } internal static string? GetRequestHandlerError(UnityWebRequest req) { try { return GetDownloadHandlerError(typeof(UnityWebRequest).GetProperty("downloadHandler")?.GetValue(req)); } catch { return null; } } } public class AudioDreadSystem : MonoBehaviour { [CompilerGenerated] private sealed class <LoadClips>d__9 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public AudioDreadSystem <>4__this; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <LoadClips>d__9(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { int num = <>1__state; AudioDreadSystem CS$<>8__locals0 = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; goto IL_0042; case 1: <>1__state = -1; goto IL_0042; case 2: { <>1__state = -1; LoggingService.LogInfo($"[AudioDread] Loaded {CS$<>8__locals0._clips.Count}/{ClipNames.Length} clips."); DreadRuntimeState.AudioClipCount = CS$<>8__locals0._clips.Count; ((MonoBehaviour)CS$<>8__locals0).StartCoroutine(CS$<>8__locals0.PlayLoop()); return false; } IL_0042: if (!CS$<>8__locals0._sceneLoaded || SemiFunc.MenuLevel()) { <>2__current = null; <>1__state = 1; return true; } <>2__current = AudioClipLoader.LoadClips(ClipNames, delegate(string name, AudioClip? clip) { if (clip != null) { CS$<>8__locals0._clips.Add(clip); } }); <>1__state = 2; return true; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class <PlayLoop>d__10 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public AudioDreadSystem <>4__this; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <PlayLoop>d__10(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Expected O, but got Unknown int num = <>1__state; AudioDreadSystem audioDreadSystem = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <>2__current = (object)new WaitForSeconds(30f); <>1__state = 1; return true; case 1: <>1__state = -1; break; case 2: <>1__state = -1; LoggingService.LogVerbose("[AudioDread] Checking audio play..."); if (DreadConfig.AudioEnabled.Value && !SemiFunc.MenuLevel() && audioDreadSystem._clips.Count != 0) { if (audioDreadSystem._mainCam == null) { audioDreadSystem._mainCam = Camera.main; } if (audioDreadSystem._mainCam != null) { audioDreadSystem.PlayRandomSound(); DreadRuntimeState.AudioClipCount = audioDreadSystem._clips.Count; } } break; } float num2 = Random.Range(60f, 180f) / DreadConfig.AudioFrequency.Value; audioDreadSystem._nextPlayAt = Time.time + num2; DreadRuntimeState.AudioNextPlayIn = num2; <>2__current = (object)new WaitForSeconds(num2); <>1__state = 2; return true; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private readonly List<AudioClip> _clips = new List<AudioClip>(); private Camera? _mainCam; private bool _sceneLoaded; private float _nextPlayAt = -1f; private static readonly string[] ClipNames = new string[4] { "scraping.ogg", "footsteps.ogg", "breathing.ogg", "whisper.ogg" }; private static readonly Dictionary<string, float> ClipWeights = new Dictionary<string, float> { { "scraping.ogg", 0.6f }, { "footsteps.ogg", 0.6f }, { "breathing.ogg", 0.3f }, { "whisper.ogg", 0.1f } }; private void Start() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) LoggingService.LogVerbose("[AudioDread] Awake starting..."); SceneManager.sceneLoaded += OnSceneLoaded; OnSceneLoaded(SceneManager.GetActiveScene(), (LoadSceneMode)0); ((MonoBehaviour)this).StartCoroutine(LoadClips()); } private void OnDestroy() { ((MonoBehaviour)this).StopAllCoroutines(); SceneManager.sceneLoaded -= OnSceneLoaded; } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { _sceneLoaded = true; _mainCam = Camera.main; } [IteratorStateMachine(typeof(<LoadClips>d__9))] private IEnumerator LoadClips() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <LoadClips>d__9(0) { <>4__this = this }; } [IteratorStateMachine(typeof(<PlayLoop>d__10))] private IEnumerator PlayLoop() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <PlayLoop>d__10(0) { <>4__this = this }; } private void Update() { if (_nextPlayAt > 0f) { float num = _nextPlayAt - Time.time; DreadRuntimeState.AudioNextPlayIn = ((num < 0f) ? 0f : num); } } private AudioClip PickWeightedClip() { if (_clips.Count == 0) { return null; } float num = 0f; foreach (AudioClip clip in _clips) { num += (ClipWeights.TryGetValue(clip.name, out var value) ? value : 1f); } float num2 = Random.Range(0f, num); foreach (AudioClip clip2 in _clips) { num2 -= (ClipWeights.TryGetValue(clip2.name, out var value2) ? value2 : 1f); if (num2 <= 0f) { return clip2; } } return _clips[_clips.Count - 1]; } private void PlayRandomSound() { //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Expected O, but got Unknown if (_mainCam == null) { _mainCam = Camera.main; } if (_mainCam != null) { AudioClip val = PickWeightedClip(); if (val != null) { Camera? mainCam = _mainCam; Vector3 val2 = new Vector3(Random.Range(-1f, 1f), Random.Range(-0.3f, 0.3f), Random.Range(-1f, 1f)); Vector3 val3 = ((Vector3)(ref val2)).normalized * Random.Range(5f, 15f); Vector3 position = mainCam.transform.position + val3; GameObject val4 = new GameObject("DreadSound"); val4.transform.position = position; AudioSource obj = val4.AddComponent<AudioSource>(); obj.clip = val; float pitch = (obj.pitch = Random.Range(0.5f, 1.5f)); obj.spatialBlend = 1f; obj.volume = DreadConfig.AudioVolume.Value; obj.rolloffMode = (AudioRolloffMode)0; obj.minDistance = 1f; obj.maxDistance = 25f; obj.Play(); Object.Destroy((Object)val4, AudioPlayUtil.PlayLifetimeSeconds(val, pitch)); } } } } internal static class AudioPlayUtil { internal static float PlayLifetimeSeconds(AudioClip clip, float pitch, float paddingSeconds = 0.5f) { return clip.length / Math.Max(pitch, 0.01f) + paddingSeconds; } } public class DebugOverlaySystem : MonoBehaviour { private struct RowData { public string Left; public string Right; public Color Color; public byte Kind; } private readonly List<RowData> _rows = new List<RowData>(16); private static readonly GUIContent EmptyContent = new GUIContent(); private const byte RowNormal = 0; private const byte RowHeader = 1; private const byte RowSep = 2; private static readonly Color ColAccent = new Color(0.96f, 0.55f, 0.38f); private static readonly Color ColDim = new Color(0.62f, 0.64f, 0.7f); private static readonly Color ColValue = new Color(0.92f, 0.93f, 0.96f); private static readonly Color ColGood = new Color(0.48f, 0.9f, 0.55f); private static readonly Color ColWarn = new Color(0.97f, 0.84f, 0.42f); private static readonly Color ColBad = new Color(0.96f, 0.46f, 0.46f); private Texture2D? _bgTex; private Texture2D? _sepTex; private GUIStyle? _boxStyle; private GUIStyle? _headerStyle; private GUIStyle? _hintStyle; private GUIStyle? _labelStyle; private GUIStyle? _valueStyle; private GUIStyle? _sepStyle; private bool _visible; private bool _loggedDisabledWhileRunning; private float _smoothedDelta; private float _minFps; private float _minFpsResetAt; private float _memMB; private float _nextStatRefresh; private void OnGUI() { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) if (!GuardOverlayEnabled() || !IsOverlayVisible()) { return; } EnsureStyles(); BuildRows(); float num = 16f + (float)_rows.Count * 18f; Rect val = default(Rect); ((Rect)(ref val))..ctor(12f, 140f, 320f, num); GUI.Box(val, EmptyContent, _boxStyle); float num2 = ((Rect)(ref val)).x + 10f; float num3 = ((Rect)(ref val)).y + 6f; float num4 = 300f; for (int i = 0; i < _rows.Count; i++) { RowData rowData = _rows[i]; if (rowData.Kind == 2) { GUI.Box(new Rect(num2, num3 + 9f - 1f, num4, 1f), EmptyContent, _sepStyle); } else if (rowData.Kind == 1) { GUI.Label(new Rect(num2, num3, num4, 18f), rowData.Left, _headerStyle); GUI.Label(new Rect(num2 + num4 - 36f, num3 + 2f, 36f, 18f), rowData.Right, _hintStyle); } else { GUI.Label(new Rect(num2, num3, 82f, 18f), rowData.Left, _labelStyle); GUIStyle valueStyle = _valueStyle; valueStyle.normal.textColor = rowData.Color; GUI.Label(new Rect(num2 + 82f, num3, num4 - 82f, 18f), rowData.Right, valueStyle); } num3 += 18f; } } private void BuildRows() { //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_0202: Unknown result type (might be due to invalid IL or missing references) //IL_027f: Unknown result type (might be due to invalid IL or missing references) //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_0339: Unknown result type (might be due to invalid IL or missing references) //IL_0357: Unknown result type (might be due to invalid IL or missing references) _rows.Clear(); AddHeader("DREAD 1.6.1", "F10"); AddSep(); float num = ((_smoothedDelta > 0f) ? (1f / _smoothedDelta) : 0f); float num2 = _smoothedDelta * 1000f; Color color = ((num >= 60f) ? ColGood : ((num >= 30f) ? ColWarn : ColBad)); AddRow("FPS", $"{num:F0}", color); AddRow("Frame", $"{num2:F1} ms min {_minFps:F0} fps", ColValue); AddRow("Memory", $"{_memMB:F0} MB", ColValue); AddRow("GC", $"g0 {GC.CollectionCount(0)} g1 {GC.CollectionCount(1)} g2 {GC.CollectionCount(2)}", ColDim); AddRow("Screen", $"{Screen.width}x{Screen.height}", ColDim); AddRow("Frames", Time.frameCount.ToString(), ColDim); AddSep(); float nearestEnemyDist = DreadRuntimeState.NearestEnemyDist; string right = ((nearestEnemyDist >= 1.7014117E+38f) ? "none" : $"{nearestEnemyDist:F1} m (range 15m)"); AddRow("Enemy", right, ColValue); AddRow("Tension", "adrenaline " + OnOff(DreadRuntimeState.AdrenalineActive), ColValue); AddRow("Sprint", $"panic {OnOff(DreadRuntimeState.PanicSprintActive)} cd {DreadRuntimeState.PanicSprintCooldown:F0}s", ColValue); AddRow("Break", BreakSummary(), BreakColor()); AddRow("Break+", "clips " + OnOff(DreadRuntimeState.PsychoticBreakClipsLoaded) + " " + $"enemies {DreadRuntimeState.PsychoticBreakEnemyCount} " + $"threat {DreadRuntimeState.PsychoticBreakThreatCount}s " + $"next {DreadRuntimeState.PsychoticBreakNextCheckIn:F0}s", ColDim); AddRow("Audio", AudioSummary(), ColValue); AddSep(); AddRow("Config", "compat" + PlusMinus(DreadConfig.CompatibilityMode.Value) + " aggr" + PlusMinus(DreadConfig.MonsterAggressionEnabled.Value) + " maud" + PlusMinus(DreadConfig.MonsterAudioEnabled.Value) + " aud" + PlusMinus(DreadConfig.AudioEnabled.Value) + " srv" + PlusMinus(DreadConfig.DebugServerEnabled.Value), ColDim); AddRow("Patches", DreadRuntimeState.DreadPatchCount.ToString(), ColValue); } private void AddRow(string left, string right, Color color) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) _rows.Add(new RowData { Left = left, Right = right, Color = color, Kind = 0 }); } private void AddHeader(string left, string right) { _rows.Add(new RowData { Left = left, Right = right, Kind = 1 }); } private void AddSep() { _rows.Add(new RowData { Left = string.Empty, Right = string.Empty, Kind = 2 }); } private static string BreakSummary() { if (!DreadRuntimeState.PsychoticBreakEnabled) { return "off"; } if (DreadRuntimeState.PsychoticBreakEpisodeActive) { float num = DreadRuntimeState.PsychoticBreakEpisodeDuration - DreadRuntimeState.PsychoticBreakEpisodeTimer; return $"ACTIVE {num:F1}s"; } if (!DreadRuntimeState.PsychoticBreakCanTrigger && !string.IsNullOrEmpty(DreadRuntimeState.PsychoticBreakBlockReason)) { return "blocked: " + DreadRuntimeState.PsychoticBreakBlockReason; } return $"ready next {DreadRuntimeState.PsychoticBreakNextCheckIn:F0}s " + $"threat {DreadRuntimeState.PsychoticBreakThreatCount}s"; } private static Color BreakColor() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) if (!DreadRuntimeState.PsychoticBreakEnabled) { return ColDim; } if (DreadRuntimeState.PsychoticBreakEpisodeActive) { return ColBad; } if (!DreadRuntimeState.PsychoticBreakCanTrigger) { return ColWarn; } return ColGood; } private static string AudioSummary() { string arg = ((DreadRuntimeState.AudioNextPlayIn >= 0f) ? $"next {DreadRuntimeState.AudioNextPlayIn:F0}s" : "next n/a"); return $"{DreadRuntimeState.AudioClipCount}/4 {arg}"; } private static string OnOff(bool value) { if (!value) { return "off"; } return "ON"; } private static string PlusMinus(bool value) { if (!value) { return "-"; } return "+"; } private static int CountDreadPatches() { if (Plugin.HarmonyInstance == null) { return 0; } int num = 0; try { foreach (MethodBase allPatchedMethod in Harmony.GetAllPatchedMethods()) { Patches patchInfo = Harmony.GetPatchInfo(allPatchedMethod); if (patchInfo != null) { ReadOnlyCollection<Patch> prefixes = patchInfo.Prefixes; if (prefixes != null && prefixes.Any((Patch p) => p.owner == "elytraking.dread")) { num++; } ReadOnlyCollection<Patch> postfixes = patchInfo.Postfixes; if (postfixes != null && postfixes.Any((Patch p) => p.owner == "elytraking.dread")) { num++; } ReadOnlyCollection<Patch> transpilers = patchInfo.Transpilers; if (transpilers != null && transpilers.Any((Patch p) => p.owner == "elytraking.dread")) { num++; } ReadOnlyCollection<Patch> finalizers = patchInfo.Finalizers; if (finalizers != null && finalizers.Any((Patch p) => p.owner == "elytraking.dread")) { num++; } } } return num; } catch { return -1; } } private void EnsureStyles() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Expected O, but got Unknown //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Expected O, but got Unknown //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Expected O, but got Unknown //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Expected O, but got Unknown //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Expected O, but got Unknown //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Expected O, but got Unknown if (_boxStyle == null) { _bgTex = MakeTexture(new Color(0.05f, 0.05f, 0.07f, 0.88f)); _sepTex = MakeTexture(new Color(0.45f, 0.47f, 0.52f, 0.5f)); _boxStyle = new GUIStyle(GUI.skin.box); _boxStyle.normal.background = _bgTex; _headerStyle = new GUIStyle(GUI.skin.label) { fontSize = 15, wordWrap = false }; _headerStyle.normal.textColor = ColAccent; _hintStyle = new GUIStyle(GUI.skin.label) { fontSize = 11, wordWrap = false }; _hintStyle.normal.textColor = ColDim; _labelStyle = new GUIStyle(GUI.skin.label) { fontSize = 13, wordWrap = false }; _labelStyle.normal.textColor = ColDim; _valueStyle = new GUIStyle(GUI.skin.label) { fontSize = 13, wordWrap = false }; _valueStyle.normal.textColor = ColValue; _sepStyle = new GUIStyle(GUI.skin.box); _sepStyle.normal.background = _sepTex; } } private static Texture2D MakeTexture(Color color) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown Texture2D val = new Texture2D(1, 1); val.SetPixel(0, 0, color); val.Apply(); return val; } private void Awake() { _visible = DreadConfig.DebugOverlayEnabled.Value; DreadConfig.DebugOverlayEnabled.SettingChanged += OnOverlayConfigChanged; ((Behaviour)this).enabled = DreadConfig.DebugOverlayEnabled.Value; } private void OnDestroy() { DreadConfig.DebugOverlayEnabled.SettingChanged -= OnOverlayConfigChanged; } private void OnOverlayConfigChanged(object? sender, EventArgs e) { _visible = DreadConfig.DebugOverlayEnabled.Value; ((Behaviour)this).enabled = DreadConfig.DebugOverlayEnabled.Value; } private void Update() { if (GuardOverlayEnabled()) { SampleFrameStats(); if (Input.GetKeyDown((KeyCode)291)) { _visible = !_visible; } if (IsOverlayVisible() && Time.realtimeSinceStartup >= _nextStatRefresh) { _nextStatRefresh = Time.realtimeSinceStartup + 0.5f; DreadRuntimeState.DreadPatchCount = CountDreadPatches(); _memMB = (float)GC.GetTotalMemory(forceFullCollection: false) / 1048576f; } } } private void SampleFrameStats() { float unscaledDeltaTime = Time.unscaledDeltaTime; if (!(unscaledDeltaTime <= 0f)) { _smoothedDelta = ((_smoothedDelta <= 0f) ? unscaledDeltaTime : (_smoothedDelta + (unscaledDeltaTime - _smoothedDelta) * 0.1f)); float num = 1f / unscaledDeltaTime; float realtimeSinceStartup = Time.realtimeSinceStartup; if (realtimeSinceStartup >= _minFpsResetAt) { _minFps = num; _minFpsResetAt = realtimeSinceStartup + 2f; } else if (num < _minFps) { _minFps = num; } } } private bool IsOverlayVisible() { if (_visible) { return !SemiFunc.MenuLevel(); } return false; } private bool GuardOverlayEnabled() { if (DreadConfig.DebugOverlayEnabled.Value) { return true; } if (!_loggedDisabledWhileRunning) { _loggedDisabledWhileRunning = true; LoggingService.LogError("DebugOverlaySystem ran while DebugOverlayEnabled is false: enable/disable wiring regressed (PERF-2)."); } return false; } } public class DebugServerSystem : MonoBehaviour { private class DebugCommand { public string RequestJson; public string? Response; public ManualResetEventSlim Done = new ManualResetEventSlim(initialState: false); } private class LogEntry { public string Level; public string Message; public string Timestamp; } private class DebugLogListener : ILogListener, IDisposable { private readonly DebugServerSystem _owner; public LogLevel LogLevelFilter => (LogLevel)63; public DebugLogListener(DebugServerSystem owner) { _owner = owner; } public void LogEvent(object sender, LogEventArgs e) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) _owner.AddLogEntry($"[{e.Level}]", e.Data?.ToString() ?? ""); } public void Dispose() { } } [Serializable] private class RequestEnvelope { public int id; public string? cmd; } [Serializable] private class PingResponse { public bool pong = true; public string? version; public int port; } [Serializable] private class StateResponse { public string version = ""; public string scene = ""; public int enemyCount; public float nearestEnemyDist = -1f; public float playerHp = -1f; public float playerStamina = -1f; public int debugServerPort; public bool isEnabled; } [Serializable] private class ConfigResponse { public bool audioEnabled; public float audioFrequency; public float audioVolume; public bool monsterAggression; public bool monsterAudio; public bool crouchSpeedBoost; public bool fakeFootsteps; public bool adrenaline; public bool lowStaminaSound; public bool panicSprint; public bool errorReporting; public bool compatibilityMode; public bool compatibilitySkipConflictingPatches; public bool debugConsoleGuard; public bool psychoticBreak; public float psychoticBreakTriggerChance; public float psychoticBreakDuration; public bool psychoticBreakOncePerMatch; public bool debugServerEnabled; public int debugServerPort; public bool debugOverlayEnabled; public string logLevel = ""; public ConfigSectionEntry[] sections; } [Serializable] private class ConfigSectionEntry { public string section = ""; public ConfigKeyEntry[] keys; } [Serializable] private class ConfigKeyEntry { public string key = ""; public string debugKey = ""; public string value = ""; public string type = ""; public string description = ""; public bool restartRequired; } [Serializable] private class SetConfigResult { public string status = "ok"; public string debugKey = ""; public string value = ""; public string warning = ""; public string? error; public static SetConfigResult Ok(string debugKey, string value) { return new SetConfigResult { debugKey = debugKey, value = value }; } public static SetConfigResult Fail(string error) { return new SetConfigResult { status = "error", error = error }; } } [Serializable] private class VerifyResponse { public VerifyCheck[] checks; } [Serializable] private class VerifyCheck { public string id = ""; public bool ok; public string message = ""; } [Serializable] private class TriggerResponse { public bool triggered; } [Serializable] private class RuntimeStateResponse { public float nearestEnemyDist = -1f; public bool psychoticBreakEnabled; public bool psychoticBreakCanTrigger; public string psychoticBreakBlockReason = ""; public bool psychoticBreakEpisodeActive; public float psychoticBreakEpisodeTimer; public float psychoticBreakEpisodeDuration; public float psychoticBreakNextCheckIn; public int psychoticBreakThreatCount; public int psychoticBreakEnemyCount; public bool psychoticBreakClipsLoaded; public bool adrenalineActive; public bool panicSprintActive; public float panicSprintCooldown; public int audioClipCount; public float audioNextPlayIn = -1f; public int dreadPatchCount; public bool debugOverlayEnabled; public bool debugOverlayPresent; } [Serializable] private class ShutdownResponse { public string status = "shutting down"; } [Serializable] private class LogsResponse { public LogEntry[] logs; } [Serializable] private class PatchesResponse { public PatchEntry[] patches; } [Serializable] private class PatchEntry { public string method = ""; public int prefixes; public int postfixes; public int transpilers; public int finalizers; public string[] owners; } [Serializable] private class SetConfigRequest { public string? cmd; public SetConfigData? data; } [Serializable] private class SetConfigData { public string? section; public string? key; public string? value; } private const int MaxMessageBytes = 4096; private const int ReadTimeoutMs = 5000; private const int CommandTimeoutMs = 10000; private const int MaxLogEntries = 200; private const int MaxQueueDepth = 256; private const int AcceptPollMs = 50; private const int ShutdownJoinMs = 250; private Thread? _serverThread; private TcpListener? _listener; private volatile bool _running; private volatile bool _shutdownComplete; private readonly Queue<DebugCommand> _queue = new Queue<DebugCommand>(32); private readonly List<LogEntry> _logBuffer = new List<LogEntry>(200); private readonly object _logLock = new object(); private int _boundPort; private DebugLogListener? _logListener; private void Start() { if (!DreadConfig.DebugServerEnabled.Value) { ((Behaviour)this).enabled = false; return; } int value = DreadConfig.DebugServerPort.Value; _listener = new TcpListener(IPAddress.Loopback, value); try { _listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, optionValue: true); _listener.Start(); _boundPort = value; } catch (SocketException) { value++; try { _listener = new TcpListener(IPAddress.Loopback, value); _listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, optionValue: true); _listener.Start(); _boundPort = value; } catch (Exception ex) { Plugin.Logger.LogError((object)$"[Dread DebugServer] Failed to bind on {value - 1} or {value}: {ex.Message}"); _listener = null; ((Behaviour)this).enabled = false; return; } } _logListener = new DebugLogListener(this); Logger.Listeners.Add((ILogListener)(object)_logListener); _running = true; _serverThread = new Thread(ServerLoop) { IsBackground = true, Name = "DreadDebugServer" }; _serverThread.Start(); Application.quitting += OnApplicationQuit; Plugin.Logger.LogInfo((object)$"[Dread DebugServer] LISTENING 127.0.0.1:{_boundPort}"); } private void OnApplicationQuit() { ShutdownServer(); } private void OnDestroy() { Application.quitting -= OnApplicationQuit; ShutdownServer(); } private void ShutdownServer() { if (!_shutdownComplete) { _shutdownComplete = true; _running = false; if (_logListener != null) { Logger.Listeners.Remove((ILogListener)(object)_logListener); _logListener = null; } ReleasePendingCommands(); try { _listener?.Server?.Close(); } catch { } try { _listener?.Stop(); } catch { } _listener = null; Thread serverThread = _serverThread; if (serverThread != null && serverThread.IsAlive && Thread.CurrentThread != serverThread) { serverThread.Join(250); } _serverThread = null; } } private void ReleasePendingCommands() { lock (_queue) { while (_queue.Count > 0) { DebugCommand debugCommand = _queue.Dequeue(); int id = 0; try { id = JsonUtility.FromJson<RequestEnvelope>(debugCommand.RequestJson).id; } catch { } debugCommand.Response = MakeResponse(id, ok: false, "server shutting down", -1); debugCommand.Done.Set(); } } } private bool WaitForCommandDone(DebugCommand cmd) { int num = Environment.TickCount + 10000; while (_running) { int num2 = num - Environment.TickCount; if (num2 <= 0) { break; } int millisecondsTimeout = ((num2 > 100) ? 100 : num2); if (cmd.Done.Wait(millisecondsTimeout)) { return true; } } int id = 0; try { id = JsonUtility.FromJson<RequestEnvelope>(cmd.RequestJson).id; } catch { } cmd.Response = MakeResponse(id, ok: false, "server shutting down", -1); cmd.Done.Set(); return false; } private void AddLogEntry(string level, string message) { lock (_logLock) { _logBuffer.Add(new LogEntry { Level = level, Message = message, Timestamp = DateTime.UtcNow.ToString("O") }); if (_logBuffer.Count > 200) { _logBuffer.RemoveAt(0); } } } private void ServerLoop() { while (_running) { try { if (_listener == null) { break; } if (!_listener.Pending()) { Thread.Sleep(50); continue; } using TcpClient tcpClient = _listener.AcceptTcpClient(); tcpClient.ReceiveTimeout = 5000; using NetworkStream networkStream = tcpClient.GetStream(); using StreamReader streamReader = new StreamReader(networkStream, Encoding.UTF8); while (_running) { string text; try { text = streamReader.ReadLine(); } catch (IOException) { break; } if (text == null) { break; } text = text.Trim(); if (text.Length == 0) { continue; } DebugCommand debugCommand = new DebugCommand { RequestJson = text }; lock (_queue) { if (_queue.Count >= 256) { RequestEnvelope requestEnvelope; try { requestEnvelope = JsonUtility.FromJson<RequestEnvelope>(text); } catch { requestEnvelope = new RequestEnvelope(); } string s = $"{{\"id\":{requestEnvelope.id},\"ok\":false," + "\"error\":\"queue full\",\"code\":-1}}\n"; byte[] bytes = Encoding.UTF8.GetBytes(s); try { networkStream.Write(bytes, 0, bytes.Length); } catch (IOException) { } break; } _queue.Enqueue(debugCommand); goto IL_012d; } IL_012d: if (!WaitForCommandDone(debugCommand)) { if (_running) { Plugin.Logger.LogWarning((object)"[Dread DebugServer] Command timed out"); } break; } byte[] bytes2 = Encoding.UTF8.GetBytes((debugCommand.Response ?? "{}") + "\n"); try { networkStream.Write(bytes2, 0, bytes2.Length); } catch (IOException) { break; } } } catch (ObjectDisposedException) { break; } catch (Exception ex5) when (_running) { Plugin.Logger.LogWarning((object)("[Dread DebugServer] Connection error: " + ex5.Message)); Thread.Sleep(500); } } } private void Update() { while (true) { DebugCommand debugCommand; lock (_queue) { if (_queue.Count == 0) { break; } debugCommand = _queue.Dequeue(); } try { debugCommand.Response = ExecuteCommand(debugCommand.RequestJson); } catch (Exception ex) { int id = 0; try { id = JsonUtility.FromJson<RequestEnvelope>(debugCommand.RequestJson).id; } catch { } debugCommand.Response = MakeResponse(id, ok: false, Sanitize(ex.Message), -1); Plugin.Logger.LogError((object)$"[Dread DebugServer] Command error: {ex}"); } finally { debugCommand.Done.Set(); } } } private string ExecuteCommand(string rawJson) { RequestEnvelope requestEnvelope; try { requestEnvelope = JsonUtility.FromJson<RequestEnvelope>(rawJson); } catch { return MakeResponse(0, ok: false, "invalid JSON", -3); } if (requestEnvelope.cmd == null) { return MakeResponse(requestEnvelope.id, ok: false, "Missing cmd field", -3); } switch (requestEnvelope.cmd) { case "ping": return MakeResponse(requestEnvelope.id, ok: true, new PingResponse { version = "1.6.1", port = _boundPort }); case "get_state": return MakeResponse(requestEnvelope.id, ok: true, CaptureState()); case "get_config": return MakeResponse(requestEnvelope.id, ok: true, CaptureConfig()); case "set_config": { SetConfigRequest setConfigRequest; try { setConfigRequest = JsonUtility.FromJson<SetConfigRequest>(rawJson); } catch { return MakeResponse(requestEnvelope.id, ok: false, "invalid JSON", -3); } if (setConfigRequest.data?.section == null || setConfigRequest.data?.key == null || setConfigRequest.data?.value == null) { return MakeResponse(requestEnvelope.id, ok: false, "Missing section, key, or value", -3); } SetConfigResult setConfigResult = SetConfigValue(setConfigRequest.data.section, setConfigRequest.data.key, setConfigRequest.data.value); if (setConfigResult.error != null) { return MakeResponse(requestEnvelope.id, ok: false, setConfigResult.error, -3); } return MakeResponse(requestEnvelope.id, ok: true, setConfigResult); } case "get_patches": return MakeResponse(requestEnvelope.id, ok: true, GetHarmonyPatches()); case "get_logs": lock (_logLock) { return MakeResponse(requestEnvelope.id, ok: true, new LogsResponse { logs = _logBuffer.ToArray() }); } case "shutdown": Plugin.Logger.LogInfo((object)"[Dread DebugServer] Shutdown requested via debug command"); _running = false; try { _listener?.Server?.Close(); } catch { } try { _listener?.Stop(); } catch { } _listener = null; ReleasePendingCommands(); return MakeResponse(requestEnvelope.id, ok: true, new ShutdownResponse()); case "verify": return MakeResponse(requestEnvelope.id, ok: true, RunVerifyChecks()); case "trigger_test_crash": return TriggerTestCrash(requestEnvelope.id); case "force_psychotic_break": return ForcePsychoticBreak(requestEnvelope.id); case "get_runtime_state": return MakeResponse(requestEnvelope.id, ok: true, CaptureRuntimeState()); default: return MakeResponse(requestEnvelope.id, ok: false, "Unknown command: " + requestEnvelope.cmd, -2); } } private StateResponse CaptureState() { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) string scene = "unknown"; int enemyCount = 0; float num = -1f; float playerHp = -1f; float playerStamina = -1f; try { Scene activeScene = SceneManager.GetActiveScene(); scene = ((Scene)(ref activeScene)).name ?? "unknown"; EnemyHealth[] array = Object.FindObjectsOfType<EnemyHealth>(); enemyCount = array.Length; PlayerController val = Object.FindObjectOfType<PlayerController>(); if (val != null) { playerHp = ReadPlayerFloat(val, "Health", "health", "playerHealth"); playerStamina = ReadPlayerFloat(val, "stamina", "Stamina", "energy"); EnemyHealth[] array2 = array; foreach (EnemyHealth val2 in array2) { if (val2.CurrentHealth > 0) { float num2 = Vector3.Distance(((Component)val2).transform.position, ((Component)val).transform.position); if (num < 0f || num2 < num) { num = num2; } } } } } catch { } return new StateResponse { version = "1.6.1", scene = scene, enemyCount = enemyCount, nearestEnemyDist = num, playerHp = playerHp, playerStamina = playerStamina, debugServerPort = _boundPort, isEnabled = DreadConfig.DebugServerEnabled.Value }; } private static ConfigResponse CaptureConfig() { return new ConfigResponse { audioEnabled = DreadConfig.AudioEnabled.Value, audioFrequency = DreadConfig.AudioFrequency.Value, audioVolume = DreadConfig.AudioVolume.Value, monsterAggression = DreadConfig.MonsterAggressionEnabled.Value, monsterAudio = DreadConfig.MonsterAudioEnabled.Value, crouchSpeedBoost = DreadConfig.CrouchSpeedBoostEnabled.Value, fakeFootsteps = DreadConfig.FakeFootstepsEnabled.Value, adrenaline = DreadConfig.AdrenalineEnabled.Value, lowStaminaSound = DreadConfig.LowStaminaSoundEnabled.Value, panicSprint = DreadConfig.PanicSprintEnabled.Value, errorReporting = DreadConfig.ErrorReportingEnabled.Value, compatibilityMode = DreadConfig.CompatibilityMode.Value, compatibilitySkipConflictingPatches = DreadConfig.CompatibilitySkipConflictingPatches.Value, debugConsoleGuard = DreadConfig.DebugConsoleGuardEnabled.Value, psychoticBreak = DreadConfig.PsychoticBreakEnabled.Value, psychoticBreakTriggerChance = DreadConfig.PsychoticBreakTriggerChance.Value, psychoticBreakDuration = DreadConfig.PsychoticBreakDuration.Value, psychoticBreakOncePerMatch = DreadConfig.PsychoticBreakOncePerMatch.Value, debugServerEnabled = DreadConfig.DebugServerEnabled.Value, debugServerPort = DreadConfig.DebugServerPort.Value, debugOverlayEnabled = DreadConfig.DebugOverlayEnabled.Value, logLevel = DreadConfig.LogLevelEntry.Value.ToString(), sections = BuildConfigSections() }; } private static ConfigSectionEntry[] BuildConfigSections() { return new ConfigSectionEntry[11] { Section("1. Audio Dread", Entry("Enabled", "audio.enabled", (ConfigEntryBase)(object)DreadConfig.AudioEnabled), Entry("Frequency", "audio.frequency", (ConfigEntryBase)(object)DreadConfig.AudioFrequency), Entry("Volume", "audio.volume", (ConfigEntryBase)(object)DreadConfig.AudioVolume)), Section("2. Monster Overhaul", Entry("AggressionEnabled", "monster.aggression", (ConfigEntryBase)(object)DreadConfig.MonsterAggressionEnabled), Entry("AudioEnabled", "monster.audio", (ConfigEntryBase)(object)DreadConfig.MonsterAudioEnabled)), Section("3. Tension", Entry("FakeFootstepsEnabled", "tension.fakeFootsteps", (ConfigEntryBase)(object)DreadConfig.FakeFootstepsEnabled), Entry("AdrenalineEnabled", "tension.adrenaline", (ConfigEntryBase)(object)DreadConfig.AdrenalineEnabled), Entry("LowStaminaSoundEnabled", "tension.lowStamina", (ConfigEntryBase)(object)DreadConfig.LowStaminaSoundEnabled), Entry("PanicSprintEnabled", "tension.panicSprint", (ConfigEntryBase)(object)DreadConfig.PanicSprintEnabled)), Section("4. Psychotic Break", Entry("PsychoticBreakEnabled", "psychoticBreak.enabled", (ConfigEntryBase)(object)DreadConfig.PsychoticBreakEnabled), Entry("PsychoticBreakTriggerChance", "psychoticBreak.triggerChance", (ConfigEntryBase)(object)DreadConfig.PsychoticBreakTriggerChance), Entry("PsychoticBreakDuration", "psychoticBreak.duration", (ConfigEntryBase)(object)DreadConfig.PsychoticBreakDuration), Entry("PsychoticBreakOncePerMatch", "psychoticBreak.oncePerMatch", (ConfigEntryBase)(object)DreadConfig.PsychoticBreakOncePerMatch)), Section("5. QOL", Entry("CrouchSpeedBoost", "crouch.speed", (ConfigEntryBase)(object)DreadConfig.CrouchSpeedBoostEnabled)), Section("6. Compatibility", Entry("CompatibilityMode", "compatibility.mode", (ConfigEntryBase)(object)DreadConfig.CompatibilityMode), Entry("SkipConflictingPatches", "compatibility.skipConflictingPatches", (ConfigEntryBase)(object)DreadConfig.CompatibilitySkipConflictingPatches), Entry("DebugConsoleGuardEnabled", "compatibility.debugConsoleGuard", (ConfigEntryBase)(object)DreadConfig.DebugConsoleGuardEnabled)), Section("7. Error Reporting", Entry("ErrorReportingEnabled", "errorReporting", (ConfigEntryBase)(object)DreadConfig.ErrorReportingEnabled)), Section("8. Debug Overlay", Entry("DebugOverlayEnabled", "overlay.enabled", (ConfigEntryBase)(object)DreadConfig.DebugOverlayEnabled)), Section("9. Debug Server", Entry("DebugServerEnabled", "debugServer.enabled", (ConfigEntryBase)(object)DreadConfig.DebugServerEnabled, restartRequired: true), Entry("DebugServerPort", "debugServer.port", (ConfigEntryBase)(object)DreadConfig.DebugServerPort, restartRequired: true)), Section("10. Logging", Entry("LogLevel", "logging.level", (ConfigEntryBase)(object)DreadConfig.LogLevelEntry)), Section("11. Testing", Entry("Crash Game", "testing.crash", (ConfigEntryBase)(object)DreadConfig.TestCrashButton)) }; } private static ConfigSectionEntry Section(string section, params ConfigKeyEntry[] keys) { return new ConfigSectionEntry { section = section, keys = keys }; } private static ConfigKeyEntry Entry(string key, string debugKey, ConfigEntryBase entry, bool restartRequired = false) { string type = ((entry is ConfigEntry<bool>) ? "bool" : ((entry is ConfigEntry<float>) ? "float" : ((entry is ConfigEntry<int>) ? "int" : ((entry is ConfigEntry<LogLevel>) ? "LogLevel" : "string")))); return new ConfigKeyEntry { key = key, debugKey = debugKey, value = ConfigValueToString(entry), type = type, description = (entry.Description.Description ?? ""), restartRequired = restartRequired }; } private static string ConfigValueToString(ConfigEntryBase entry) { if (!(entry is ConfigEntry<bool> val)) { if (!(entry is ConfigEntry<float> val2)) { if (!(entry is ConfigEntry<int> val3)) { if (entry is ConfigEntry<LogLevel> val4) { return val4.Value.ToString(); } return ""; } return val3.Value.ToString(); } return val2.Value.ToString(CultureInfo.InvariantCulture); } return val.Value ? "true" : "false"; } private static SetConfigResult SetConfigValue(string section, string key, string value) { Dictionary<string, (ConfigEntryBase, bool)> obj = new Dictionary<string, (ConfigEntryBase, bool)> { ["audio.enabled"] = ((ConfigEntryBase)(object)DreadConfig.AudioEnabled, false), ["audio.frequency"] = ((ConfigEntryBase)(object)DreadConfig.AudioFrequency, false), ["audio.volume"] = ((ConfigEntryBase)(object)DreadConfig.AudioVolume, false), ["monster.aggression"] = ((ConfigEntryBase)(object)DreadConfig.MonsterAggressionEnabled, false), ["monster.audio"] = ((ConfigEntryBase)(object)DreadConfig.MonsterAudioEnabled, false), ["crouch.speed"] = ((ConfigEntryBase)(object)DreadConfig.CrouchSpeedBoostEnabled, false), ["tension.fakeFootsteps"] = ((ConfigEntryBase)(object)DreadConfig.FakeFootstepsEnabled, false), ["tension.adrenaline"] = ((ConfigEntryBase)(object)DreadConfig.AdrenalineEnabled, false), ["tension.lowStamina"] = ((ConfigEntryBase)(object)DreadConfig.LowStaminaSoundEnabled, false), ["tension.panicSprint"] = ((ConfigEntryBase)(object)DreadConfig.PanicSprintEnabled, false), ["errorReporting"] = ((ConfigEntryBase)(object)DreadConfig.ErrorReportingEnabled, false), ["compatibility.mode"] = ((ConfigEntryBase)(object)DreadConfig.CompatibilityMode, false), ["compatibility.skipConflictingPatches"] = ((ConfigEntryBase)(object)DreadConfig.CompatibilitySkipConflictingPatches, false), ["compatibility.debugConsoleGuard"] = ((ConfigEntryBase)(object)DreadConfig.DebugConsoleGuardEnabled, false), ["psychoticBreak.enabled"] = ((ConfigEntryBase)(object)DreadConfig.PsychoticBreakEnabled, false), ["psychoticBreak.triggerChance"] = ((ConfigEntryBase)(object)DreadConfig.PsychoticBreakTriggerChance, false), ["psychoticBreak.duration"] = ((ConfigEntryBase)(object)DreadConfig.PsychoticBreakDuration, false), ["psychoticBreak.oncePerMatch"] = ((ConfigEntryBase)(object)DreadConfig.PsychoticBreakOncePerMatch, false), ["testing.crash"] = ((ConfigEntryBase)(object)DreadConfig.TestCrashButton, false), ["debugServer.enabled"] = ((ConfigEntryBase)(object)DreadConfig.DebugServerEnabled, true), ["debugServer.port"] = ((ConfigEntryBase)(object)DreadConfig.DebugServerPort, true), ["overlay.enabled"] = ((ConfigEntryBase)(object)DreadConfig.DebugOverlayEnabled, false), ["logging.level"] = ((ConfigEntryBase)(object)DreadConfig.LogLevelEntry, false) }; string text = (string.IsNullOrEmpty(section) ? key : (string.IsNullOrEmpty(key) ? section : (section + "." + key))); if (!obj.TryGetValue(text, out var value2) || value2.Item1 == null) { return SetConfigResult.Fail("Unknown config: " + section + "/" + key + " (debug key: " + text + ")"); } try { if (value2.Item1 is ConfigEntry<bool> val) { val.Value = bool.Parse(value); } else if (value2.Item1 is ConfigEntry<float> val2) { val2.Value = float.Parse(value); } else if (value2.Item1 is ConfigEntry<int> val3) { val3.Value = int.Parse(value); } else { if (!(value2.Item1 is ConfigEntry<LogLevel> val4)) { return SetConfigResult.Fail("Unsupported config type for " + section + "/" + key); } val4.Value = (LogLevel)Enum.Parse(typeof(LogLevel), value, ignoreCase: true); } } catch (Exception ex) { return SetConfigResult.Fail("Failed to set " + section + "/" + key + ": " + ex.Message); } SetConfigResult setConfigResult = SetConfigResult.Ok(text, value); if (value2.Item2) { setConfigResult.warning = "Restart the game for debug server bind changes to take effect."; } return setConfigResult; } private VerifyResponse RunVerifyChecks() { List<VerifyCheck> list = new List<VerifyCheck> { Check("version", !string.IsNullOrEmpty("1.6.1"), "version=1.6.1"), Check("debug_server_listening", _running && _listener != null, $"port={_boundPort}"), Check("systems_count", CountActiveSystems() >= 7, $"count={CountActiveSystems()}"), Check("audio_clips", DreadRuntimeState.AudioClipCount > 0, $"loaded={DreadRuntimeState.AudioClipCount}/4"), Check("psychotic_break_clips", DreadRuntimeState.PsychoticBreakClipsLoaded, DreadRuntimeState.PsychoticBreakClipsLoaded ? "all loaded" : "missing clips"), Check("overlay_present", Object.FindObjectOfType<DebugOverlaySystem>() != null, "DebugOverlaySystem host"), Check("harmony_patches", GetDreadPatchCount() > 0, $"dreadPatches={GetDreadPatchCount()}") }; return new VerifyResponse { checks = list.ToArray() }; } private static int CountActiveSystems() { int num = 0; if (Object.FindObjectOfType<AudioDreadSystem>() != null) { num++; } if (Object.FindObjectOfType<MonsterOverhaulSystem>() != null) { num++; } if (Object.FindObjectOfType<TensionSystem>() != null) { num++; } if (Object.FindObjectOfType<ErrorReporterSystem>() != null) { num++; } if (Object.FindObjectOfType<PsychoticBreakSystem>() != null) { num++; } if (Object.FindObjectOfType<TestCrashSystem>() != null) { num++; } if (Object.FindObjectOfType<DebugServerSystem>() != null) { num++; } if (Object.FindObjectOfType<DebugOverlaySystem>() != null) { num++; } return num; } private static int GetDreadPatchCount() { if (DreadRuntimeState.DreadPatchCount > 0) { return DreadRuntimeState.DreadPatchCount; } if (Plugin.HarmonyInstance == null) { return 0; } int num = 0; try { foreach (MethodBase allPatchedMethod in Harmony.GetAllPatchedMethods()) { Patches patchInfo = Harmony.GetPatchInfo(allPatchedMethod); if (patchInfo != null) { ReadOnlyCollection<Patch> prefixes = patchInfo.Prefixes; if (prefixes != null && prefixes.Any((Patch p) => p.owner == "elytraking.dread")) { num++; } ReadOnlyCollection<Patch> postfixes = patchInfo.Postfixes; if (postfixes != null && postfixes.Any((Patch p) => p.owner == "elytraking.dread")) { num++; } ReadOnlyCollection<Patch> transpilers = patchInfo.Transpilers; if (transpilers != null && transpilers.Any((Patch p) => p.owner == "elytraking.dread")) { num++; } ReadOnlyCollection<Patch> finalizers = patchInfo.Finalizers; if (finalizers != null && finalizers.Any((Patch p) => p.owner == "elytraking.dread")) { num++; } } } return num; } catch { return -1; } } private static VerifyCheck Check(string id, bool ok, string message) { return new VerifyCheck { id = id, ok = ok, message = message }; } private static string TriggerTestCrash(int id) { if (!DreadConfig.DebugServerEnabled.Value) { return MakeResponse(id, ok: false, "Debug server disabled", -3); } TestCrashSystem.TriggerForDebug(); return MakeResponse(id, ok: true, new TriggerResponse { triggered = true }); } private static string ForcePsychoticBreak(int id) { if (!DreadConfig.DebugServerEnabled.Value) { return MakeResponse(id, ok: false, "Debug server disabled", -3); } PsychoticBreakSystem psychoticBreakSystem = Object.FindObjectOfType<PsychoticBreakSystem>(); if (psychoticBreakSystem == null) { return MakeResponse(id, ok: false, "PsychoticBreakSystem not found", -3); } try { psychoticBreakSystem.ForceEpisodeForDebug(); } catch (Exception ex) { return MakeResponse(id, ok: false, ex.Message, -1); } return MakeResponse(id, ok: true, new TriggerResponse { triggered = true }); } private static RuntimeStateResponse CaptureRuntimeState() { float nearestEnemyDist = DreadRuntimeState.NearestEnemyDist; return new RuntimeStateResponse { nearestEnemyDist = ((nearestEnemyDist >= 1.7014117E+38f) ? (-1f) : nearestEnemyDist), psychoticBreakEnabled = DreadRuntimeState.PsychoticBreakEnabled, psychoticBreakCanTrigger = DreadRuntimeState.PsychoticBreakCanTrigger, psychoticBreakBlockReason = DreadRuntimeState.PsychoticBreakBlockReason, psychoticBreakEpisodeActive = DreadRuntimeState.PsychoticBreakEpisodeActive, psychoticBreakEpisodeTimer = DreadRuntimeState.PsychoticBreakEpisodeTimer, psychoticBreakEpisodeDuration = DreadRuntimeState.PsychoticBreakEpisodeDuration, psychoticBreakNextCheckIn = DreadRuntimeState.PsychoticBreakNextCheckIn, psychoticBreakThreatCount = DreadRuntimeState.PsychoticBreakThreatCount, psychoticBreakEnemyCount = DreadRuntimeState.PsychoticBreakEnemyCount, psychoticBreakClipsLoaded = DreadRuntimeState.PsychoticBreakClipsLoaded, adrenalineActive = DreadRuntimeState.AdrenalineActive, panicSprintActive = DreadRuntimeState.PanicSprintActive, panicSprintCooldown = DreadRuntimeState.PanicSprintCooldown, audioClipCount = DreadRuntimeState.AudioClipCount, audioNextPlayIn = DreadRuntimeState.AudioNextPlayIn, dreadPatchCount = DreadRuntimeState.DreadPatchCount, debugOverlayEnabled = DreadConfig.DebugOverlayEnabled.Value, debugOverlayPresent = (Object.FindObjectOfType<DebugOverlaySystem>() != null) }; } private PatchesResponse GetHarmonyPatches() { if (Plugin.HarmonyInstance == null) { return new PatchesResponse { patches = Array.Empty<PatchEntry>() }; } List<PatchEntry> list = new List<PatchEntry>(); try { foreach (MethodBase allPatchedMethod in Harmony.GetAllPatchedMethods()) { Patches patchInfo = Harmony.GetPatchInfo(allPatchedMethod); list.Add(new PatchEntry { method = GeneralExtensions.FullDescription(allPatchedMethod), prefixes = (patchInfo?.Prefixes?.Count).GetValueOrDefault(), postfixes = (patchInfo?.Postfixes?.Count).GetValueOrDefault(), transpilers = (patchInfo?.Transpilers?.Count).GetValueOrDefault(), finalizers = (patchInfo?.Finalizers?.Count).GetValueOrDefault(), owners = (patchInfo?.Prefixes?.Select((Patch p) => p.owner).Concat(patchInfo?.Postfixes?.Select((Patch p) => p.owner) ?? Enumerable.Empty<string>()).Distinct() .ToArray() ?? Array.Empty<string>()) }); } } catch (Exception ex) { Plugin.Logger.LogWarning((object)("[Dread DebugServer] get_patches error: " + ex.Message)); } return new PatchesResponse { patches = list.ToArray() }; } private static string MakeResponse(int id, bool ok, object data) { string arg = JsonUtility.ToJson(data); return string.Format("{{\"id\":{0},\"ok\":{1},\"data\":{2}}}", id, ok ? "true" : "false", arg); } private static string MakeResponse(int id, bool ok, string error, int code) { string text = Sanitize(error); return string.Format("{{\"id\":{0},\"ok\":{1},\"error\":\"{2}\",\"code\":{3}}}", id, ok ? "true" : "false", text, code); } private static float ReadPlayerFloat(PlayerController player, params string[] names) { foreach (string text in names) { try { return Traverse.Create((object)player).Property<float>(text, (object[])null).Value; } catch { } try { return Traverse.Create((object)player).Field<float>(text).Value; } catch { } } return -1f; } private static string Sanitize(string s) { if (string.IsNullOrEmpty(s)) { return ""; } StringBuilder stringBuilder = new StringBuilder(s.Length); foreach (char c in s) { if (c == '"') { stringBuilder.Append("\\\""); } else if (c == '\\') { stringBuilder.Append("\\\\"); } else if (c == '\n') { stringBuilder.Append("\\n"); } else if (c == '\r') { stringBuilder.Append("\\r"); } else if (c == '\t') { stringBuilder.Append("\\t"); } else if (c < ' ') { stringBuilder.Append($"\\u{(int)c:x4}"); } else { stringBuilder.Append(c); } } return stringBuilder.ToString(); } } internal static class DreadRuntimeState { public static float NearestEnemyDist { get; internal set; } = float.MaxValue; public static bool AdrenalineActive { get; internal set; } public static bool PanicSprintActive { get; internal set; } public static float PanicSprintCooldown { get; internal set; } public static bool PsychoticBreakEnabled { get; internal set; } public static bool PsychoticBreakCanTrigger { get; internal set; } public static string PsychoticBreakBlockReason { get; internal set; } = ""; public static bool PsychoticBreakEpisodeActive { get; internal set; } public static float PsychoticBreakEpisodeTimer { get; internal set; } public static float PsychoticBreakEpisodeDuration { get; internal set; } public static float PsychoticBreakNextCheckIn { get; internal set; } public static int PsychoticBreakThreatCount { get; internal set; } public static int PsychoticBreakEnemyCount { get; internal set; } public static bool PsychoticBreakClipsLoaded { get; internal set; } public static int AudioClipCount { get; internal set; } public static float AudioNextPlayIn { get; internal set; } = -1f; public static int DreadPatchCount { get; internal set; } } internal static class DreadSystemInitializer { private static bool _initialized; public static bool TryInitialize() { if (_initialized) { return true; } if (!EnsureUnityEngineUiLoaded()) { LoggingService.LogVerbose("[Dread] Deferring system init until UnityEngine.UI is available"); return false; } _initialized = true; int num = 0; int num2 = 0; foreach (SystemRegistration item in DreadSystemRegistry.Registrations.OrderBy((SystemRegistration r) => r.OrderGroup)) { if (item.IsEnabled == null || item.IsEnabled()) { num2++; num += TryAddSystem(item.SystemType, item.HostName); } } RepoConfigCompat.TryApply(Plugin.HarmonyInstance); if (num > 0) { if (num < num2) { LoggingService.LogInfo($"Systems initialized ({num}/{num2})"); } else { LoggingService.LogInfo($"Systems initialized ({num})"); } } else if (num2 > 0) { LoggingService.LogError("All systems failed to initialize."); } else { LoggingService.LogVerbose("[Dread] No runtime systems enabled for initialization."); } return true; } private static int TryAddSystem(Type systemType, string hostName) { try { if (CreateSystemHost(hostName).AddComponent(systemType) == null) { LoggingService.LogError("Failed to add " + systemType.Name + " component: Unity could not instantiate the script (check BepInEx log for TypeLoadException)"); return 0; } return 1; } catch (Exception ex) { bool flag = ((ex is TypeLoadException || ex is ReflectionTypeLoadException) ? true : false); string text = ((!flag) ? ex.Message : (ex.InnerException?.Message ?? ex.Message)); LoggingService.LogError("Failed to add " + systemType.Name + " component: " + text); return 0; } } private static bool EnsureUnityEngineUiLoaded() { try { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { if (string.Equals(assembly.GetName().Name, "UnityEngine.UI", StringComparison.Ordinal)) { return assembly.GetType("UnityEngine.UI.RawImage") != null; } } return Assembly.Load("UnityEngine.UI").GetType("UnityEngine.UI.RawImage") != null; } catch (Exception ex) { LoggingService.LogVerbose("[Dread] UnityEngine.UI not ready: " + ex.Message); return false; } } private static GameObject CreateSystemHost(string name) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_000d: Expected O, but got Unknown GameObject val = new GameObject(name); Object.DontDestroyOnLoad((Object)val); return val; } } internal enum SystemOrderGroup { Core, Debug } internal sealed class SystemRegistration { public string Id { get; } public Type SystemType { get; } public string HostName { get; } public SystemOrderGroup OrderGroup { get; } public Func<bool>? IsEnabled { get; } public SystemRegistration(string id, Type systemType, string hostName, SystemOrderGroup orderGroup, Func<bool>? isEnabled = null) { Id = id; SystemType = systemType; HostName = hostName; OrderGroup = orderGroup; IsEnabled = isEnabled; } } internal static class DreadSystemRegistry { public static IReadOnlyList<SystemRegistration> Registrations { get; } = new <>z__ReadOnlyArray<SystemRegistration>(new SystemRegistration[9] { new SystemRegistration("audio-dread", typeof(AudioDreadSystem), "DreadAudioHost", SystemOrderGroup.Core), new SystemRegistration("monster-overhaul", typeof(MonsterOverhaulSystem), "DreadMonsterHost", SystemOrderGroup.Core), new SystemRegistration("tension", typeof(TensionSystem), "DreadTensionHost", SystemOrderGroup.Core), new SystemRegistration("error-reporter", typeof(ErrorReporterSystem), "DreadErrorHost", SystemOrderGroup.Core), new SystemRegistration("error-reporting-prompt", typeof(ErrorReportingPromptSystem), "DreadErrorReportingPromptHost", SystemOrderGroup.Core), new SystemRegistration("psychotic-break", typeof(PsychoticBreakSystem), "DreadPsychoticBreakHost", SystemOrderGroup.Core), new SystemRegistration("test-crash", typeof(TestCrashSystem), "DreadTestCrashHost", SystemOrderGroup.Debug), new SystemRegistration("debug-server", typeof(DebugServerSystem), "DreadDebugHost", SystemOrderGroup.Debug), new SystemRegistration("debug-overlay", typeof(DebugOverlaySystem), "DreadDebugOverlayHost", SystemOrderGroup.Debug) }); } internal static class EnemyHealthCompat { internal static bool IsValid(EnemyHealth? enemy) { if (enemy == null) { return false; } try { return ((Component)enemy).gameObject != null; } catch { return false; } } internal static bool IsAliveForVisibility(EnemyHealth enemy) { if (!IsValid(enemy)) { return false; } try { if (!((Component)enemy).gameObject.activeInHierarchy) { return false; } } catch { return false; } if (TryReadHealth(enemy, out var hp)) { return hp > 0f; } return true; } private static bool TryReadHealth(EnemyHealth enemy, out float hp) { hp = 0f; if (!IsValid(enemy)) { return false; } Traverse traverse = Traverse.Create((object)enemy); string[] array = new string[6] { "CurrentHealth", "currentHealth", "health", "Health", "HP", "hp" }; foreach (string name in array) { if (TryReadFloatMember(traverse, name, out hp)) { return true; } if (TryReadIntMember(traverse, name, out var value)) { hp = value; return true; } } return false; } private static bool TryReadFloatMember(Traverse traverse, string name, out float value) { value = 0f; try { value = traverse.Property<float>(name, (object[])null).Value; return true; } catch { } try { value = traverse.Field<float>(name).Value; return true; } catch { } return false; } private static bool TryReadIntMember(Traverse traverse, string name, out int value) { value = 0; try { value = traverse.Property<int>(name, (object[])null).Value; return true; } catch { } try { value = traverse.Field<int>(name).Value; return true; } catch { } return false; } } internal static class EnemyScanCache { private static EnemyHealth[] _enemies = Array.Empty<EnemyHealth>(); private static float _nextRefresh = -1f; private const float RefreshInterval = 0.5f; public static int Count => _enemies.Length; public static EnemyHealth[] GetEnemies() { RefreshIfNeeded(); return _enemies; } public static float NearestDistance(Vector3 origin) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) RefreshIfNeeded(); float num = float.MaxValue; for (int i = 0; i < _enemies.Length; i++) { EnemyHealth enemy = _enemies[i]; if (EnemyHealthCompat.IsValid(enemy)) { float num2 = Vector3.Distance(origin, GetFocusPosition(enemy)); if (num2 < num) { num = num2; } } } return num; } public static Vector3 GetFocusPosition(EnemyHealth enemy) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) if (!EnemyHealthCompat.IsValid(enemy)) { return Vector3.zero; } try { return ((Component)enemy).transform.position; } catch { return Vector3.zero; } } public static void Invalidate() { _nextRefresh = -1f; } private static void RefreshIfNeeded() { if (Time.time < _nextRefresh) { return; } _nextRefresh = Time.time + 0.5f; EnemyHealth[] array = Object.FindObjectsOfType<EnemyHealth>(); if (array == null || array.Length == 0) { _enemies = Array.Empty<EnemyHealth>(); return; } int num = 0; for (int i = 0; i < array.Length; i++) { if (EnemyHealthCompat.IsValid(array[i])) { array[num++] = array[i]; } } if (num == 0) { _enemies = Array.Empty<EnemyHealth>(); return; } EnemyHealth[] array2 = (EnemyHealth[])(object)new EnemyHealth[num]; Array.Copy(array, array2, num); _enemies = array2; } } public class ErrorReporterSystem : MonoBehaviour { [CompilerGenerated] private static class <>O { public static LogCallback <0>__OnLogMessageReceived; public static EventHandler <1>__OnErrorReportingSettingChanged; } [CompilerGenerated] private sealed class <ReportTestCrashAndWait>d__12 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public Exception ex; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <ReportTestCrashAndWait>d__12(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) if (<>1__state != 0) { return false; } <>1__state = -1; if (!ErrorReportingConsent.IsReportingAllowed()) { LoggingService.LogWarning("[ErrorReporter] Error reporting is not allowed yet (disabled or first-run prompt pending)."); return false; } LoggingService.LogInfo("[ErrorReporter] Sending test crash report (sync POST)..."); try { string message = this.ex.GetType().Name + ": " + this.ex.Message; string stack = this.ex.StackTrace ?? string.Empty; Scene activeScene = SceneManager.GetActiveScene(); string scene = ((Scene)(ref activeScene)).name ?? "unknown"; ErrorReport errorReport = ErrorReportPayloadCapture.BuildTestCrashReport(this.ex, message, stack, scene); ErrorPayload errorPayload = new ErrorPayload { ModVersion = "1.6.1", GameVersion = Application.version, UnityVersion = Application.unityVersion, Reports = new ErrorReport[1] { errorReport } }; if (ErrorReportUploader.TryPostPayloadSync(errorPayload, out string responseBody, out string error)) { if (ErrorReportUploader.HasWorkerReportFailures(responseBody, errorPayload.Reports)) { LoggingService.LogWarning("Test crash report reached worker but GitHub step failed. Response: " + responseBody); } else { LoggingService.LogInfo("Test crash report sent. Response: " + responseBody); } } else { LoggingService.LogWarning("Test crash report POST failed: " + error); } } catch (Exception ex) { LoggingService.LogWarning("[ErrorReporter] Test crash report failed: " + ex.Message); } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class <SendBatch>d__19 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public ErrorReporterSystem <>4__this; public List<ErrorReport> batch; private ErrorPayload <payload>5__2; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <SendBatch>d__19(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <payload>5__2 = null; <>1__state = -2; } private bool MoveNext() { bool result; try { int num = <>1__state; ErrorReporterSystem errorReporterSystem = <>4__this; switch (num) { default: result = false; break; case 0: { <>1__state = -1; errorReporterSystem._sendInProgress = true; <>1__state = -3; LoggingService.LogVerbose("[ErrorReporter] Sending report..."); <payload>5__2 = new ErrorPayload { ModVersion = "1.6.1", GameVersion = Application.version, UnityVersion = Application.unityVersion, Reports = batch.ToArray() }; ErrorReportUploader.EncodePayload(<payload>5__2, out string json); string text = ErrorReportUploader.ValidateBatchJson(json); if (text != null) { LoggingService.LogWarning("[ErrorReporter] " + text); errorReporterSystem.RequeueFailedBatch(batch); result = false; <>m__Finally1(); } else { <>2__current = null; <>1__state = 1; result = true; } break; } case 1: { <>1__state = -3; if (!ErrorReportUploader.TryPostPayloadSync(<payload>5__2, out string responseBody, out string error)) { LoggingService.LogWarning("Error report HTTP failed: " + error); errorReporterSystem.RequeueFailedBatch(batch); } else { errorReporterSystem.HandleWorkerResponse(responseBody, batch); } <payload>5__2 = null; <>m__Finally1(); result = false; break; } } } catch { //try-fault ((IDisposable)this).Dispose(); throw; } return result; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; <>4__this._sendInProgress = false; } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private readonly List<ErrorReport> _buffer = new List<ErrorReport>(); private float _lastFlushTime; private volatile bool _shouldFlush; private bool _sendInProgress; private const float FlushInterval = 300f; private void OnEnable() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown LoggingService.LogVerbose("[ErrorReporter] Awake starting..."); object obj = <>O.<0>__OnLogMessageReceived; if (obj == null) { LogCallback val = OnLogMessageReceived; <>O.<0>__OnLogMessageReceived = val; obj = (object)val; } Application.logMessageReceived += (LogCallback)obj; SceneManager.sceneLoaded += OnSceneLoaded; DreadConfig.ErrorReportingEnabled.SettingChanged += OnErrorReportingSettingChanged; _lastFlushTime = Time.realtimeSinceStartup; } private void OnDisable() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown object obj = <>O.<0>__OnLogMessageReceived; if (obj == null) { LogCallback val = OnLogMessageReceived; <>O.<0>__OnLogMessageReceived = val; obj = (object)val; } Application.logMessageReceived -= (LogCallback)obj; SceneManager.sceneLoaded -= OnSceneLoaded; DreadConfig.ErrorReportingEnabled.SettingChanged -= OnErrorReportingSettingChanged; FlushNow(); } private static void OnErrorReportingSettingChanged(object sender, EventArgs e) { if (ErrorReportingConsent.IsReportingAllowed()) { LoggingService.LogInfo("[Dread] Error reporting enabled. Anonymous error reporting (on by default for new installs). When enabled, serious Unity errors may be sent to the developer to fix bugs. To disable: set ErrorReportingEnabled = false in BepInEx/config/elytraking.dread.cfg (section 7. Error Reporting in elytraking.dread.cfg). REPOConfig lists the toggle only (no per-toggle description API); use the cfg file or Configuration Manager (F1) for full text."); } } private static void OnLogMessageReceived(string logString, string stackTrace, LogType type) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) if (!ShouldIgnoreUnityLog(logString, stackTrace)) { EnqueueLog(logString, stackTrace, type); } } private static bool ShouldIgnoreUnityLog(string logString, string stackTrace) { if (!logString.Contains("BadImageFormatException")) { return false; } if (logString.IndexOf("zero rva", StringComparison.OrdinalIgnoreCase) < 0) { return stackTrace.IndexOf("UnityEngine.Networking", StringComparison.Ordinal) >= 0; } return true; } internal static void EnqueueLog(string logString, string stackTrace, LogType type) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) ErrorReportLogQueue.EnqueueLog(logString, stackTrace, type); } private void Update() { ProcessPendingLogs(); if (_shouldFlush || Time.realtimeSinceStartup - _lastFlushTime >= 300f) { FlushNow(); } } [IteratorStateMachine(typeof(<ReportTestCrashAndWait>d__12))] internal IEnumerator ReportTestCrashAndWait(Exception ex) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <ReportTestCrashAndWait>d__12(0) { ex = ex }; } private void ProcessPendingLogs() { try { ProcessPendingLogsCore(); } catch (Exception ex) { LoggingService.LogWarning("[ErrorReporter] Failed to process pending logs: " + ex.Message); } } private void ProcessPendingLogsCore() { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Invalid comparison between Unknown and I4 if (!ErrorReportingConsent.IsReportingAllowed() || !ErrorReportLogQueue.TryDequeueBatch(out ErrorReportLogQueue.RawLogEntry[] batch)) { return; } GameStateData gameState = ErrorReportPayloadCapture.CaptureGameState(); SystemInfoData systemInfo = ErrorReportPayloadCapture.CaptureSystemInfoSafe(); DisplayInfoData display = ErrorReportPayloadCapture.CaptureDisplayInfoSafe(); ConfigData config = ErrorReportPayloadCapture.CaptureConfig(); Scene activeScene = SceneManager.GetActiveScene(); string scene = ((Scene)(ref activeScene)).name ?? "unknown"; ErrorReportLogQueue.RawLogEntry[] array = batch; foreach (ErrorReportLogQueue.RawLogEntry rawLogEntry in array) { ErrorReport item = new ErrorReport { Hash = ErrorReportLogQueue.ComputeHash(rawLogEntry.StackTrace, rawLogEntry.Message), Timestamp = DateTime.UtcNow.ToString("o"), Type = (((int)rawLogEntry.Type == 4) ? "exception" : "error"), ExceptionType = ErrorReportPayloadCapture.ParseExceptionType(rawLogEntry.Message), Message = ErrorReportPayloadCapture.Truncate(rawLogEntry.Message, 500), StackTrace = ErrorReportPayloadCapture.Truncate(rawLogEntry.StackTrace, 3000), Scene = scene, GameState = gameState, SystemInfo = systemInfo, Display = display, Config = config }; lock (_buffer) { _buffer.Add(item); if (_buffer.Count >= 50) { _shouldFlush = true; } } } } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { FlushNow(); } private void FlushNow() { if (_sendInProgress || !ErrorReportingConsent.IsReportingAllowed()) { return; } List<ErrorReport> batch; lock (_buffer) { if (_buffer.Count == 0) { return; } batch = new List<ErrorReport>(_buffer); _buffer.Clear(); } _shouldFlush = false; _lastFlushTime = Time.realtimeSinceStartup; ((MonoBehaviour)this).StartCoroutine(SendBatch(batch)); } private void RequeueFailedBatch(List<ErrorReport> batch) { if (batch.Count != 0) { lock (_buffer) { _buffer.AddRange(batch); } LoggingService.LogWarning($"[ErrorReporter] Re-queued {batch.Count} report(s) after failed send."); } } private void HandleWorkerResponse(string body, List<ErrorReport> batch) { List<ErrorReport> list = ErrorReportUploader.CollectFailedReports(body, batch); if (list.Count > 0) { LoggingService.LogWarning($"[ErrorReporter] Worker reported {list.Count} GitHub failure(s). Response: {body}"); RequeueFailedBatch(list); } else if (ErrorReportUploader.HasUnmappedWorkerErrors(body)) { LoggingService.LogWarning("[ErrorReporter] Worker returned errors; re-queuing full batch. Response: " + body); RequeueFailedBatch(batch); } else { LoggingService.LogInfo($"Sent {batch.Count} error report(s). Response: {body}"); } } [IteratorStateMachine(typeof(<SendBatch>d__19))] private IEnumerator SendBatch(List<ErrorReport> batch) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <SendBatch>d__19(0) { <>4__this = this, batch = batch }; } } internal static class ErrorReportingConsent { public static bool IsReportingAllowed() { if (!DreadConfig.ErrorReportingEnabled.Value) { return false; } if (!DreadConfig.ErrorReportingPromptShown.Value) { return false; } return true; } } internal static class ErrorReportingPrivacyCopy { public const string ShortSummary = "Anonymous error reporting (on by default for new installs). When enabled, serious Unity errors may be sent to the developer to fix bugs."; public const string DisableInstructions = "To disable: set ErrorReportingEnabled = false in BepInEx/config/elytraking.dread.cfg (section 7. Error Reporting in elytraking.dread.cfg). REPOConfig lists the toggle only (no per-toggle description API); use the cfg file or Configuration Manager (F1) for full text."; public static readonly string[] DataBullets; public static readonly string FullDescription; static ErrorReportingPrivacyCopy() { DataBullets = new string[9] { "Exception type, message (length-capped), stack trace (length-capped), and a dedupe hash", "Active scene name and session play time", "Enemy counts (alive, total, nearby)", "Player HP, stamina, and world position when available", "OS, CPU, RAM, GPU, device model, and may include VRAM, GPU driver version, and shader level", "Screen resolution, refresh rate, DPI, and fullscreen mode", "Eleven named Dread settings (toggles plus audio frequency and volume), including this setting", "Not sent: your username, Steam profile, or deliberate PII", "Default on for new installs; turn off anytime via the first-run prompt or cfg" };
BepInEx/plugins/elytraking-Dread/NVorbis.dll
Decompiled a week ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using NVorbis.Contracts; using NVorbis.Contracts.Ogg; using NVorbis.Ogg; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName = ".NET Framework 4.5")] [assembly: AssemblyCompany("Andrew Ward")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © Andrew Ward 2021")] [assembly: AssemblyDescription("A fully managed implementation of a Xiph.org Foundation Ogg Vorbis decoder.")] [assembly: AssemblyFileVersion("0.10.5.0")] [assembly: AssemblyInformationalVersion("0.10.5")] [assembly: AssemblyProduct("NVorbis")] [assembly: AssemblyTitle("NVorbis")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/NVorbis/NVorbis")] [assembly: NeutralResourcesLanguage("en")] [assembly: AssemblyVersion("0.10.5.0")] namespace NVorbis { internal class Codebook : ICodebook { private class FastRange : IReadOnlyList<int>, IReadOnlyCollection<int>, IEnumerable<int>, IEnumerable { [ThreadStatic] private static FastRange _cachedRange; private int _start; private int _count; public int this[int index] { get { if (index > _count) { throw new ArgumentOutOfRangeException(); } return _start + index; } } public int Count => _count; internal static FastRange Get(int start, int count) { FastRange obj = _cachedRange ?? (_cachedRange = new FastRange()); obj._start = start; obj._count = count; return obj; } private FastRange() { } public IEnumerator<int> GetEnumerator() { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private int[] _lengths; private float[] _lookupTable; private IReadOnlyList<HuffmanListNode> _overflowList; private IReadOnlyList<HuffmanListNode> _prefixList; private int _prefixBitLength; private int _maxBits; public float this[int entry, int dim] => _lookupTable[entry * Dimensions + dim]; public int Dimensions { get; private set; } public int Entries { get; private set; } public int MapType { get; private set; } public void Init(IPacket packet, IHuffman huffman) { if (packet.ReadBits(24) != 5653314) { throw new InvalidDataException("Book header had invalid signature!"); } Dimensions = (int)packet.ReadBits(16); Entries = (int)packet.ReadBits(24); _lengths = new int[Entries]; InitTree(packet, huffman); InitLookupTable(packet); } private void InitTree(IPacket packet, IHuffman huffman) { int num = 0; bool flag; int num5; if (packet.ReadBit()) { int num2 = (int)packet.ReadBits(5) + 1; int num3 = 0; while (num3 < Entries) { int num4 = (int)packet.ReadBits(Utils.ilog(Entries - num3)); while (--num4 >= 0) { _lengths[num3++] = num2; } num2++; } num = 0; flag = false; num5 = num2; } else { num5 = -1; flag = packet.ReadBit(); for (int i = 0; i < Entries; i++) { if (!flag || packet.ReadBit()) { _lengths[i] = (int)packet.ReadBits(5) + 1; num++; } else { _lengths[i] = -1; } if (_lengths[i] > num5) { num5 = _lengths[i]; } } } if ((_maxBits = num5) > -1) { int[] array = null; if (flag && num >= Entries >> 2) { array = new int[Entries]; Array.Copy(_lengths, array, Entries); flag = false; } int num6 = (flag ? num : 0); int[] array2 = null; int[] array3 = null; if (!flag) { array3 = new int[Entries]; } else if (num6 != 0) { array = new int[num6]; array3 = new int[num6]; array2 = new int[num6]; } if (!ComputeCodewords(flag, array3, array, _lengths, Entries, array2)) { throw new InvalidDataException(); } IReadOnlyList<int> readOnlyList = array2; IReadOnlyList<int> value = readOnlyList ?? FastRange.Get(0, array3.Length); huffman.GenerateTable(value, array ?? _lengths, array3); _prefixList = huffman.PrefixTree; _prefixBitLength = huffman.TableBits; _overflowList = huffman.OverflowList; } } private bool ComputeCodewords(bool sparse, int[] codewords, int[] codewordLengths, int[] len, int n, int[] values) { int num = 0; uint[] array = new uint[32]; int i; for (i = 0; i < n && len[i] <= 0; i++) { } if (i == n) { return true; } AddEntry(sparse, codewords, codewordLengths, 0u, i, num++, len[i], values); for (int j = 1; j <= len[i]; j++) { array[j] = (uint)(1 << 32 - j); } for (int j = i + 1; j < n; j++) { int num2 = len[j]; if (num2 <= 0) { continue; } while (num2 > 0 && array[num2] == 0) { num2--; } if (num2 == 0) { return false; } uint num3 = array[num2]; array[num2] = 0u; AddEntry(sparse, codewords, codewordLengths, Utils.BitReverse(num3), j, num++, len[j], values); if (num2 != len[j]) { for (int num4 = len[j]; num4 > num2; num4--) { array[num4] = num3 + (uint)(1 << 32 - num4); } } } return true; } private void AddEntry(bool sparse, int[] codewords, int[] codewordLengths, uint huffCode, int symbol, int count, int len, int[] values) { if (sparse) { codewords[count] = (int)huffCode; codewordLengths[count] = len; values[count] = symbol; } else { codewords[symbol] = (int)huffCode; } } private void InitLookupTable(IPacket packet) { MapType = (int)packet.ReadBits(4); if (MapType == 0) { return; } float num = Utils.ConvertFromVorbisFloat32((uint)packet.ReadBits(32)); float num2 = Utils.ConvertFromVorbisFloat32((uint)packet.ReadBits(32)); int count = (int)packet.ReadBits(4) + 1; bool flag = packet.ReadBit(); int num3 = Entries * Dimensions; float[] array = new float[num3]; if (MapType == 1) { num3 = lookup1_values(); } uint[] array2 = new uint[num3]; for (int i = 0; i < num3; i++) { array2[i] = (uint)packet.ReadBits(count); } if (MapType == 1) { for (int j = 0; j < Entries; j++) { double num4 = 0.0; int num5 = 1; for (int k = 0; k < Dimensions; k++) { int num6 = j / num5 % num3; double num7 = (double)((float)array2[num6] * num2 + num) + num4; array[j * Dimensions + k] = (float)num7; if (flag) { num4 = num7; } num5 *= num3; } } } else { for (int l = 0; l < Entries; l++) { double num8 = 0.0; int num9 = l * Dimensions; for (int m = 0; m < Dimensions; m++) { double num10 = (double)((float)array2[num9] * num2 + num) + num8; array[l * Dimensions + m] = (float)num10; if (flag) { num8 = num10; } num9++; } } } _lookupTable = array; } private int lookup1_values() { int num = (int)Math.Floor(Math.Exp(Math.Log(Entries) / (double)Dimensions)); if (Math.Floor(Math.Pow(num + 1, Dimensions)) <= (double)Entries) { num++; } return num; } public int DecodeScalar(IPacket packet) { int index = (int)packet.TryPeekBits(_prefixBitLength, out var bitsRead); if (bitsRead == 0) { return -1; } HuffmanListNode huffmanListNode = _prefixList[index]; if (huffmanListNode != null) { packet.SkipBits(huffmanListNode.Length); return huffmanListNode.Value; } index = (int)packet.TryPeekBits(_maxBits, out var _); for (int i = 0; i < _overflowList.Count; i++) { huffmanListNode = _overflowList[i]; if (huffmanListNode.Bits == (index & huffmanListNode.Mask)) { packet.SkipBits(huffmanListNode.Length); return huffmanListNode.Value; } } return -1; } } public abstract class DataPacket : IPacket { [Flags] protected enum PacketFlags : byte { IsResync = 1, IsEndOfStream = 2, IsShort = 4, User0 = 8, User1 = 0x10, User2 = 0x20, User3 = 0x40, User4 = 0x80 } private ulong _bitBucket; private int _bitCount; private byte _overflowBits; private PacketFlags _packetFlags; private int _readBits; public int ContainerOverheadBits { get; set; } public long? GranulePosition { get; set; } public bool IsResync { get { return GetFlag(PacketFlags.IsResync); } set { SetFlag(PacketFlags.IsResync, value); } } public bool IsShort { get { return GetFlag(PacketFlags.IsShort); } private set { SetFlag(PacketFlags.IsShort, value); } } public bool IsEndOfStream { get { return GetFlag(PacketFlags.IsEndOfStream); } set { SetFlag(PacketFlags.IsEndOfStream, value); } } public int BitsRead => _readBits; public int BitsRemaining => TotalBits - _readBits; protected abstract int TotalBits { get; } private bool GetFlag(PacketFlags flag) { return _packetFlags.HasFlag(flag); } private void SetFlag(PacketFlags flag, bool value) { if (value) { _packetFlags |= flag; } else { _packetFlags &= (PacketFlags)(byte)(~(int)flag); } } protected abstract int ReadNextByte(); public virtual void Done() { } public virtual void Reset() { _bitBucket = 0uL; _bitCount = 0; _overflowBits = 0; _readBits = 0; } ulong IPacket.ReadBits(int count) { if (count == 0) { return 0uL; } int bitsRead; ulong result = TryPeekBits(count, out bitsRead); SkipBits(count); return result; } public ulong TryPeekBits(int count, out int bitsRead) { switch (count) { default: throw new ArgumentOutOfRangeException("count"); case 0: bitsRead = 0; return 0uL; case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 58: case 59: case 60: case 61: case 62: case 63: case 64: break; } while (_bitCount < count) { int num = ReadNextByte(); if (num == -1) { bitsRead = _bitCount; return _bitBucket; } _bitBucket = (ulong)((long)(num & 0xFF) << _bitCount) | _bitBucket; _bitCount += 8; if (_bitCount > 64) { _overflowBits = (byte)(num >> 72 - _bitCount); } } ulong num2 = _bitBucket; if (count < 64) { num2 &= (ulong)((1L << count) - 1); } bitsRead = count; return num2; } public void SkipBits(int count) { if (count <= 0) { return; } if (_bitCount > count) { if (count > 63) { _bitBucket = 0uL; } else { _bitBucket >>= count; } if (_bitCount > 64) { int num = _bitCount - 64; _bitBucket |= (ulong)_overflowBits << _bitCount - count - num; if (num > count) { _overflowBits = (byte)(_overflowBits >> count); } } _bitCount -= count; _readBits += count; return; } if (_bitCount == count) { _bitBucket = 0uL; _bitCount = 0; _readBits += count; return; } count -= _bitCount; _readBits += _bitCount; _bitCount = 0; _bitBucket = 0uL; while (count > 8) { if (ReadNextByte() == -1) { count = 0; IsShort = true; break; } count -= 8; _readBits += 8; } if (count > 0) { int num2 = ReadNextByte(); if (num2 == -1) { IsShort = true; return; } _bitBucket = (ulong)(num2 >> count); _bitCount = 8 - count; _readBits += count; } } } public static class Extensions { public static int Read(this IPacket packet, byte[] buffer, int index, int count) { if (index < 0 || index >= buffer.Length) { throw new ArgumentOutOfRangeException("index"); } if (count < 0 || index + count > buffer.Length) { throw new ArgumentOutOfRangeException("count"); } for (int i = 0; i < count; i++) { int bitsRead; byte b = (byte)packet.TryPeekBits(8, out bitsRead); if (bitsRead == 0) { return i; } buffer[index++] = b; packet.SkipBits(8); } return count; } public static byte[] ReadBytes(this IPacket packet, int count) { byte[] array = new byte[count]; int num = packet.Read(array, 0, count); if (num < count) { byte[] array2 = new byte[num]; Buffer.BlockCopy(array, 0, array2, 0, num); return array2; } return array; } public static bool ReadBit(this IPacket packet) { return packet.ReadBits(1) == 1; } public static byte PeekByte(this IPacket packet) { int bitsRead; return (byte)packet.TryPeekBits(8, out bitsRead); } public static byte ReadByte(this IPacket packet) { return (byte)packet.ReadBits(8); } public static short ReadInt16(this IPacket packet) { return (short)packet.ReadBits(16); } public static int ReadInt32(this IPacket packet) { return (int)packet.ReadBits(32); } public static long ReadInt64(this IPacket packet) { return (long)packet.ReadBits(64); } public static ushort ReadUInt16(this IPacket packet) { return (ushort)packet.ReadBits(16); } public static uint ReadUInt32(this IPacket packet) { return (uint)packet.ReadBits(32); } public static ulong ReadUInt64(this IPacket packet) { return packet.ReadBits(64); } public static void SkipBytes(this IPacket packet, int count) { packet.SkipBits(count * 8); } } internal class Factory : IFactory { public IHuffman CreateHuffman() { return new Huffman(); } public IMdct CreateMdct() { return new Mdct(); } public ICodebook CreateCodebook() { return new Codebook(); } public IFloor CreateFloor(IPacket packet) { return (int)packet.ReadBits(16) switch { 0 => new Floor0(), 1 => new Floor1(), _ => throw new InvalidDataException("Invalid floor type!"), }; } public IMapping CreateMapping(IPacket packet) { if (packet.ReadBits(16) != 0L) { throw new InvalidDataException("Invalid mapping type!"); } return new Mapping(); } public IMode CreateMode() { return new Mode(); } public IResidue CreateResidue(IPacket packet) { return (int)packet.ReadBits(16) switch { 0 => new Residue0(), 1 => new Residue1(), 2 => new Residue2(), _ => throw new InvalidDataException("Invalid residue type!"), }; } } internal class Floor0 : IFloor { private class Data : IFloorData { internal float[] Coeff; internal float Amp; public bool ExecuteChannel { get { if (ForceEnergy || Amp > 0f) { return !ForceNoEnergy; } return false; } } public bool ForceEnergy { get; set; } public bool ForceNoEnergy { get; set; } } private int _order; private int _rate; private int _bark_map_size; private int _ampBits; private int _ampOfs; private int _ampDiv; private ICodebook[] _books; private int _bookBits; private Dictionary<int, float[]> _wMap; private Dictionary<int, int[]> _barkMaps; public void Init(IPacket packet, int channels, int block0Size, int block1Size, ICodebook[] codebooks) { _order = (int)packet.ReadBits(8); _rate = (int)packet.ReadBits(16); _bark_map_size = (int)packet.ReadBits(16); _ampBits = (int)packet.ReadBits(6); _ampOfs = (int)packet.ReadBits(8); _books = new ICodebook[(int)packet.ReadBits(4) + 1]; if (_order < 1 || _rate < 1 || _bark_map_size < 1 || _books.Length == 0) { throw new InvalidDataException(); } _ampDiv = (1 << _ampBits) - 1; for (int i = 0; i < _books.Length; i++) { int num = (int)packet.ReadBits(8); if (num < 0 || num >= codebooks.Length) { throw new InvalidDataException(); } ICodebook codebook = codebooks[num]; if (codebook.MapType == 0 || codebook.Dimensions < 1) { throw new InvalidDataException(); } _books[i] = codebook; } _bookBits = Utils.ilog(_books.Length); _barkMaps = new Dictionary<int, int[]> { [block0Size] = SynthesizeBarkCurve(block0Size / 2), [block1Size] = SynthesizeBarkCurve(block1Size / 2) }; _wMap = new Dictionary<int, float[]> { [block0Size] = SynthesizeWDelMap(block0Size / 2), [block1Size] = SynthesizeWDelMap(block1Size / 2) }; } private int[] SynthesizeBarkCurve(int n) { float num = (float)_bark_map_size / toBARK(_rate / 2); int[] array = new int[n + 1]; for (int i = 0; i < n - 1; i++) { array[i] = Math.Min(_bark_map_size - 1, (int)Math.Floor(toBARK((float)_rate / 2f / (float)n * (float)i) * num)); } array[n] = -1; return array; } private static float toBARK(double lsp) { return (float)(13.1 * Math.Atan(0.00074 * lsp) + 2.24 * Math.Atan(1.85E-08 * lsp * lsp) + 0.0001 * lsp); } private float[] SynthesizeWDelMap(int n) { float num = (float)(Math.PI / (double)_bark_map_size); float[] array = new float[n]; for (int i = 0; i < n; i++) { array[i] = 2f * (float)Math.Cos(num * (float)i); } return array; } public IFloorData Unpack(IPacket packet, int blockSize, int channel) { Data data = new Data { Coeff = new float[_order + 1] }; data.Amp = packet.ReadBits(_ampBits); if (data.Amp > 0f) { Array.Clear(data.Coeff, 0, data.Coeff.Length); data.Amp = data.Amp / (float)_ampDiv * (float)_ampOfs; uint num = (uint)packet.ReadBits(_bookBits); if (num >= _books.Length) { data.Amp = 0f; return data; } ICodebook codebook = _books[num]; int i = 0; while (i < _order) { int num2 = codebook.DecodeScalar(packet); if (num2 == -1) { data.Amp = 0f; return data; } int num3 = 0; for (; i < _order; i++) { if (num3 >= codebook.Dimensions) { break; } data.Coeff[i] = codebook[num2, num3]; num3++; } } float num4 = 0f; int num5 = 0; while (num5 < _order) { int num6 = 0; while (num5 < _order && num6 < codebook.Dimensions) { data.Coeff[num5] += num4; num5++; num6++; } num4 = data.Coeff[num5 - 1]; } } return data; } public void Apply(IFloorData floorData, int blockSize, float[] residue) { if (!(floorData is Data data)) { throw new ArgumentException("Incorrect packet data!"); } int num = blockSize / 2; if (data.Amp > 0f) { int[] array = _barkMaps[blockSize]; float[] array2 = _wMap[blockSize]; int num2 = 0; for (num2 = 0; num2 < _order; num2++) { data.Coeff[num2] = 2f * (float)Math.Cos(data.Coeff[num2]); } num2 = 0; while (num2 < num) { int num3 = array[num2]; float num4 = 0.5f; float num5 = 0.5f; float num6 = array2[num3]; int i; for (i = 1; i < _order; i += 2) { num5 *= num6 - data.Coeff[i - 1]; num4 *= num6 - data.Coeff[i]; } if (i == _order) { num5 *= num6 - data.Coeff[i - 1]; num4 *= num4 * (4f - num6 * num6); num5 *= num5; } else { num4 *= num4 * (2f - num6); num5 *= num5 * (2f + num6); } num5 = data.Amp / (float)Math.Sqrt(num4 + num5) - (float)_ampOfs; num5 = (float)Math.Exp(num5 * 0.11512925f); residue[num2] *= num5; while (array[++num2] == num3) { residue[num2] *= num5; } } } else { Array.Clear(residue, 0, num); } } } internal class Floor1 : IFloor { private class Data : IFloorData { internal int[] Posts = new int[64]; internal int PostCount; public bool ExecuteChannel { get { if (ForceEnergy || PostCount > 0) { return !ForceNoEnergy; } return false; } } public bool ForceEnergy { get; set; } public bool ForceNoEnergy { get; set; } } private int[] _partitionClass; private int[] _classDimensions; private int[] _classSubclasses; private int[] _xList; private int[] _classMasterBookIndex; private int[] _hNeigh; private int[] _lNeigh; private int[] _sortIdx; private int _multiplier; private int _range; private int _yBits; private ICodebook[] _classMasterbooks; private ICodebook[][] _subclassBooks; private int[][] _subclassBookIndex; private static readonly int[] _rangeLookup = new int[4] { 256, 128, 86, 64 }; private static readonly int[] _yBitsLookup = new int[4] { 8, 7, 7, 6 }; private static readonly float[] inverse_dB_table = new float[256] { 1.0649863E-07f, 1.1341951E-07f, 1.2079015E-07f, 1.2863978E-07f, 1.369995E-07f, 1.459025E-07f, 1.5538409E-07f, 1.6548181E-07f, 1.7623574E-07f, 1.8768856E-07f, 1.998856E-07f, 2.128753E-07f, 2.2670913E-07f, 2.4144197E-07f, 2.5713223E-07f, 2.7384212E-07f, 2.9163792E-07f, 3.1059022E-07f, 3.307741E-07f, 3.5226967E-07f, 3.7516213E-07f, 3.995423E-07f, 4.255068E-07f, 4.5315863E-07f, 4.8260745E-07f, 5.1397E-07f, 5.4737063E-07f, 5.829419E-07f, 6.208247E-07f, 6.611694E-07f, 7.041359E-07f, 7.4989464E-07f, 7.98627E-07f, 8.505263E-07f, 9.057983E-07f, 9.646621E-07f, 1.0273513E-06f, 1.0941144E-06f, 1.1652161E-06f, 1.2409384E-06f, 1.3215816E-06f, 1.4074654E-06f, 1.4989305E-06f, 1.5963394E-06f, 1.7000785E-06f, 1.8105592E-06f, 1.9282195E-06f, 2.053526E-06f, 2.1869757E-06f, 2.3290977E-06f, 2.4804558E-06f, 2.6416496E-06f, 2.813319E-06f, 2.9961443E-06f, 3.1908505E-06f, 3.39821E-06f, 3.619045E-06f, 3.8542307E-06f, 4.1047006E-06f, 4.371447E-06f, 4.6555283E-06f, 4.958071E-06f, 5.280274E-06f, 5.623416E-06f, 5.988857E-06f, 6.3780467E-06f, 6.7925284E-06f, 7.2339453E-06f, 7.704048E-06f, 8.2047E-06f, 8.737888E-06f, 9.305725E-06f, 9.910464E-06f, 1.0554501E-05f, 1.1240392E-05f, 1.1970856E-05f, 1.2748789E-05f, 1.3577278E-05f, 1.4459606E-05f, 1.5399271E-05f, 1.6400005E-05f, 1.7465769E-05f, 1.8600793E-05f, 1.9809577E-05f, 2.1096914E-05f, 2.2467912E-05f, 2.3928002E-05f, 2.5482977E-05f, 2.7139005E-05f, 2.890265E-05f, 3.078091E-05f, 3.2781227E-05f, 3.4911533E-05f, 3.718028E-05f, 3.9596467E-05f, 4.2169668E-05f, 4.491009E-05f, 4.7828602E-05f, 5.0936775E-05f, 5.424693E-05f, 5.7772202E-05f, 6.152657E-05f, 6.552491E-05f, 6.9783084E-05f, 7.4317984E-05f, 7.914758E-05f, 8.429104E-05f, 8.976875E-05f, 9.560242E-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f, 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f, 0.00015820454f, 0.00016848555f, 0.00017943469f, 0.00019109536f, 0.00020351382f, 0.0002167393f, 0.00023082423f, 0.00024582449f, 0.00026179955f, 0.00027881275f, 0.00029693157f, 0.00031622787f, 0.00033677815f, 0.00035866388f, 0.00038197188f, 0.00040679457f, 0.00043323037f, 0.0004613841f, 0.0004913675f, 0.00052329927f, 0.0005573062f, 0.0005935231f, 0.0006320936f, 0.0006731706f, 0.000716917f, 0.0007635063f, 0.00081312325f, 0.00086596457f, 0.00092223985f, 0.0009821722f, 0.0010459992f, 0.0011139743f, 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f, 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f, 0.0019632196f, 0.0020908006f, 0.0022266726f, 0.0023713743f, 0.0025254795f, 0.0026895993f, 0.0028643848f, 0.0030505287f, 0.003248769f, 0.0034598925f, 0.0036847359f, 0.0039241905f, 0.0041792067f, 0.004450795f, 0.004740033f, 0.005048067f, 0.0053761187f, 0.005725489f, 0.0060975635f, 0.0064938175f, 0.0069158226f, 0.0073652514f, 0.007843887f, 0.008353627f, 0.008896492f, 0.009474637f, 0.010090352f, 0.01074608f, 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f, 0.014722068f, 0.015678791f, 0.016697686f, 0.017782796f, 0.018938422f, 0.020169148f, 0.021479854f, 0.022875736f, 0.02436233f, 0.025945531f, 0.027631618f, 0.029427277f, 0.031339627f, 0.03337625f, 0.035545226f, 0.037855156f, 0.0403152f, 0.042935107f, 0.045725275f, 0.048696756f, 0.05186135f, 0.05523159f, 0.05882085f, 0.062643364f, 0.06671428f, 0.07104975f, 0.075666964f, 0.08058423f, 0.08582105f, 0.09139818f, 0.097337745f, 0.1036633f, 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f, 0.14201812f, 0.15124726f, 0.16107617f, 0.1715438f, 0.18269168f, 0.19456401f, 0.20720787f, 0.22067343f, 0.23501402f, 0.25028655f, 0.26655158f, 0.28387362f, 0.3023213f, 0.32196787f, 0.34289113f, 0.36517414f, 0.3889052f, 0.41417846f, 0.44109413f, 0.4697589f, 0.50028646f, 0.53279793f, 0.5674221f, 0.6042964f, 0.64356697f, 0.6853896f, 0.72993004f, 0.777365f, 0.8278826f, 0.88168305f, 0.9389798f, 1f }; public void Init(IPacket packet, int channels, int block0Size, int block1Size, ICodebook[] codebooks) { int num = -1; _partitionClass = new int[(uint)packet.ReadBits(5)]; for (int i = 0; i < _partitionClass.Length; i++) { _partitionClass[i] = (int)packet.ReadBits(4); if (_partitionClass[i] > num) { num = _partitionClass[i]; } } _classDimensions = new int[++num]; _classSubclasses = new int[num]; _classMasterbooks = new ICodebook[num]; _classMasterBookIndex = new int[num]; _subclassBooks = new ICodebook[num][]; _subclassBookIndex = new int[num][]; for (int j = 0; j < num; j++) { _classDimensions[j] = (int)packet.ReadBits(3) + 1; _classSubclasses[j] = (int)packet.ReadBits(2); if (_classSubclasses[j] > 0) { _classMasterBookIndex[j] = (int)packet.ReadBits(8); _classMasterbooks[j] = codebooks[_classMasterBookIndex[j]]; } _subclassBooks[j] = new ICodebook[1 << _classSubclasses[j]]; _subclassBookIndex[j] = new int[_subclassBooks[j].Length]; for (int k = 0; k < _subclassBooks[j].Length; k++) { int num2 = (int)packet.ReadBits(8) - 1; if (num2 >= 0) { _subclassBooks[j][k] = codebooks[num2]; } _subclassBookIndex[j][k] = num2; } } _multiplier = (int)packet.ReadBits(2); _range = _rangeLookup[_multiplier]; _yBits = _yBitsLookup[_multiplier]; _multiplier++; int num3 = (int)packet.ReadBits(4); List<int> list = new List<int>(); list.Add(0); list.Add(1 << num3); for (int l = 0; l < _partitionClass.Length; l++) { int num4 = _partitionClass[l]; for (int m = 0; m < _classDimensions[num4]; m++) { list.Add((int)packet.ReadBits(num3)); } } _xList = list.ToArray(); _lNeigh = new int[list.Count]; _hNeigh = new int[list.Count]; _sortIdx = new int[list.Count]; _sortIdx[0] = 0; _sortIdx[1] = 1; for (int n = 2; n < _lNeigh.Length; n++) { _lNeigh[n] = 0; _hNeigh[n] = 1; _sortIdx[n] = n; for (int num5 = 2; num5 < n; num5++) { int num6 = _xList[num5]; if (num6 < _xList[n]) { if (num6 > _xList[_lNeigh[n]]) { _lNeigh[n] = num5; } } else if (num6 < _xList[_hNeigh[n]]) { _hNeigh[n] = num5; } } } for (int num7 = 0; num7 < _sortIdx.Length - 1; num7++) { for (int num8 = num7 + 1; num8 < _sortIdx.Length; num8++) { if (_xList[num7] == _xList[num8]) { throw new InvalidDataException(); } if (_xList[_sortIdx[num7]] > _xList[_sortIdx[num8]]) { int num9 = _sortIdx[num7]; _sortIdx[num7] = _sortIdx[num8]; _sortIdx[num8] = num9; } } } } public IFloorData Unpack(IPacket packet, int blockSize, int channel) { Data data = new Data(); if (packet.ReadBit()) { int num = 2; data.Posts[0] = (int)packet.ReadBits(_yBits); data.Posts[1] = (int)packet.ReadBits(_yBits); for (int i = 0; i < _partitionClass.Length; i++) { int num2 = _partitionClass[i]; int num3 = _classDimensions[num2]; int num4 = _classSubclasses[num2]; int num5 = (1 << num4) - 1; uint num6 = 0u; if (num4 > 0 && (num6 = (uint)_classMasterbooks[num2].DecodeScalar(packet)) == uint.MaxValue) { num = 0; break; } for (int j = 0; j < num3; j++) { ICodebook codebook = _subclassBooks[num2][num6 & num5]; num6 >>= num4; if (codebook != null && (data.Posts[num] = codebook.DecodeScalar(packet)) == -1) { num = 0; i = _partitionClass.Length; break; } num++; } } data.PostCount = num; } return data; } public void Apply(IFloorData floorData, int blockSize, float[] residue) { if (!(floorData is Data data)) { throw new ArgumentException("Incorrect packet data!", "packetData"); } int num = blockSize / 2; if (data.PostCount > 0) { bool[] array = UnwrapPosts(data); int num2 = 0; int num3 = data.Posts[0] * _multiplier; for (int i = 1; i < data.PostCount; i++) { int num4 = _sortIdx[i]; if (array[num4]) { int num5 = _xList[num4]; int num6 = data.Posts[num4] * _multiplier; if (num2 < num) { RenderLineMulti(num2, num3, Math.Min(num5, num), num6, residue); } num2 = num5; num3 = num6; } if (num2 >= num) { break; } } if (num2 < num) { RenderLineMulti(num2, num3, num, num3, residue); } } else { Array.Clear(residue, 0, num); } } private bool[] UnwrapPosts(Data data) { bool[] array = new bool[64]; array[0] = true; array[1] = true; int[] array2 = new int[64]; array2[0] = data.Posts[0]; array2[1] = data.Posts[1]; for (int i = 2; i < data.PostCount; i++) { int num = _lNeigh[i]; int num2 = _hNeigh[i]; int num3 = RenderPoint(_xList[num], array2[num], _xList[num2], array2[num2], _xList[i]); int num4 = data.Posts[i]; int num5 = _range - num3; int num6 = num3; int num7 = ((num5 >= num6) ? (num6 * 2) : (num5 * 2)); if (num4 != 0) { array[num] = true; array[num2] = true; array[i] = true; if (num4 >= num7) { if (num5 > num6) { array2[i] = num4 - num6 + num3; } else { array2[i] = num3 - num4 + num5 - 1; } } else if (num4 % 2 == 1) { array2[i] = num3 - (num4 + 1) / 2; } else { array2[i] = num3 + num4 / 2; } } else { array[i] = false; array2[i] = num3; } } for (int j = 0; j < data.PostCount; j++) { data.Posts[j] = array2[j]; } return array; } private int RenderPoint(int x0, int y0, int x1, int y1, int X) { int num = y1 - y0; int num2 = x1 - x0; int num3 = Math.Abs(num) * (X - x0) / num2; if (num < 0) { return y0 - num3; } return y0 + num3; } private void RenderLineMulti(int x0, int y0, int x1, int y1, float[] v) { int num = y1 - y0; int num2 = x1 - x0; int num3 = Math.Abs(num); int num4 = 1 - ((num >> 31) & 1) * 2; int num5 = num / num2; int num6 = x0; int num7 = y0; int num8 = -num2; v[x0] *= inverse_dB_table[y0]; num3 -= Math.Abs(num5) * num2; while (++num6 < x1) { num7 += num5; num8 += num3; if (num8 >= 0) { num8 -= num2; num7 += num4; } v[num6] *= inverse_dB_table[num7]; } } } internal class Huffman : IHuffman, IComparer<HuffmanListNode> { private const int MAX_TABLE_BITS = 10; public int TableBits { get; private set; } public IReadOnlyList<HuffmanListNode> PrefixTree { get; private set; } public IReadOnlyList<HuffmanListNode> OverflowList { get; private set; } public void GenerateTable(IReadOnlyList<int> values, int[] lengthList, int[] codeList) { HuffmanListNode[] array = new HuffmanListNode[lengthList.Length]; int num = 0; for (int i = 0; i < array.Length; i++) { array[i] = new HuffmanListNode { Value = values[i], Length = ((lengthList[i] <= 0) ? 99999 : lengthList[i]), Bits = codeList[i], Mask = (1 << lengthList[i]) - 1 }; if (lengthList[i] > 0 && num < lengthList[i]) { num = lengthList[i]; } } Array.Sort(array, 0, array.Length, this); int num2 = ((num > 10) ? 10 : num); List<HuffmanListNode> list = new List<HuffmanListNode>(1 << num2); List<HuffmanListNode> list2 = null; for (int j = 0; j < array.Length && array[j].Length < 99999; j++) { int length = array[j].Length; if (length > num2) { list2 = new List<HuffmanListNode>(array.Length - j); for (; j < array.Length && array[j].Length < 99999; j++) { list2.Add(array[j]); } continue; } int num3 = 1 << num2 - length; HuffmanListNode huffmanListNode = array[j]; for (int k = 0; k < num3; k++) { int num4 = (k << length) | huffmanListNode.Bits; while (list.Count <= num4) { list.Add(null); } list[num4] = huffmanListNode; } } while (list.Count < 1 << num2) { list.Add(null); } TableBits = num2; PrefixTree = list; OverflowList = list2; } int IComparer<HuffmanListNode>.Compare(HuffmanListNode x, HuffmanListNode y) { int num = x.Length - y.Length; if (num == 0) { return x.Bits - y.Bits; } return num; } } [Obsolete("Moved to NVorbis.Contracts.IContainerReader", true)] public interface IContainerReader : NVorbis.Contracts.IContainerReader, IDisposable { [Obsolete("Use Streams.Select(s => s.StreamSerial).ToArray() instead.", true)] int[] StreamSerials { get; } [Obsolete("No longer supported.", true)] int PagesRead { get; } [Obsolete("Moved to NewStreamCallback.", true)] event EventHandler<NewStreamEventArgs> NewStream; [Obsolete("Renamed to TryInit().", true)] bool Init(); [Obsolete("No longer supported.", true)] int GetTotalPageCount(); } [Obsolete("Moved to NVorbis.Contracts.IPacketProvider", true)] public interface IPacketProvider : NVorbis.Contracts.IPacketProvider { [Obsolete("Moved to per-stream IStreamStats instance on IStreamDecoder.Stats or VorbisReader.Stats.", true)] long ContainerBits { get; } [Obsolete("No longer supported.", true)] event EventHandler ParameterChange; [Obsolete("No longer supported.", true)] int GetTotalPageCount(); [Obsolete("Getting a packet by index is no longer supported.", true)] DataPacket GetPacket(int packetIndex); [Obsolete("Moved to long SeekTo(long, int, GetPacketGranuleCount)", true)] DataPacket FindPacket(long granulePos, Func<DataPacket, DataPacket, int> packetGranuleCountCallback); [Obsolete("Seeking to a specified packet is no longer supported. See SeekTo(...) instead.", true)] void SeekToPacket(DataPacket packet, int preRoll); } [Obsolete("Moved to NVorbis.Contracts.IStreamStats", true)] public interface IVorbisStreamStatus : IStreamStats { [Obsolete("No longer supported.", true)] TimeSpan PageLatency { get; } [Obsolete("No longer supported.", true)] TimeSpan PacketLatency { get; } [Obsolete("No longer supported.", true)] TimeSpan SecondLatency { get; } [Obsolete("No longer supported.", true)] int PagesRead { get; } [Obsolete("No longer supported.", true)] int TotalPages { get; } [Obsolete("Use IStreamDecoder.HasClipped instead. VorbisReader.HasClipped will return the same value for the stream it is handling.", true)] bool Clipped { get; } } internal class Mapping : IMapping { private IMdct _mdct; private int[] _couplingAngle; private int[] _couplingMangitude; private IFloor[] _submapFloor; private IResidue[] _submapResidue; private IFloor[] _channelFloor; private IResidue[] _channelResidue; public void Init(IPacket packet, int channels, IFloor[] floors, IResidue[] residues, IMdct mdct) { int num = 1; if (packet.ReadBit()) { num += (int)packet.ReadBits(4); } int num2 = 0; if (packet.ReadBit()) { num2 = (int)packet.ReadBits(8) + 1; } int count = Utils.ilog(channels - 1); _couplingAngle = new int[num2]; _couplingMangitude = new int[num2]; for (int i = 0; i < num2; i++) { int num3 = (int)packet.ReadBits(count); int num4 = (int)packet.ReadBits(count); if (num3 == num4 || num3 > channels - 1 || num4 > channels - 1) { throw new InvalidDataException("Invalid magnitude or angle in mapping header!"); } _couplingAngle[i] = num4; _couplingMangitude[i] = num3; } if (packet.ReadBits(2) != 0L) { throw new InvalidDataException("Reserved bits not 0 in mapping header."); } int[] array = new int[channels]; if (num > 1) { for (int j = 0; j < channels; j++) { array[j] = (int)packet.ReadBits(4); if (array[j] > num) { throw new InvalidDataException("Invalid channel mux submap index in mapping header!"); } } } _submapFloor = new IFloor[num]; _submapResidue = new IResidue[num]; for (int k = 0; k < num; k++) { packet.SkipBits(8); int num5 = (int)packet.ReadBits(8); if (num5 >= floors.Length) { throw new InvalidDataException("Invalid floor number in mapping header!"); } int num6 = (int)packet.ReadBits(8); if (num6 >= residues.Length) { throw new InvalidDataException("Invalid residue number in mapping header!"); } _submapFloor[k] = floors[num5]; _submapResidue[k] = residues[num6]; } _channelFloor = new IFloor[channels]; _channelResidue = new IResidue[channels]; for (int l = 0; l < channels; l++) { _channelFloor[l] = _submapFloor[array[l]]; _channelResidue[l] = _submapResidue[array[l]]; } _mdct = mdct; } public void DecodePacket(IPacket packet, int blockSize, int channels, float[][] buffer) { int num = blockSize >> 1; IFloorData[] array = new IFloorData[_channelFloor.Length]; bool[] array2 = new bool[_channelFloor.Length]; for (int i = 0; i < _channelFloor.Length; i++) { array[i] = _channelFloor[i].Unpack(packet, blockSize, i); array2[i] = !array[i].ExecuteChannel; Array.Clear(buffer[i], 0, num); } for (int j = 0; j < _couplingAngle.Length; j++) { if (array[_couplingAngle[j]].ExecuteChannel || array[_couplingMangitude[j]].ExecuteChannel) { array[_couplingAngle[j]].ForceEnergy = true; array[_couplingMangitude[j]].ForceEnergy = true; } } for (int k = 0; k < _submapFloor.Length; k++) { for (int l = 0; l < _channelFloor.Length; l++) { if (_submapFloor[k] != _channelFloor[l] || _submapResidue[k] != _channelResidue[l]) { array[l].ForceNoEnergy = true; } } _submapResidue[k].Decode(packet, array2, blockSize, buffer); } for (int num2 = _couplingAngle.Length - 1; num2 >= 0; num2--) { if (array[_couplingAngle[num2]].ExecuteChannel || array[_couplingMangitude[num2]].ExecuteChannel) { float[] array3 = buffer[_couplingMangitude[num2]]; float[] array4 = buffer[_couplingAngle[num2]]; for (int m = 0; m < num; m++) { float num3 = array3[m]; float num4 = array4[m]; float num5; float num6; if (num3 > 0f) { if (num4 > 0f) { num5 = num3; num6 = num3 - num4; } else { num6 = num3; num5 = num3 + num4; } } else if (num4 > 0f) { num5 = num3; num6 = num3 + num4; } else { num6 = num3; num5 = num3 - num4; } array3[m] = num5; array4[m] = num6; } } } for (int n = 0; n < _channelFloor.Length; n++) { if (array[n].ExecuteChannel) { _channelFloor[n].Apply(array[n], blockSize, buffer[n]); _mdct.Reverse(buffer[n], blockSize); } else { Array.Clear(buffer[n], num, num); } } } } internal class Mdct : IMdct { private class MdctImpl { private readonly int _n; private readonly int _n2; private readonly int _n4; private readonly int _n8; private readonly int _ld; private readonly float[] _a; private readonly float[] _b; private readonly float[] _c; private readonly ushort[] _bitrev; public MdctImpl(int n) { _n = n; _n2 = n >> 1; _n4 = _n2 >> 1; _n8 = _n4 >> 1; _ld = Utils.ilog(n) - 1; _a = new float[_n2]; _b = new float[_n2]; _c = new float[_n4]; int num; int num2 = (num = 0); while (num2 < _n4) { _a[num] = (float)Math.Cos((float)(4 * num2) * (float)Math.PI / (float)n); _a[num + 1] = (float)(0.0 - Math.Sin((float)(4 * num2) * (float)Math.PI / (float)n)); _b[num] = (float)Math.Cos((float)(num + 1) * (float)Math.PI / (float)n / 2f) * 0.5f; _b[num + 1] = (float)Math.Sin((float)(num + 1) * (float)Math.PI / (float)n / 2f) * 0.5f; num2++; num += 2; } num2 = (num = 0); while (num2 < _n8) { _c[num] = (float)Math.Cos((float)(2 * (num + 1)) * (float)Math.PI / (float)n); _c[num + 1] = (float)(0.0 - Math.Sin((float)(2 * (num + 1)) * (float)Math.PI / (float)n)); num2++; num += 2; } _bitrev = new ushort[_n8]; for (int i = 0; i < _n8; i++) { _bitrev[i] = (ushort)(Utils.BitReverse((uint)i, _ld - 3) << 2); } } internal void CalcReverse(float[] buffer) { float[] array = new float[_n2]; int num = _n2 - 2; int num2 = 0; int i = 0; for (int n = _n2; i != n; i += 4) { array[num + 1] = buffer[i] * _a[num2] - buffer[i + 2] * _a[num2 + 1]; array[num] = buffer[i] * _a[num2 + 1] + buffer[i + 2] * _a[num2]; num -= 2; num2 += 2; } i = _n2 - 3; while (num >= 0) { array[num + 1] = (0f - buffer[i + 2]) * _a[num2] - (0f - buffer[i]) * _a[num2 + 1]; array[num] = (0f - buffer[i + 2]) * _a[num2 + 1] + (0f - buffer[i]) * _a[num2]; num -= 2; num2 += 2; i -= 4; } float[] array2 = array; int num3 = _n2 - 8; int num4 = _n4; int num5 = 0; int num6 = _n4; int num7 = 0; while (num3 >= 0) { float num8 = array2[num4 + 1] - array2[num5 + 1]; float num9 = array2[num4] - array2[num5]; buffer[num6 + 1] = array2[num4 + 1] + array2[num5 + 1]; buffer[num6] = array2[num4] + array2[num5]; buffer[num7 + 1] = num8 * _a[num3 + 4] - num9 * _a[num3 + 5]; buffer[num7] = num9 * _a[num3 + 4] + num8 * _a[num3 + 5]; num8 = array2[num4 + 3] - array2[num5 + 3]; num9 = array2[num4 + 2] - array2[num5 + 2]; buffer[num6 + 3] = array2[num4 + 3] + array2[num5 + 3]; buffer[num6 + 2] = array2[num4 + 2] + array2[num5 + 2]; buffer[num7 + 3] = num8 * _a[num3] - num9 * _a[num3 + 1]; buffer[num7 + 2] = num9 * _a[num3] + num8 * _a[num3 + 1]; num3 -= 8; num6 += 4; num7 += 4; num4 += 4; num5 += 4; } int n2 = _n >> 4; int num10 = _n2 - 1; _ = _n4; step3_iter0_loop(n2, buffer, num10 - 0, -_n8); step3_iter0_loop(_n >> 4, buffer, _n2 - 1 - _n4, -_n8); int lim = _n >> 5; int num11 = _n2 - 1; _ = _n8; step3_inner_r_loop(lim, buffer, num11 - 0, -(_n >> 4), 16); step3_inner_r_loop(_n >> 5, buffer, _n2 - 1 - _n8, -(_n >> 4), 16); step3_inner_r_loop(_n >> 5, buffer, _n2 - 1 - _n8 * 2, -(_n >> 4), 16); step3_inner_r_loop(_n >> 5, buffer, _n2 - 1 - _n8 * 3, -(_n >> 4), 16); int j; for (j = 2; j < _ld - 3 >> 1; j++) { int num12 = _n >> j + 2; int num13 = num12 >> 1; int num14 = 1 << j + 1; for (int k = 0; k < num14; k++) { step3_inner_r_loop(_n >> j + 4, buffer, _n2 - 1 - num12 * k, -num13, 1 << j + 3); } } for (; j < _ld - 6; j++) { int num15 = _n >> j + 2; int num16 = 1 << j + 3; int num17 = num15 >> 1; int num18 = _n >> j + 6; int n3 = 1 << j + 1; int num19 = _n2 - 1; int num20 = 0; for (int num21 = num18; num21 > 0; num21--) { step3_inner_s_loop(n3, buffer, num19, -num17, num20, num16, num15); num20 += num16 * 4; num19 -= 8; } } step3_inner_s_loop_ld654(_n >> 5, buffer, _n2 - 1, _n); int num22 = 0; int num23 = _n4 - 4; int num24 = _n2 - 4; while (num23 >= 0) { int num25 = _bitrev[num22]; array2[num24 + 3] = buffer[num25]; array2[num24 + 2] = buffer[num25 + 1]; array2[num23 + 3] = buffer[num25 + 2]; array2[num23 + 2] = buffer[num25 + 3]; num25 = _bitrev[num22 + 1]; array2[num24 + 1] = buffer[num25]; array2[num24] = buffer[num25 + 1]; array2[num23 + 1] = buffer[num25 + 2]; array2[num23] = buffer[num25 + 3]; num23 -= 4; num24 -= 4; num22 += 2; } int num26 = 0; int num27 = 0; int num28 = _n2 - 4; while (num27 < num28) { float num29 = array2[num27] - array2[num28 + 2]; float num30 = array2[num27 + 1] + array2[num28 + 3]; float num31 = _c[num26 + 1] * num29 + _c[num26] * num30; float num32 = _c[num26 + 1] * num30 - _c[num26] * num29; float num33 = array2[num27] + array2[num28 + 2]; float num34 = array2[num27 + 1] - array2[num28 + 3]; array2[num27] = num33 + num31; array2[num27 + 1] = num34 + num32; array2[num28 + 2] = num33 - num31; array2[num28 + 3] = num32 - num34; num29 = array2[num27 + 2] - array2[num28]; num30 = array2[num27 + 3] + array2[num28 + 1]; num31 = _c[num26 + 3] * num29 + _c[num26 + 2] * num30; num32 = _c[num26 + 3] * num30 - _c[num26 + 2] * num29; num33 = array2[num27 + 2] + array2[num28]; num34 = array2[num27 + 3] - array2[num28 + 1]; array2[num27 + 2] = num33 + num31; array2[num27 + 3] = num34 + num32; array2[num28] = num33 - num31; array2[num28 + 1] = num32 - num34; num26 += 4; num27 += 4; num28 -= 4; } int num35 = _n2 - 8; int num36 = _n2 - 8; int num37 = 0; int num38 = _n2 - 4; int num39 = _n2; int num40 = _n - 4; while (num36 >= 0) { float num41 = array[num36 + 6] * _b[num35 + 7] - array[num36 + 7] * _b[num35 + 6]; float num42 = (0f - array[num36 + 6]) * _b[num35 + 6] - array[num36 + 7] * _b[num35 + 7]; buffer[num37] = num41; buffer[num38 + 3] = 0f - num41; buffer[num39] = num42; buffer[num40 + 3] = num42; float num43 = array[num36 + 4] * _b[num35 + 5] - array[num36 + 5] * _b[num35 + 4]; float num44 = (0f - array[num36 + 4]) * _b[num35 + 4] - array[num36 + 5] * _b[num35 + 5]; buffer[num37 + 1] = num43; buffer[num38 + 2] = 0f - num43; buffer[num39 + 1] = num44; buffer[num40 + 2] = num44; num41 = array[num36 + 2] * _b[num35 + 3] - array[num36 + 3] * _b[num35 + 2]; num42 = (0f - array[num36 + 2]) * _b[num35 + 2] - array[num36 + 3] * _b[num35 + 3]; buffer[num37 + 2] = num41; buffer[num38 + 1] = 0f - num41; buffer[num39 + 2] = num42; buffer[num40 + 1] = num42; num43 = array[num36] * _b[num35 + 1] - array[num36 + 1] * _b[num35]; num44 = (0f - array[num36]) * _b[num35] - array[num36 + 1] * _b[num35 + 1]; buffer[num37 + 3] = num43; buffer[num38] = 0f - num43; buffer[num39 + 3] = num44; buffer[num40] = num44; num35 -= 8; num36 -= 8; num37 += 4; num39 += 4; num38 -= 4; num40 -= 4; } } private void step3_iter0_loop(int n, float[] e, int i_off, int k_off) { int num = i_off; int num2 = num + k_off; int num3 = 0; for (int num4 = n >> 2; num4 > 0; num4--) { float num5 = e[num] - e[num2]; float num6 = e[num - 1] - e[num2 - 1]; e[num] += e[num2]; e[num - 1] += e[num2 - 1]; e[num2] = num5 * _a[num3] - num6 * _a[num3 + 1]; e[num2 - 1] = num6 * _a[num3] + num5 * _a[num3 + 1]; num3 += 8; num5 = e[num - 2] - e[num2 - 2]; num6 = e[num - 3] - e[num2 - 3]; e[num - 2] += e[num2 - 2]; e[num - 3] += e[num2 - 3]; e[num2 - 2] = num5 * _a[num3] - num6 * _a[num3 + 1]; e[num2 - 3] = num6 * _a[num3] + num5 * _a[num3 + 1]; num3 += 8; num5 = e[num - 4] - e[num2 - 4]; num6 = e[num - 5] - e[num2 - 5]; e[num - 4] += e[num2 - 4]; e[num - 5] += e[num2 - 5]; e[num2 - 4] = num5 * _a[num3] - num6 * _a[num3 + 1]; e[num2 - 5] = num6 * _a[num3] + num5 * _a[num3 + 1]; num3 += 8; num5 = e[num - 6] - e[num2 - 6]; num6 = e[num - 7] - e[num2 - 7]; e[num - 6] += e[num2 - 6]; e[num - 7] += e[num2 - 7]; e[num2 - 6] = num5 * _a[num3] - num6 * _a[num3 + 1]; e[num2 - 7] = num6 * _a[num3] + num5 * _a[num3 + 1]; num3 += 8; num -= 8; num2 -= 8; } } private void step3_inner_r_loop(int lim, float[] e, int d0, int k_off, int k1) { int num = d0; int num2 = num + k_off; int num3 = 0; for (int num4 = lim >> 2; num4 > 0; num4--) { float num5 = e[num] - e[num2]; float num6 = e[num - 1] - e[num2 - 1]; e[num] += e[num2]; e[num - 1] += e[num2 - 1]; e[num2] = num5 * _a[num3] - num6 * _a[num3 + 1]; e[num2 - 1] = num6 * _a[num3] + num5 * _a[num3 + 1]; num3 += k1; num5 = e[num - 2] - e[num2 - 2]; num6 = e[num - 3] - e[num2 - 3]; e[num - 2] += e[num2 - 2]; e[num - 3] += e[num2 - 3]; e[num2 - 2] = num5 * _a[num3] - num6 * _a[num3 + 1]; e[num2 - 3] = num6 * _a[num3] + num5 * _a[num3 + 1]; num3 += k1; num5 = e[num - 4] - e[num2 - 4]; num6 = e[num - 5] - e[num2 - 5]; e[num - 4] += e[num2 - 4]; e[num - 5] += e[num2 - 5]; e[num2 - 4] = num5 * _a[num3] - num6 * _a[num3 + 1]; e[num2 - 5] = num6 * _a[num3] + num5 * _a[num3 + 1]; num3 += k1; num5 = e[num - 6] - e[num2 - 6]; num6 = e[num - 7] - e[num2 - 7]; e[num - 6] += e[num2 - 6]; e[num - 7] += e[num2 - 7]; e[num2 - 6] = num5 * _a[num3] - num6 * _a[num3 + 1]; e[num2 - 7] = num6 * _a[num3] + num5 * _a[num3 + 1]; num3 += k1; num -= 8; num2 -= 8; } } private void step3_inner_s_loop(int n, float[] e, int i_off, int k_off, int a, int a_off, int k0) { float num = _a[a]; float num2 = _a[a + 1]; float num3 = _a[a + a_off]; float num4 = _a[a + a_off + 1]; float num5 = _a[a + a_off * 2]; float num6 = _a[a + a_off * 2 + 1]; float num7 = _a[a + a_off * 3]; float num8 = _a[a + a_off * 3 + 1]; int num9 = i_off; int num10 = num9 + k_off; for (int num11 = n; num11 > 0; num11--) { float num12 = e[num9] - e[num10]; float num13 = e[num9 - 1] - e[num10 - 1]; e[num9] += e[num10]; e[num9 - 1] += e[num10 - 1]; e[num10] = num12 * num - num13 * num2; e[num10 - 1] = num13 * num + num12 * num2; num12 = e[num9 - 2] - e[num10 - 2]; num13 = e[num9 - 3] - e[num10 - 3]; e[num9 - 2] += e[num10 - 2]; e[num9 - 3] += e[num10 - 3]; e[num10 - 2] = num12 * num3 - num13 * num4; e[num10 - 3] = num13 * num3 + num12 * num4; num12 = e[num9 - 4] - e[num10 - 4]; num13 = e[num9 - 5] - e[num10 - 5]; e[num9 - 4] += e[num10 - 4]; e[num9 - 5] += e[num10 - 5]; e[num10 - 4] = num12 * num5 - num13 * num6; e[num10 - 5] = num13 * num5 + num12 * num6; num12 = e[num9 - 6] - e[num10 - 6]; num13 = e[num9 - 7] - e[num10 - 7]; e[num9 - 6] += e[num10 - 6]; e[num9 - 7] += e[num10 - 7]; e[num10 - 6] = num12 * num7 - num13 * num8; e[num10 - 7] = num13 * num7 + num12 * num8; num9 -= k0; num10 -= k0; } } private void step3_inner_s_loop_ld654(int n, float[] e, int i_off, int base_n) { int num = base_n >> 3; float num2 = _a[num]; int num3 = i_off; int num4 = num3 - 16 * n; while (num3 > num4) { float num5 = e[num3] - e[num3 - 8]; float num6 = e[num3 - 1] - e[num3 - 9]; e[num3] += e[num3 - 8]; e[num3 - 1] += e[num3 - 9]; e[num3 - 8] = num5; e[num3 - 9] = num6; num5 = e[num3 - 2] - e[num3 - 10]; num6 = e[num3 - 3] - e[num3 - 11]; e[num3 - 2] += e[num3 - 10]; e[num3 - 3] += e[num3 - 11]; e[num3 - 10] = (num5 + num6) * num2; e[num3 - 11] = (num6 - num5) * num2; num5 = e[num3 - 12] - e[num3 - 4]; num6 = e[num3 - 5] - e[num3 - 13]; e[num3 - 4] += e[num3 - 12]; e[num3 - 5] += e[num3 - 13]; e[num3 - 12] = num6; e[num3 - 13] = num5; num5 = e[num3 - 14] - e[num3 - 6]; num6 = e[num3 - 7] - e[num3 - 15]; e[num3 - 6] += e[num3 - 14]; e[num3 - 7] += e[num3 - 15]; e[num3 - 14] = (num5 + num6) * num2; e[num3 - 15] = (num5 - num6) * num2; iter_54(e, num3); iter_54(e, num3 - 8); num3 -= 16; } } private void iter_54(float[] e, int z) { float num = e[z] - e[z - 4]; float num2 = e[z] + e[z - 4]; float num3 = e[z - 2] + e[z - 6]; float num4 = e[z - 2] - e[z - 6]; e[z] = num2 + num3; e[z - 2] = num2 - num3; float num5 = e[z - 3] - e[z - 7]; e[z - 4] = num + num5; e[z - 6] = num - num5; float num6 = e[z - 1] - e[z - 5]; float num7 = e[z - 1] + e[z - 5]; float num8 = e[z - 3] + e[z - 7]; e[z - 1] = num7 + num8; e[z - 3] = num7 - num8; e[z - 5] = num6 - num4; e[z - 7] = num6 + num4; } } private const float M_PI = (float)Math.PI; private Dictionary<int, MdctImpl> _setupCache = new Dictionary<int, MdctImpl>(); public void Reverse(float[] samples, int sampleCount) { if (!_setupCache.TryGetValue(sampleCount, out var value)) { value = new MdctImpl(sampleCount); _setupCache[sampleCount] = value; } value.CalcReverse(samples); } } internal class Mode : IMode { private struct OverlapInfo { public int PacketStartIndex; public int PacketTotalLength; public int PacketValidLength; } private const float M_PI2 = (float)Math.PI / 2f; private int _channels; private bool _blockFlag; private int _blockSize; private IMapping _mapping; private float[][] _windows; private OverlapInfo[] _overlapInfo; public void Init(IPacket packet, int channels, int block0Size, int block1Size, IMapping[] mappings) { _channels = channels; _blockFlag = packet.ReadBit(); if (packet.ReadBits(32) != 0L) { throw new InvalidDataException("Mode header had invalid window or transform type!"); } int num = (int)packet.ReadBits(8); if (num >= mappings.Length) { throw new InvalidDataException("Mode header had invalid mapping index!"); } _mapping = mappings[num]; if (_blockFlag) { _blockSize = block1Size; _windows = new float[4][] { CalcWindow(block0Size, block1Size, block0Size), CalcWindow(block1Size, block1Size, block0Size), CalcWindow(block0Size, block1Size, block1Size), CalcWindow(block1Size, block1Size, block1Size) }; _overlapInfo = new OverlapInfo[4] { CalcOverlap(block0Size, block1Size, block0Size), CalcOverlap(block1Size, block1Size, block0Size), CalcOverlap(block0Size, block1Size, block1Size), CalcOverlap(block1Size, block1Size, block1Size) }; } else { _blockSize = block0Size; _windows = new float[1][] { CalcWindow(block0Size, block0Size, block0Size) }; } } private static float[] CalcWindow(int prevBlockSize, int blockSize, int nextBlockSize) { float[] array = new float[blockSize]; int num = prevBlockSize / 2; int num2 = nextBlockSize / 2; int num3 = blockSize / 4 - num / 2; int num4 = blockSize - blockSize / 4 - num2 / 2; for (int i = 0; i < num; i++) { float num5 = (float)Math.Sin(((double)i + 0.5) / (double)num * 1.5707963705062866); num5 *= num5; array[num3 + i] = (float)Math.Sin(num5 * ((float)Math.PI / 2f)); } for (int j = num3 + num; j < num4; j++) { array[j] = 1f; } for (int k = 0; k < num2; k++) { float num6 = (float)Math.Sin(((double)(num2 - k) - 0.5) / (double)num2 * 1.5707963705062866); num6 *= num6; array[num4 + k] = (float)Math.Sin(num6 * ((float)Math.PI / 2f)); } return array; } private static OverlapInfo CalcOverlap(int prevBlockSize, int blockSize, int nextBlockSize) { int num = prevBlockSize / 4; int num2 = nextBlockSize / 4; int packetStartIndex = blockSize / 4 - num; int num3 = blockSize / 4 * 3 + num2; int packetValidLength = num3 - num2 * 2; OverlapInfo result = default(OverlapInfo); result.PacketStartIndex = packetStartIndex; result.PacketValidLength = packetValidLength; result.PacketTotalLength = num3; return result; } private bool GetPacketInfo(IPacket packet, out int windowIndex, out int packetStartIndex, out int packetValidLength, out int packetTotalLength) { if (packet.IsShort) { windowIndex = 0; packetStartIndex = 0; packetValidLength = 0; packetTotalLength = 0; return false; } if (_blockFlag) { bool flag = packet.ReadBit(); bool flag2 = packet.ReadBit(); windowIndex = (flag ? 1 : 0) + (flag2 ? 2 : 0); OverlapInfo overlapInfo = _overlapInfo[windowIndex]; packetStartIndex = overlapInfo.PacketStartIndex; packetValidLength = overlapInfo.PacketValidLength; packetTotalLength = overlapInfo.PacketTotalLength; } else { windowIndex = 0; packetStartIndex = 0; packetValidLength = _blockSize / 2; packetTotalLength = _blockSize; } return true; } public bool Decode(IPacket packet, float[][] buffer, out int packetStartindex, out int packetValidLength, out int packetTotalLength) { if (GetPacketInfo(packet, out var windowIndex, out packetStartindex, out packetValidLength, out packetTotalLength)) { _mapping.DecodePacket(packet, _blockSize, _channels, buffer); float[] array = _windows[windowIndex]; for (int i = 0; i < _blockSize; i++) { for (int j = 0; j < _channels; j++) { buffer[j][i] *= array[i]; } } return true; } return false; } public int GetPacketSampleCount(IPacket packet) { GetPacketInfo(packet, out var _, out var packetStartIndex, out var packetValidLength, out var _); return packetValidLength - packetStartIndex; } } [Serializable] public class NewStreamEventArgs : EventArgs { public IStreamDecoder StreamDecoder { get; } public bool IgnoreStream { get; set; } public NewStreamEventArgs(IStreamDecoder streamDecoder) { StreamDecoder = streamDecoder ?? throw new ArgumentNullException("streamDecoder"); } } internal class Residue0 : IResidue { private int _channels; private int _begin; private int _end; private int _partitionSize; private int _classifications; private int _maxStages; private ICodebook[][] _books; private ICodebook _classBook; private int[] _cascade; private int[][] _decodeMap; private static int icount(int v) { int num = 0; while (v != 0) { num += v & 1; v >>= 1; } return num; } public virtual void Init(IPacket packet, int channels, ICodebook[] codebooks) { _begin = (int)packet.ReadBits(24); _end = (int)packet.ReadBits(24); _partitionSize = (int)packet.ReadBits(24) + 1; _classifications = (int)packet.ReadBits(6) + 1; _classBook = codebooks[(uint)packet.ReadBits(8)]; _cascade = new int[_classifications]; int num = 0; for (int i = 0; i < _classifications; i++) { int num2 = (int)packet.ReadBits(3); if (packet.ReadBit()) { _cascade[i] = ((int)packet.ReadBits(5) << 3) | num2; } else { _cascade[i] = num2; } num += icount(_cascade[i]); } int[] array = new int[num]; for (int j = 0; j < num; j++) { array[j] = (int)packet.ReadBits(8); if (codebooks[array[j]].MapType == 0) { throw new InvalidDataException(); } } int entries = _classBook.Entries; int num3 = _classBook.Dimensions; int num4 = 1; while (num3 > 0) { num4 *= _classifications; if (num4 > entries) { throw new InvalidDataException(); } num3--; } _books = new ICodebook[_classifications][]; num = 0; int num5 = 0; for (int k = 0; k < _classifications; k++) { int num6 = Utils.ilog(_cascade[k]); _books[k] = new ICodebook[num6]; if (num6 <= 0) { continue; } num5 = Math.Max(num5, num6); for (int l = 0; l < num6; l++) { if ((_cascade[k] & (1 << l)) > 0) { _books[k][l] = codebooks[array[num++]]; } } } _maxStages = num5; _decodeMap = new int[num4][]; for (int m = 0; m < num4; m++) { int num7 = m; int num8 = num4 / _classifications; _decodeMap[m] = new int[_classBook.Dimensions]; for (int n = 0; n < _classBook.Dimensions; n++) { int num9 = num7 / num8; num7 -= num9 * num8; num8 /= _classifications; _decodeMap[m][n] = num9; } } _channels = channels; } public virtual void Decode(IPacket packet, bool[] doNotDecodeChannel, int blockSize, float[][] buffer) { int num = ((_end < blockSize / 2) ? _end : (blockSize / 2)) - _begin; if (num <= 0 || Array.IndexOf(doNotDecodeChannel, value: false) == -1) { return; } int num2 = num / _partitionSize; int num3 = (num2 + _classBook.Dimensions - 1) / _classBook.Dimensions; int[,][] array = new int[_channels, num3][]; for (int i = 0; i < _maxStages; i++) { int j = 0; int num4 = 0; while (j < num2) { if (i == 0) { for (int k = 0; k < _channels; k++) { int num5 = _classBook.DecodeScalar(packet); if (num5 >= 0 && num5 < _decodeMap.Length) { array[k, num4] = _decodeMap[num5]; continue; } j = num2; i = _maxStages; break; } } int num6 = 0; for (; j < num2; j++) { if (num6 >= _classBook.Dimensions) { break; } int offset = _begin + j * _partitionSize; for (int l = 0; l < _channels; l++) { int num7 = array[l, num4][num6]; if ((_cascade[num7] & (1 << i)) != 0) { ICodebook codebook = _books[num7][i]; if (codebook != null && WriteVectors(codebook, packet, buffer, l, offset, _partitionSize)) { j = num2; i = _maxStages; break; } } } num6++; } num4++; } } } protected virtual bool WriteVectors(ICodebook codebook, IPacket packet, float[][] residue, int channel, int offset, int partitionSize) { float[] array = residue[channel]; int num = partitionSize / codebook.Dimensions; int[] array2 = new int[num]; for (int i = 0; i < num; i++) { if ((array2[i] = codebook.DecodeScalar(packet)) == -1) { return true; } } for (int j = 0; j < codebook.Dimensions; j++) { int num2 = 0; while (num2 < num) { array[offset] += codebook[array2[num2], j]; num2++; offset++; } } return false; } } internal class Residue1 : Residue0 { protected override bool WriteVectors(ICodebook codebook, IPacket packet, float[][] residue, int channel, int offset, int partitionSize) { float[] array = residue[channel]; int num = 0; while (num < partitionSize) { int num2 = codebook.DecodeScalar(packet); if (num2 == -1) { return true; } for (int i = 0; i < codebook.Dimensions; i++) { array[offset + num] += codebook[num2, i]; num++; } } return false; } } internal class Residue2 : Residue0 { private int _channels; public override void Init(IPacket packet, int channels, ICodebook[] codebooks) { _channels = channels; base.Init(packet, 1, codebooks); } public override void Decode(IPacket packet, bool[] doNotDecodeChannel, int blockSize, float[][] buffer) { base.Decode(packet, doNotDecodeChannel, blockSize * _channels, buffer); } protected override bool WriteVectors(ICodebook codebook, IPacket packet, float[][] residue, int channel, int offset, int partitionSize) { int num = 0; offset /= _channels; int num2 = 0; while (num2 < partitionSize) { int num3 = codebook.DecodeScalar(packet); if (num3 == -1) { return true; } int num4 = 0; while (num4 < codebook.Dimensions) { residue[num][offset] += codebook[num3, num4]; if (++num == _channels) { num = 0; offset++; } num4++; num2++; } } return false; } } public sealed class StreamDecoder : IStreamDecoder, IDisposable { private NVorbis.Contracts.IPacketProvider _packetProvider; private IFactory _factory; private StreamStats _stats; private byte _channels; private int _sampleRate; private int _block0Size; private int _block1Size; private IMode[] _modes; private int _modeFieldBits; private string _vendor; private string[] _comments; private ITagData _tags; private long _currentPosition; private bool _hasClipped; private bool _hasPosition; private bool _eosFound; private float[][] _nextPacketBuf; private float[][] _prevPacketBuf; private int _prevPacketStart; private int _prevPacketEnd; private int _prevPacketStop; private static readonly byte[] PacketSignatureStream = new byte[11] { 1, 118, 111, 114, 98, 105, 115, 0, 0, 0, 0 }; private static readonly byte[] PacketSignatureComments = new byte[7] { 3, 118, 111, 114, 98, 105, 115 }; private static readonly byte[] PacketSignatureBooks = new byte[7] { 5, 118, 111, 114, 98, 105, 115 }; internal static Func<IFactory> CreateFactory { get; set; } = () => new Factory(); public int Channels => _channels; public int SampleRate => _sampleRate; public int UpperBitrate { get; private set; } public int NominalBitrate { get; private set; } public int LowerBitrate { get; private set; } public ITagData Tags => _tags ?? (_tags = new TagData(_vendor, _comments)); public TimeSpan TotalTime => TimeSpan.FromSeconds((double)TotalSamples / (double)_sampleRate); public long TotalSamples => (_packetProvider ?? throw new ObjectDisposedException("StreamDecoder")).GetGranuleCount(); public TimeSpan TimePosition { get { return TimeSpan.FromSeconds((double)_currentPosition / (double)_sampleRate); } set { SeekTo(value); } } public long SamplePosition { get { return _currentPosition; } set { SeekTo(value); } } public bool ClipSamples { get; set; } public bool HasClipped => _hasClipped; public bool IsEndOfStream { get { if (_eosFound) { return _prevPacketBuf == null; } return false; } } public IStreamStats Stats => _stats; public StreamDecoder(NVorbis.Contracts.IPacketProvider packetProvider) : this(packetProvider, new Factory()) { } internal StreamDecoder(NVorbis.Contracts.IPacketProvider packetProvider, IFactory factory) { _packetProvider = packetProvider ?? throw new ArgumentNullException("packetProvider"); _factory = factory ?? throw new ArgumentNullException("factory"); _stats = new StreamStats(); _currentPosition = 0L; ClipSamples = true; IPacket packet = _packetProvider.PeekNextPacket(); if (!ProcessHeaderPackets(packet)) { _packetProvider = null; packet.Reset(); throw GetInvalidStreamException(packet); } } private static Exception GetInvalidStreamException(IPacket packet) { try { ulong num = packet.ReadBits(64); if (num == 7233173838382854223L) { return new ArgumentException("Found OPUS bitstream."); } if ((num & 0xFF) == 127) { return new ArgumentException("Found FLAC bitstream."); } switch (num) { case 2314885909937746003uL: return new ArgumentException("Found Speex bitstream."); case 28254585843050854uL: return new ArgumentException("Found Skeleton metadata bitstream."); default: if ((num & 0xFFFFFFFFFFFF00L) == 27428895509214208L) { return new ArgumentException("Found Theora bitsream."); } return new ArgumentException("Could not find Vorbis data to decode."); } } finally { packet.Reset(); } } private bool ProcessHeaderPackets(IPacket packet) { if (!ProcessHeaderPacket(packet, LoadStreamHeader, delegate { _packetProvider.GetNextPacket().Done(); })) { return false; } if (!ProcessHeaderPacket(_packetProvider.GetNextPacket(), LoadComments, delegate(IPacket pkt) { pkt.Done(); })) { return false; } if (!ProcessHeaderPacket(_packetProvider.GetNextPacket(), LoadBooks, delegate(IPacket pkt) { pkt.Done(); })) { return false; } _currentPosition = 0L; ResetDecoder(); return true; } private static bool ProcessHeaderPacket(IPacket packet, Func<IPacket, bool> processAction, Action<IPacket> doneAction) { if (packet != null) { try { return processAction(packet); } finally { doneAction(packet); } } return false; } private static bool ValidateHeader(IPacket packet, byte[] expected) { for (int i = 0; i < expected.Length; i++) { if (expected[i] != packet.ReadBits(8)) { return false; } } return true; } private static string ReadString(IPacket packet) { int num = (int)packet.ReadBits(32); if (num == 0) { return string.Empty; } byte[] array = new byte[num]; if (packet.Read(array, 0, num) < num) { throw new InvalidDataException("Could not read full string!"); } return Encoding.UTF8.GetString(array); } private bool LoadStreamHeader(IPacket packet) { if (!ValidateHeader(packet, PacketSignatureStream)) { return false; } _channels = (byte)packet.ReadBits(8); _sampleRate = (int)packet.ReadBits(32); UpperBitrate = (int)packet.ReadBits(32); NominalBitrate = (int)packet.ReadBits(32); LowerBitrate = (int)packet.ReadBits(32); _block0Size = 1 << (int)packet.ReadBits(4); _block1Size = 1 << (int)packet.ReadBits(4); if (NominalBitrate == 0 && UpperBitrate > 0 && LowerBitrate > 0) { NominalBitrate = (UpperBitrate + LowerBitrate) / 2; } _stats.SetSampleRate(_sampleRate); _stats.AddPacket(-1, packet.BitsRead, packet.BitsRemaining, packet.ContainerOverheadBits); return true; } private bool LoadComments(IPacket packet) { if (!ValidateHeader(packet, PacketSignatureComments)) { return false; } _vendor = ReadString(packet); _comments = new string[packet.ReadBits(32)]; for (int i = 0; i < _comments.Length; i++) { _comments[i] = ReadString(packet); } _stats.AddPacket(-1, packet.BitsRead, packet.BitsRemaining, packet.ContainerOverheadBits); return true; } private bool LoadBooks(IPacket packet) { if (!ValidateHeader(packet, PacketSignatureBooks)) { return false; } IMdct mdct = _factory.CreateMdct(); IHuffman huffman = _factory.CreateHuffman(); ICodebook[] array = new ICodebook[packet.ReadBits(8) + 1]; for (int i = 0; i < array.Length; i++) { array[i] = _factory.CreateCodebook(); array[i].Init(packet, huffman); } int num = (int)packet.ReadBits(6) + 1; packet.SkipBits(16 * num); IFloor[] array2 = new IFloor[packet.ReadBits(6) + 1]; for (int j = 0; j < array2.Length; j++) { array2[j] = _factory.CreateFloor(packet); array2[j].Init(packet, _channels, _block0Size, _block1Size, array); } IResidue[] array3 = new IResidue[packet.ReadBits(6) + 1]; for (int k = 0; k < array3.Length; k++) { array3[k] = _factory.CreateResidue(packet); array3[k].Init(packet, _channels, array); } IMapping[] array4 = new IMapping[packet.ReadBits(6) + 1]; for (int l = 0; l < array4.Length; l++) { array4[l] = _factory.CreateMapping(packet); array4[l].Init(packet, _channels, array2, array3, mdct); } _modes = new IMode[packet.ReadBits(6) + 1]; for (int m = 0; m < _modes.Length; m++) { _modes[m] = _factory.CreateMode(); _modes[m].Init(packet, _channels, _block0Size, _block1Size, array4); } if (!packet.ReadBit()) { throw new InvalidDataException("Book packet did not end on correct bit!"); } _modeFieldBits = Utils.ilog(_modes.Length - 1); _stats.AddPacket(-1, packet.BitsRead, packet.BitsRemaining, packet.ContainerOverheadBits); return true; } private void ResetDecoder() { _prevPacketBuf = null; _prevPacketStart = 0; _prevPacketEnd = 0; _prevPacketStop = 0; _nextPacketBuf = null; _eosFound = false; _hasClipped = false; _hasPosition = false; } public int Read(Span<float> buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset + count > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count % _channels != 0) { throw new ArgumentOutOfRangeException("count", "Must be a multiple of Channels!"); } if (_packetProvider == null) { throw new ObjectDisposedException("StreamDecoder"); } if (count == 0) { return 0; } int num = offset; int num2 = offset + count; while (num < num2) { if (_prevPacketStart == _prevPacketEnd) { if (_eosFound) { _nextPacketBuf = null; _prevPacketBuf = null; break; } if (!ReadNextPacket((num - offset) / _channels, out var samplePosition)) { _prevPacketEnd = _prevPacketStop; } if (samplePosition.HasValue && !_hasPosition) { _hasPosition = true; _currentPosition = samplePosition.Value - (_prevPacketEnd - _prevPacketStart) - (num - offset) / _channels; } } int num3 = Math.Min((num2 - num) / _channels, _prevPacketEnd - _prevPacketStart); if (num3 > 0) { num = ((!ClipSamples) ? (num + CopyBuffer(buffer, num, num3)) : (num + ClippingCopyBuffer(buffer, num, num3))); } } count = num - offset; _currentPosition += count / _channels; return count; } private int ClippingCopyBuffer(Span<float> target, int targetIndex, int count) { int num = targetIndex; while (count > 0) { for (int i = 0; i < _channels; i++) { target[num++] = Utils.ClipValue(_prevPacketBuf[i][_prevPacketStart], ref _hasClipped); } _prevPacketStart++; count--; } return num - targetIndex; } private int CopyBuffer(Span<float> target, int targetIndex, int count) { int num = targetIndex; while (count > 0) { for (int i = 0; i < _channels; i++) { target[num++] = _prevPacketBuf[i][_prevPacketStart]; } _prevPacketStart++; count--; } return num - targetIndex; } private bool ReadNextPacket(int bufferedSamples, out long? samplePosition) { int packetStartindex; int packetValidLength; int packetTotalLength; bool isEndOfStream; int bitsRead; int bitsRemaining; int containerOverheadBits; float[][] array = DecodeNextPacket(out packetStartindex, out packetValidLength, out packetTotalLength, out isEndOfStream, out samplePosition, out bitsRead, out bitsRemaining, out containerOverheadBits); _eosFound |= isEndOfStream; if (array == null) { _stats.AddPacket(0, bitsRead, bitsRemaining, containerOverheadBits); return false; } if (samplePosition.HasValue && isEndOfStream) { long num = _currentPosition + bufferedSamples + packetValidLength - packetStartindex; int num2 = (int)(samplePosition.Value - num); if (num2 < 0) { packetValidLength += num2; } } if (_prevPacketEnd > 0) { OverlapBuffers(_prevPacketBuf, array, _prevPacketStart, _prevPacketStop, packetStartindex, _channels); _prevPacketStart = packetStartindex; } else if (_prevPacketBuf == null) { _prevPacketStart = packetValidLength; } _stats.AddPacket(packetValidLength - _prevPacketStart, bitsRead, bitsRemaining, containerOverheadBits); _nextPacketBuf = _prevPacketBuf; _prevPacketEnd = packetValidLength; _prevPacketStop = packetTotalLength; _prevPacketBuf = array; return true; } private float[][] DecodeNextPacket(out int packetStartindex, out int packetValidLength, out int packetTotalLength, out bool isEndOfStream, out long? samplePosition, out int bitsRead, out int bitsRemaining, out int containerOverheadBits) { IPacket packet = null; try { if ((packet = _packetProvider.GetNextPacket()) == null) { isEndOfStream = true; } else { isEndOfStream = packet.IsEndOfStream; if (packet.IsResync) { _hasPosition = false; } containerOverheadBits = packet.ContainerOverheadBits; if (packet.ReadBit()) { bitsRemaining = packet.BitsRemaining + 1; } else { IMode mode = _modes[(uint)packet.ReadBits(_modeFieldBits)]; if (_nextPacketBuf == null) { _nextPacketBuf = new float[_channels][]; for (int i = 0; i < _channels; i++) { _nextPacketBuf[i] = new float[_block1Size]; } } if (mode.Decode(packet, _nextPacketBuf, out packetStartindex, out packetValidLength, out packetTotalLength)) { samplePosition = packet.GranulePosition; bitsRead = packet.BitsRead; bitsRemaining = packet.BitsRemaining; return _nextPacketBuf; } bitsRemaining = packet.BitsRead + packet.BitsRemaining; } } packetStartindex = 0; packetValidLength = 0; packetTotalLength = 0; samplePosition = null; bitsRead = 0; bitsRemaining = 0; containerOverheadBits = 0; return null; } finally { packet?.Done(); } } private static void OverlapBuffers(float[][] previous, float[][] next, int prevStart, int prevLen, int nextStart, int channels) { while (prevStart < prevLen) { for (int i = 0; i < channels; i++) { next[i][nextStart] += previous[i][prevStart]; } prevStart++; nextStart++; } } public void SeekTo(TimeSpan timePosition, SeekOrigin seekOrigin = SeekOrigin.Begin) { SeekTo((long)((double)SampleRate * timePosition.TotalSeconds), seekOrigin); } public void SeekTo(long samplePosition, SeekOrigin seekOrigin = SeekOrigin.Begin) { if (_packetProvider == null) { throw new ObjectDisposedException("StreamDecoder"); } if (!_packetProvider.CanSeek) { throw new InvalidOperationException("Seek is not supported by the Contracts.IPacketProvider instance."); } switch (seekOrigin) { case SeekOrigin.Current: samplePosition = SamplePosition - samplePosition; break; case SeekOrigin.End: samplePosition = TotalSamples - samplePosition; break; default: throw new ArgumentOutOfRangeException("seekOrigin"); case SeekOrigin.Begin: break; } if (samplePosition < 0) { throw new ArgumentOutOfRangeException("samplePosition"); } int num; if (samplePosition == 0L) { _packetProvider.SeekTo(0L, 0, GetPacketGranules); num = 0; } else { long num2 = _packetProvider.SeekTo(samplePosition, 1, GetPacketGranules); num = (int)(samplePosition - num2); } ResetDecoder(); _hasPosition = true; if (!ReadNextPacket(0, out var samplePosition2)) { _eosFound = true; if (_packetProvider.GetGranuleCount() != samplePosition) { throw new InvalidOperationException("Could not read pre-roll packet! Try seeking again prior to reading more samples."); } _prevPacketStart = _prevPacketStop; _currentPosition = samplePosition; return; } if (!ReadNextPacket(0, out samplePosition2)) { ResetDecoder(); _eosFound = true; throw new InvalidOperationException("Could not read pre-roll packet! Try seeking again prior to reading more samples."); } _prevPacketStart += num; _currentPosition = samplePosition; } private int GetPacketGranules(IPacket curPacket) { if (curPacket.IsResync) { return 0; } if (curPacket.ReadBit()) { return 0; } int num = (int)curPacket.ReadBits(_modeFieldBits); if (num < 0 || num >= _modes.Length) { return 0; } return _modes[num].GetPacketSampleCount(curPacket); } public void Dispose() { (_packetProvider as IDisposable)?.Dispose(); _packetProvider = null; } } internal class StreamStats : IStreamStats { private int _sampleRate; private readonly int[] _packetBits = new int[2]; private readonly int[] _packetSamples = new int[2]; private int _packetIndex; private long _totalSamples; private long _audioBits; private long _headerBits; private long _containerBits; private long _wasteBits; private object _lock = new object(); private int _packetCount; public int EffectiveBitRate { get { long totalSamples; long num; lock (_lock) { totalSamples = _totalSamples; num = _audioBits + _headerBits + _containerBits + _wasteBits; } if (totalSamples > 0) { return (int)((double)num / (double)totalSamples * (double)_sampleRate); } return 0; } } public int InstantBitRate { get { int num; int num2; lock (_lock) { num = _packetBits[0] + _packetBits[1]; num2 = _packetSamples[0] + _packetSamples[1]; } if (num2 > 0) { return (int)((double)num / (double)num2 * (double)_sampleRate); } return 0; } } public long ContainerBits => _containerBits; public long OverheadBits => _headerBits; public long AudioBits => _audioBits; public long WasteBits => _wasteBits; public int PacketCount => _packetCount; public void ResetStats() { lock (_lock) { _packetBits[0] = (_packetBits[1] = 0); _packetSamples[0] = (_packetSamples[1] = 0); _packetIndex = 0; _packetCount = 0; _audioBits = 0L; _totalSamples = 0L; _headerBits = 0L; _containerBits = 0L; _wasteBits = 0L; } } internal void SetSampleRate(int sampleRate) { lock (_lock) { _sampleRate = sampleRate; ResetStats(); } } internal void AddPacket(int samples, int bits, int waste, int container) { lock (_lock) { if (samples >= 0) { _audioBits += bits; _wasteBits += waste; _containerBits += container; _totalSamples += samples; _packetBits[_packetIndex] = bits + waste; _packetSamples[_packetIndex] = samples; if (++_packetIndex == 2) { _packetIndex = 0; } } else { _headerBits += bits; _wasteBits += waste; _containerBits += container; } } } } internal class TagData : ITagData { private static IReadOnlyList<string> s_emptyList = new List<string>(); private Dictionary<string, IReadOnlyList<string>> _tags; public IReadOnlyDictionary<string, IReadOnlyList<string>> All => _tags; public string EncoderVendor { get; } public string Title => GetTagSingle("TITLE"); public string Version => GetTagSingle("VERSION"); public string Album => GetTagSingle("ALBUM"); public string TrackNumber => GetTagSingle("TRACKNUMBER"); public string Artist => GetTagSingle("ARTIST"); public IReadOnlyList<string> Performers => GetTagMulti("PERFORMER"); public string Copyright => GetTagSingle("COPYRIGHT"); public string License => GetTagSingle("LICENSE"); public string Organization => GetTagSingle("ORGANIZATION"); public string Description => GetTagSingle("DESCRIPTION"); public IReadOnlyList<string> Genres => GetTagMulti("GENRE"); public IReadOnlyList<string> Dates => GetTagMulti("DATE"); public IReadOnlyList<string> Locations => GetTagMulti("LOCATION"); public string Contact => GetTagSingle("CONTACT"); public string Isrc => GetTagSingle("ISRC"); public TagData(string vendor, string[] comments) { EncoderVendor = vendor; Dictionary<string, IReadOnlyList<string>> dictionary = new Dictionary<string, IReadOnlyList<string>>(); for (int i = 0; i < comments.Length; i++) { string[] array = comments[i].Split(new char[1] { '=' }); if (array.Length == 1) { array = new string[2] { array[0], string.Empty }; } int num = array[0].IndexOf('['); if (num > -1) { array[1] = array[0].Substring(num + 1, array[0].Length - num - 2).ToUpper(CultureInfo.CurrentCulture) + ": " + array[1]; array[0] = array[0].Substring(0, num); } if (dictionary.TryGetValue(array[0].ToUpperInvariant(), out var value)) { ((List<string>)value).Add(array[1]); continue; } dictionary.Add(array[0].ToUpperInvariant(), new List<string> { array[1] }); } _tags = dictionary; } public string GetTagSingle(string key, bool concatenate = false) { IReadOnlyList<string> tagMulti = GetTagMulti(key); if (tagMulti.Count > 0) { if (concatenate) { return string.Join(Environment.NewLine, tagMulti.ToArray()); } return tagMulti[tagMulti.Count - 1]; } return string.Empty; } public IReadOnlyList<string> GetTagMulti(string key) { if (_tags.TryGetValue(key.ToUpperInvariant(), out var value)) { return value; } return s_emptyList; } } internal static class Utils { internal static int ilog(int x) { int num = 0; while (x > 0) { num++; x >>= 1; } return num; } internal static uint BitReverse(uint n) { return BitReverse(n, 32); } internal static uint BitReverse(uint n, int bits) { n = ((n & 0xAAAAAAAAu) >> 1) | ((n & 0x55555555) << 1); n = ((n & 0xCCCCCCCCu) >> 2) | ((n & 0x33333333) << 2); n = ((n & 0xF0F0F0F0u) >> 4) | ((n & 0xF0F0F0F) << 4); n = ((n & 0xFF00FF00u) >> 8) | ((n & 0xFF00FF) << 8); return ((n >> 16) | (n << 16)) >> 32 - bits; } internal static float ClipValue(float value, ref bool clipped) { if (value > (float)Math.PI * 113f / 355f) { clipped = true; return (float)Math.PI * 113f / 355f; } if (value < (float)Math.PI * -113f / 355f) { clipped = true; return (float)Math.PI * -113f / 355f; } return value; } internal static float ConvertFromVorbisFloat32(uint bits) { int num = (int)bits >> 31; double y = (int)(((bits & 0x7FE00000) >> 21) - 788); return (float)(((bits & 0x1FFFFF) ^ num) + (num & 1)) * (float)Math.Pow(2.0, y); } } public sealed class VorbisReader : IVorbisReader, IDisposable { private readonly List<IStreamDecoder> _decoders; private readonly NVorbis.Contracts.IContainerReader _containerReader; private readonly bool _closeOnDispose; private IStreamDecoder _streamDecoder; internal static Func<Stream, bool, NVorbis.Contracts.IContainerReader> CreateContainerReader { get; set; } = (Stream s, bool cod) => new ContainerReader(s, cod); internal static Func<NVorbis.Contracts.IPacketProvider, IStreamDecoder> CreateStreamDecoder { get; set; } = (NVorbis.Contracts.IPacketProvider pp) => new StreamDecoder(pp, new Factory()); public IReadOnlyList<IStreamDecoder> Streams => _decoders; public int Channels => _streamDecoder.Channels; public int SampleRate => _streamDecoder.SampleRate; public int UpperBitrate => _streamDecoder.UpperBitrate; public int NominalBitrate => _streamDecoder.NominalBitrate; public int LowerBitrate => _streamDecoder.LowerBitrate; public ITagData Tags => _streamDecoder.Tags; [Obsolete("Use .Tags.EncoderVendor instead.")] public string Vendor => _streamDecoder.Tags.EncoderVendor; [Obsolete("Use .Tags.All instead.")] public string[] Comments => _streamDecoder.Tags.All.SelectMany((KeyValuePair<string, IReadOnlyList<string>> k) => k.Value, (KeyValuePair<string, IReadOnlyList<string>> kvp, string Item) => kvp.Key + "=" + Item).ToArray(); [Obsolete("No longer supported. Will receive a new stream when parameters change.", true)] public bool IsParameterChange { get { throw new NotSupportedException(); } } public long ContainerOverheadBits => _containerReader?.ContainerBits ?? 0; public long ContainerWasteBits => _containerReader?.WasteBits ?? 0; public int StreamIndex => _decoders.IndexOf(_streamDecoder); [Obsolete("Use .Streams.Count instead.")] public int StreamCount => _decoders.Count; [Obsolete("Use VorbisReader.TimePosition instead.")] public TimeSpan DecodedTime { get { return _streamDecoder.TimePosition; } set { TimePosition = value; } } [Obsolete("Use VorbisReader.SamplePosition instead.")] public long DecodedPosition { get { return _streamDecoder.SamplePosition; } set { SamplePosition = value; } } public TimeSpan TotalTime => _streamDecoder.TotalTime; public long TotalSamples => _streamDecoder.TotalSamples; public TimeSpan TimePosition { get { return _streamDecoder.TimePosition; } set { _streamDecoder.TimePosition = value; } } public long SamplePosition { get { return _streamDecoder.SamplePosition; } set { _streamDecoder.SamplePosition = value; } } public bool IsEndOfStream => _streamDecoder.IsEndOfStream; public bool ClipSamples { get { return _streamDecoder.ClipSamples; } set { _streamDecoder.ClipSamples = value; } } public bool HasClipped => _streamDecoder.HasClipped; public IStreamStats StreamStats => _streamDecoder.Stats; [Obsolete("Use Streams[*].Stats instead.", true)] public IVorbisStreamStatus[] Stats { get { throw new NotSupportedException(); } } public event EventHandler<NewStreamEventArgs> NewStream; public VorbisReader(string fileName) : this(File.OpenRead(fileName)) { } public VorbisReader(Stream stream, bool closeOnDispose = true) { _decoders = new List<IStreamDecoder>(); NVorbis.Contracts.IContainerReader containerReader = CreateContainerReader(stream, closeOnDispose); containerReader.NewStreamCallback = ProcessNewStream; if (!containerReader.TryInit() || _decoders.Count == 0) { containerReader.NewStreamCallback = null; containerReader.Dispose(); if (closeOnDispose) { stream.Dispose(); } throw new ArgumentException("Could not load the specified container!", "containerReader"); } _closeOnDispose = closeOnDispose; _containerReader = containerReader; _streamDecoder = _decoders[0]; } [Obsolete("Use \"new StreamDecoder(Contracts.IPacketProvider)\" and the container's NewStreamCallback or Streams property instead.", true)] public VorbisReader(NVorbis.Contracts.IContainerReader containerReader) { throw new NotSupportedException(); } [Obsolete("Use \"new StreamDecoder(Contracts.IPacketProvider)\" instead.", true)] public VorbisReader(NVorbis.Contracts.IPacketProvider packetProvider) { throw new NotSupportedException(); } private bool ProcessNewStream(NVorbis.Contracts.IPacketProvider packetProvider) { IStreamDecoder streamDecoder = CreateStreamDecoder(packetProvider); streamDecoder.ClipSamples = true; NewStreamEventArgs newStreamEventArgs = new NewStreamEventArgs(streamDecoder); this.NewStream?.Invoke(this, newStreamEventArgs); if (!newStreamEventArgs.IgnoreStream) { _decoders.Add(streamDecoder); return true; } return false; } public void Dispose() { if (_decoders != null) { foreach (IStreamDecoder decoder in _decoders) { decoder.Dispose(); } _decoders.Clear(); } if (_containerReader != null) { _containerReader.NewStreamCallback = null; if (_closeOnDispose) { _containerReader.Dispose(); } } } public bool FindNextStream() { if (_containerReader == null) { return false; } return _containerReader.FindNextStream(); } public bool SwitchStreams(int index) { if (index < 0 || index >= _decoders.Count) { throw new ArgumentOutOfRangeException("index"); } IStreamDecoder streamDecoder = _decoders[index]; IStreamDecoder streamDecoder2 = _streamDecoder; if (streamDecoder == streamDecoder2) { return false; } streamDecoder.ClipSamples = streamDecoder2.ClipSamples; _streamDecoder = streamDecoder; if (streamDecoder.Channels == streamDecoder2.Channels) { return streamDecoder.SampleRate != streamDecoder2.SampleRate; } return true; } public void SeekTo(TimeSpan timePosition, SeekOrigin seekOrigin = SeekOrigin.Begin) { _streamDecoder.SeekTo(timePosition, seekOrigin); } public void SeekTo(long samplePosition, SeekOrigin seekOrigin = SeekOrigin.Begin) { _streamDecoder.SeekTo(samplePosition, seekOrigin); } public int ReadSamples(float[] buffer, int offset, int count) { count -= count % _streamDecoder.Channels; if (count > 0) { return _streamDecoder.Read(buffer, offset, count); } return 0; } public int ReadSamples(Span<float> buffer) { int count = buffer.Length - buffer.Length % _streamDecoder.Channels; if (!buffer.IsEmpty) { return _streamDecoder.Read(buffer, 0, count); } return 0; } [Obsolete("No longer needed.", true)] public void ClearParameterChange() { throw new NotSupportedException(); } } } namespace NVorbis.Ogg { public sealed class ContainerReader : NVorbis.Contracts.IContainerReader, IDisposable { private IPageReader _reader; private List<WeakReference<NVorbis.Contracts.IPacketProvider>> _packetProviders; private bool _foundStream; internal static Func<Stream, bool, Func<NVorbis.Contracts.IPacketProvider, bool>, IPageReader> CreatePageReader { get; set; } = (Stream s, bool cod, Func<NVorbis.Contracts.IPacketProvider, bool> cb) => new PageReader(s, cod, cb); internal static Func<Stream, bool, Func<NVorbis.Contracts.IPacketProvider, bool>, IPageReader> CreateForwardOnlyPageReader { get; set; } = (Stream s, bool cod, Func<NVorbis.Contracts.IPacketProvider, bool> cb) => new ForwardOnlyPageReader(s, cod, cb); public NewStreamHandler NewStreamCallback { get; set; } public bool CanSeek { get; } public long WasteBits => _reader.WasteBits; public long ContainerBits => _reader.ContainerBits; public IReadOnlyList<NVorbis.Contracts.IPacketProvider> GetStreams() { List<NVorbis.Contracts.IPacketProvider> list = new List<NVorbis.Contracts.IPacketProvider>(_packetProviders.Count); for (int i = 0; i < _packetProviders.Count; i++) { if (_packetProviders[i].TryGetTarget(out var target)) { list.Add(target); continue; } list.RemoveAt(i); i--; } return list; } public ContainerReader(Stream stream, bool closeOnDispose) { if (stream == null) { throw new ArgumentNullException("stream"); } _packetProviders = new List<WeakReference<NVorbis.Contracts.IPacketProvider>>(); if (stream.CanSeek) { _reader = CreatePageReader(stream, closeOnDispose, ProcessNewStream); CanSeek = true; } else { _reader = CreateForwardOnlyPageReader(stream, closeOnDispose, ProcessNewStream); } } public bool TryInit() { return FindNextStream(); } public bool FindNextStream() { _reader.Lock(); try { _foundStream = false; while (_reader.ReadNextPage()) { if (_foundStream) { return true; } } return false; } finally { _reader.Release(); } } private bool ProcessNewStream(NVorbis.Contracts.IPacketProvider packetProvider) { bool flag = _reader.Release(); try { NewStreamHandler newStreamCallback = NewStreamCallback; if (newStreamCallback == null || newStreamCallback(packetProvider)) { _packetProviders.Add(new WeakReference<NVorbis.Contracts.IPacketProvider>(packetProvider)); _foundStream = true; return true; } return false; } finally { if (flag) { _reader.Lock(); } } } public void Dispose() { _reader?.Dispose(); _reader = null; } } internal class Crc : ICrc { private const uint CRC32_POLY = 79764919u; private static readonly uint[] s_crcTable; private uint _crc; static Crc() { s_crcTable = new uint[256]; for (uint num = 0u; num < 256; num++) { uint num2 = num << 24; for (int i = 0; i < 8; i++) { num2 = (num2 << 1) ^ ((num2 >= 2147483648u) ? 79764919u : 0u); } s_crcTable[num] = num2; } } public Crc() { Reset(); } public void Reset() { _crc = 0u; } public void Update(int nextVal) { _crc = (_crc << 8) ^ s_crcTable[nextVal ^ (_crc >> 24)]; } public bool Test(uint checkCrc) { return _crc == checkCrc; } } internal class ForwardOnlyPacketProvider : DataPacket, IForwardOnlyPacketProvider, NVorbis.Contracts.IPacketProvider { private int _lastSeqNo; private readonly Queue<(byte[] buf, bool isResync)> _pageQueue = new Queue<(byte[], bool)>(); private readonly IPageReader _reader; private byte[] _pageBuf; private int _packetIndex; private bool _isEndOfStream; private int _dataStart; private bool _lastWasPeek; private Memory<byte> _packetBuf; private int _dataIndex; public bool CanSeek => false; public int StreamSerial { get; } protected override int TotalBits => _packetBuf.Length * 8; public ForwardOnlyPacketProvider(IPageReader reader, int streamSerial) { _reader = reader; StreamSerial = streamSerial; _packetIndex = int.MaxValue; } public bool AddPage(byte[] buf, bool isResync) { if ((buf[5] & 2u) != 0) { if (_isEndOfStream) { return false; } isResync = true; _lastSeqNo = BitConverter.ToInt32(buf, 18); } else { int num = BitConverter.ToInt32(buf, 18); isResync |= num != _lastSeqNo + 1; _lastSeqNo = num; } int num2 = 0; for (int i = 0; i < buf[26]; i++) { num2 += buf[27 + i]; } if (num2 == 0) { return false; } _pageQueue.Enqueue((buf, isResync)); return true; } public void SetEndOfStream() { _isEndOfStream = true; } public IPacket GetNextPacket() { if (_packetBuf.Length > 0) { if (!_lastWasPeek) { throw new InvalidOperationException("Must call Done() on previous packet first."); } _lastWasPeek = false; return this; } _lastWasPeek = false; if (GetPacket()) { return this; } return null; } public IPacket PeekNextPacket() { if (_packetBuf.Length > 0) { if (!_lastWasPeek) { throw new InvalidOperationException("Must call Done() on previous packet first."); } return this; } _lastWasPeek = true; if (GetPacket()) { return this; } return null; } private bool GetPacket() { byte[] pageBuf; bool isResync; int packetIndex; bool isContinuation; bool isContinued; int dataStart; if (_pageBuf != null && _packetIndex < 27 + _pageBuf[26]) { pageBuf = _pageBuf; isResync = false; dataStart = _dataStart; packetIndex = _packetIndex; isContinuation = false; isContinued = pageBuf[26 + pageBuf[26]] == byte.MaxValue; } else if (!ReadNextPage(out pageBuf, out isResync, out dataStart, out packetIndex, out isContinuation, out isContinued)) { return false; } int num = dataStart; bool flag = packetIndex == 27; if (isContinuation && flag) { isResync = true; num += GetPacketLength(pageBuf, ref packetIndex); if (packetIndex == 27 + pageBuf[26]) { return GetPacket(); } } if (!flag) { num = 0; } int packetLength = GetPacketLength(pageBuf, ref packetIndex); Memory<byte> memory = new Memory<byte>(pageBuf, dataStart, packetLength); dataStart += packetLength; bool flag2 = packetIndex == 27 + pageBuf[26]; if (isContinued) { if (flag2) { flag2 = false; } else { int packetIndex2 = packetIndex; GetPacketLength(pageBuf, ref packetIndex2); flag2 = packetIndex2 == 27 + pageBuf[26]; } } bool flag3 = false; long? granulePosition = null; if (flag2) { granulePosition = BitConverter.ToInt64(pageBuf, 6); if ((pageBuf[5] & 4u) != 0 || (_isEndOfStream && _pageQueue.Count == 0)) { flag3 = true; } } else { while (isContinued && packetIndex == 27 + pageBuf[26] && ReadNextPage(out pageBuf, out isResync, out dataStart, out packetIndex, out isContinuation, out isContinued) && !isResync && isContinuation) { num += 27 + pageBuf[26]; Memory<byte> memory2 = memory; int packetLength2 = GetPacketLength(pageBuf, ref packetIndex); memory = new Memory<byte>(new byte[memory2.Length + packetLength2]); memory2.CopyTo(memory); new Memory<byte>(pageBuf, dataStart, packetLength2).CopyTo(memory.Slice(memory2.Length)); dataStart += packetLength2; } } base.IsResync = isResync; base.GranulePosition = granulePosition; base.IsEndOfStream = flag3; base.ContainerOverheadBits = num * 8; _pageBuf = pageBuf; _dataStart = dataStart; _packetIndex = packetIndex; _packetBuf = memory; _isEndOfStream |= flag3; Reset(); return true; } private bool ReadNextPage(out byte[] pageBuf, out bool isResync, out int dataStart, out int packetIndex, out bool isContinuation, out bool isContinued) { while (_pageQueue.Count == 0) { if (_isEndOfStream || !_reader.ReadNextPage()) { pageBuf = null; isResync = false; dataStart = 0; packetIndex = 0; isContinuation = false; isContinued = false; return false; } } (byte[], bool) tuple = _pageQueue.Dequeue(); pageBuf = tuple.Item1; isResync = tuple.Item2; dataStart = pageBuf[26] + 27; packetIndex = 27; isContinuation = (pageBuf[5] & 1) != 0; isContinued = pageBuf[26 + pageBuf[26]] == byte.MaxValue; retu
BepInEx/plugins/elytraking-Dread/System.Buffers.dll
Decompiled a week agousing System; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Threading; using FxResources.System.Buffers; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Buffers")] [assembly: AssemblyDescription("System.Buffers")] [assembly: AssemblyDefaultAlias("System.Buffers")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.25519.03")] [assembly: AssemblyInformationalVersion("4.6.25519.03 built by: dlab-DDVSOWINAGE013. Commit Hash: 8321c729934c0f8be754953439b88e6e1c120c24")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.2.0")] [module: UnverifiableCode] namespace FxResources.System.Buffers { internal static class SR { } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; private const string s_resourcesName = "FxResources.System.Buffers.SR"; private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); internal static string ArgumentException_BufferNotFromPool => GetResourceString("ArgumentException_BufferNotFromPool", null); internal static Type ResourceType => typeof(SR); [MethodImpl(MethodImplOptions.NoInlining)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString) { string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal)) { return defaultString; } return text; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.All)] internal class __BlockReflectionAttribute : Attribute { } } namespace System.Buffers { public abstract class ArrayPool<T> { private static ArrayPool<T> s_sharedInstance; public static ArrayPool<T> Shared { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Volatile.Read(ref s_sharedInstance) ?? EnsureSharedCreated(); } } [MethodImpl(MethodImplOptions.NoInlining)] private static ArrayPool<T> EnsureSharedCreated() { Interlocked.CompareExchange(ref s_sharedInstance, Create(), null); return s_sharedInstance; } public static ArrayPool<T> Create() { return new DefaultArrayPool<T>(); } public static ArrayPool<T> Create(int maxArrayLength, int maxArraysPerBucket) { return new DefaultArrayPool<T>(maxArrayLength, maxArraysPerBucket); } public abstract T[] Rent(int minimumLength); public abstract void Return(T[] array, bool clearArray = false); } [EventSource(Name = "System.Buffers.ArrayPoolEventSource")] internal sealed class ArrayPoolEventSource : EventSource { internal enum BufferAllocatedReason { Pooled, OverMaximumSize, PoolExhausted } internal static readonly System.Buffers.ArrayPoolEventSource Log = new System.Buffers.ArrayPoolEventSource(); [Event(1, Level = EventLevel.Verbose)] internal unsafe void BufferRented(int bufferId, int bufferSize, int poolId, int bucketId) { EventData* ptr = stackalloc EventData[4]; ptr->Size = 4; ptr->DataPointer = (IntPtr)(&bufferId); ptr[1].Size = 4; ptr[1].DataPointer = (IntPtr)(&bufferSize); ptr[2].Size = 4; ptr[2].DataPointer = (IntPtr)(&poolId); ptr[3].Size = 4; ptr[3].DataPointer = (IntPtr)(&bucketId); WriteEventCore(1, 4, ptr); } [Event(2, Level = EventLevel.Informational)] internal unsafe void BufferAllocated(int bufferId, int bufferSize, int poolId, int bucketId, BufferAllocatedReason reason) { EventData* ptr = stackalloc EventData[5]; ptr->Size = 4; ptr->DataPointer = (IntPtr)(&bufferId); ptr[1].Size = 4; ptr[1].DataPointer = (IntPtr)(&bufferSize); ptr[2].Size = 4; ptr[2].DataPointer = (IntPtr)(&poolId); ptr[3].Size = 4; ptr[3].DataPointer = (IntPtr)(&bucketId); ptr[4].Size = 4; ptr[4].DataPointer = (IntPtr)(&reason); WriteEventCore(2, 5, ptr); } [Event(3, Level = EventLevel.Verbose)] internal void BufferReturned(int bufferId, int bufferSize, int poolId) { WriteEvent(3, bufferId, bufferSize, poolId); } } internal sealed class DefaultArrayPool<T> : ArrayPool<T> { private sealed class Bucket { internal readonly int _bufferLength; private readonly T[][] _buffers; private readonly int _poolId; private SpinLock _lock; private int _index; internal int Id => GetHashCode(); internal Bucket(int bufferLength, int numberOfBuffers, int poolId) { _lock = new SpinLock(Debugger.IsAttached); _buffers = new T[numberOfBuffers][]; _bufferLength = bufferLength; _poolId = poolId; } internal T[] Rent() { T[][] buffers = _buffers; T[] array = null; bool lockTaken = false; bool flag = false; try { _lock.Enter(ref lockTaken); if (_index < buffers.Length) { array = buffers[_index]; buffers[_index++] = null; flag = array == null; } } finally { if (lockTaken) { _lock.Exit(useMemoryBarrier: false); } } if (flag) { array = new T[_bufferLength]; System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; if (log.IsEnabled()) { log.BufferAllocated(array.GetHashCode(), _bufferLength, _poolId, Id, System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.Pooled); } } return array; } internal void Return(T[] array) { if (array.Length != _bufferLength) { throw new ArgumentException(System.SR.ArgumentException_BufferNotFromPool, "array"); } bool lockTaken = false; try { _lock.Enter(ref lockTaken); if (_index != 0) { _buffers[--_index] = array; } } finally { if (lockTaken) { _lock.Exit(useMemoryBarrier: false); } } } } private const int DefaultMaxArrayLength = 1048576; private const int DefaultMaxNumberOfArraysPerBucket = 50; private static T[] s_emptyArray; private readonly Bucket[] _buckets; private int Id => GetHashCode(); internal DefaultArrayPool() : this(1048576, 50) { } internal DefaultArrayPool(int maxArrayLength, int maxArraysPerBucket) { if (maxArrayLength <= 0) { throw new ArgumentOutOfRangeException("maxArrayLength"); } if (maxArraysPerBucket <= 0) { throw new ArgumentOutOfRangeException("maxArraysPerBucket"); } if (maxArrayLength > 1073741824) { maxArrayLength = 1073741824; } else if (maxArrayLength < 16) { maxArrayLength = 16; } int id = Id; int num = System.Buffers.Utilities.SelectBucketIndex(maxArrayLength); Bucket[] array = new Bucket[num + 1]; for (int i = 0; i < array.Length; i++) { array[i] = new Bucket(System.Buffers.Utilities.GetMaxSizeForBucket(i), maxArraysPerBucket, id); } _buckets = array; } public override T[] Rent(int minimumLength) { if (minimumLength < 0) { throw new ArgumentOutOfRangeException("minimumLength"); } if (minimumLength == 0) { return s_emptyArray ?? (s_emptyArray = new T[0]); } System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; T[] array = null; int num = System.Buffers.Utilities.SelectBucketIndex(minimumLength); if (num < _buckets.Length) { int num2 = num; do { array = _buckets[num2].Rent(); if (array != null) { if (log.IsEnabled()) { log.BufferRented(array.GetHashCode(), array.Length, Id, _buckets[num2].Id); } return array; } } while (++num2 < _buckets.Length && num2 != num + 2); array = new T[_buckets[num]._bufferLength]; } else { array = new T[minimumLength]; } if (log.IsEnabled()) { int hashCode = array.GetHashCode(); int bucketId = -1; log.BufferRented(hashCode, array.Length, Id, bucketId); log.BufferAllocated(hashCode, array.Length, Id, bucketId, (num >= _buckets.Length) ? System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.OverMaximumSize : System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.PoolExhausted); } return array; } public override void Return(T[] array, bool clearArray = false) { if (array == null) { throw new ArgumentNullException("array"); } if (array.Length == 0) { return; } int num = System.Buffers.Utilities.SelectBucketIndex(array.Length); if (num < _buckets.Length) { if (clearArray) { Array.Clear(array, 0, array.Length); } _buckets[num].Return(array); } System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; if (log.IsEnabled()) { log.BufferReturned(array.GetHashCode(), array.Length, Id); } } } internal static class Utilities { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int SelectBucketIndex(int bufferSize) { uint num = (uint)(bufferSize - 1) >> 4; int num2 = 0; if (num > 65535) { num >>= 16; num2 = 16; } if (num > 255) { num >>= 8; num2 += 8; } if (num > 15) { num >>= 4; num2 += 4; } if (num > 3) { num >>= 2; num2 += 2; } if (num > 1) { num >>= 1; num2++; } return num2 + (int)num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int GetMaxSizeForBucket(int binIndex) { return 16 << binIndex; } } }
BepInEx/plugins/elytraking-Dread/System.Memory.dll
Decompiled a week ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Numerics; using System.Numerics.Hashing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using FxResources.System.Memory; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Memory")] [assembly: AssemblyDescription("System.Memory")] [assembly: AssemblyDefaultAlias("System.Memory")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.27617.02")] [assembly: AssemblyInformationalVersion("4.6.27617.02 @BuiltBy: dlab14-DDVSOWINAGE071 @Branch: release/2.1-MSRC @SrcCode: https://github.com/dotnet/corefx/tree/c6cf790234e063b855fcdb50f3fb1b3cfac73275")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.1.1")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsByRefLikeAttribute : Attribute { } } namespace FxResources.System.Memory { internal static class SR { } } namespace System { public readonly struct SequencePosition : IEquatable<SequencePosition> { private readonly object _object; private readonly int _integer; public SequencePosition(object @object, int integer) { _object = @object; _integer = integer; } [EditorBrowsable(EditorBrowsableState.Never)] public object GetObject() { return _object; } [EditorBrowsable(EditorBrowsableState.Never)] public int GetInteger() { return _integer; } public bool Equals(SequencePosition other) { if (_integer == other._integer) { return object.Equals(_object, other._object); } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is SequencePosition other) { return Equals(other); } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return HashHelpers.Combine(_object?.GetHashCode() ?? 0, _integer); } } internal static class ThrowHelper { internal static void ThrowArgumentNullException(System.ExceptionArgument argument) { throw CreateArgumentNullException(argument); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentNullException(System.ExceptionArgument argument) { return new ArgumentNullException(argument.ToString()); } internal static void ThrowArrayTypeMismatchException() { throw CreateArrayTypeMismatchException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArrayTypeMismatchException() { return new ArrayTypeMismatchException(); } internal static void ThrowArgumentException_InvalidTypeWithPointersNotSupported(Type type) { throw CreateArgumentException_InvalidTypeWithPointersNotSupported(type); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException_InvalidTypeWithPointersNotSupported(Type type) { return new ArgumentException(System.SR.Format(System.SR.Argument_InvalidTypeWithPointersNotSupported, type)); } internal static void ThrowArgumentException_DestinationTooShort() { throw CreateArgumentException_DestinationTooShort(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException_DestinationTooShort() { return new ArgumentException(System.SR.Argument_DestinationTooShort); } internal static void ThrowIndexOutOfRangeException() { throw CreateIndexOutOfRangeException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateIndexOutOfRangeException() { return new IndexOutOfRangeException(); } internal static void ThrowArgumentOutOfRangeException() { throw CreateArgumentOutOfRangeException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException() { return new ArgumentOutOfRangeException(); } internal static void ThrowArgumentOutOfRangeException(System.ExceptionArgument argument) { throw CreateArgumentOutOfRangeException(argument); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException(System.ExceptionArgument argument) { return new ArgumentOutOfRangeException(argument.ToString()); } internal static void ThrowArgumentOutOfRangeException_PrecisionTooLarge() { throw CreateArgumentOutOfRangeException_PrecisionTooLarge(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_PrecisionTooLarge() { return new ArgumentOutOfRangeException("precision", System.SR.Format(System.SR.Argument_PrecisionTooLarge, (byte)99)); } internal static void ThrowArgumentOutOfRangeException_SymbolDoesNotFit() { throw CreateArgumentOutOfRangeException_SymbolDoesNotFit(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_SymbolDoesNotFit() { return new ArgumentOutOfRangeException("symbol", System.SR.Argument_BadFormatSpecifier); } internal static void ThrowInvalidOperationException() { throw CreateInvalidOperationException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException() { return new InvalidOperationException(); } internal static void ThrowInvalidOperationException_OutstandingReferences() { throw CreateInvalidOperationException_OutstandingReferences(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException_OutstandingReferences() { return new InvalidOperationException(System.SR.OutstandingReferences); } internal static void ThrowInvalidOperationException_UnexpectedSegmentType() { throw CreateInvalidOperationException_UnexpectedSegmentType(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException_UnexpectedSegmentType() { return new InvalidOperationException(System.SR.UnexpectedSegmentType); } internal static void ThrowInvalidOperationException_EndPositionNotReached() { throw CreateInvalidOperationException_EndPositionNotReached(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException_EndPositionNotReached() { return new InvalidOperationException(System.SR.EndPositionNotReached); } internal static void ThrowArgumentOutOfRangeException_PositionOutOfRange() { throw CreateArgumentOutOfRangeException_PositionOutOfRange(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_PositionOutOfRange() { return new ArgumentOutOfRangeException("position"); } internal static void ThrowArgumentOutOfRangeException_OffsetOutOfRange() { throw CreateArgumentOutOfRangeException_OffsetOutOfRange(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_OffsetOutOfRange() { return new ArgumentOutOfRangeException("offset"); } internal static void ThrowObjectDisposedException_ArrayMemoryPoolBuffer() { throw CreateObjectDisposedException_ArrayMemoryPoolBuffer(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateObjectDisposedException_ArrayMemoryPoolBuffer() { return new ObjectDisposedException("ArrayMemoryPoolBuffer"); } internal static void ThrowFormatException_BadFormatSpecifier() { throw CreateFormatException_BadFormatSpecifier(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateFormatException_BadFormatSpecifier() { return new FormatException(System.SR.Argument_BadFormatSpecifier); } internal static void ThrowArgumentException_OverlapAlignmentMismatch() { throw CreateArgumentException_OverlapAlignmentMismatch(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException_OverlapAlignmentMismatch() { return new ArgumentException(System.SR.Argument_OverlapAlignmentMismatch); } internal static void ThrowNotSupportedException() { throw CreateThrowNotSupportedException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateThrowNotSupportedException() { return new NotSupportedException(); } public static bool TryFormatThrowFormatException(out int bytesWritten) { bytesWritten = 0; ThrowFormatException_BadFormatSpecifier(); return false; } public static bool TryParseThrowFormatException<T>(out T value, out int bytesConsumed) { value = default(T); bytesConsumed = 0; ThrowFormatException_BadFormatSpecifier(); return false; } public static void ThrowArgumentValidationException<T>(ReadOnlySequenceSegment<T> startSegment, int startIndex, ReadOnlySequenceSegment<T> endSegment) { throw CreateArgumentValidationException(startSegment, startIndex, endSegment); } private static Exception CreateArgumentValidationException<T>(ReadOnlySequenceSegment<T> startSegment, int startIndex, ReadOnlySequenceSegment<T> endSegment) { if (startSegment == null) { return CreateArgumentNullException(System.ExceptionArgument.startSegment); } if (endSegment == null) { return CreateArgumentNullException(System.ExceptionArgument.endSegment); } if (startSegment != endSegment && startSegment.RunningIndex > endSegment.RunningIndex) { return CreateArgumentOutOfRangeException(System.ExceptionArgument.endSegment); } if ((uint)startSegment.Memory.Length < (uint)startIndex) { return CreateArgumentOutOfRangeException(System.ExceptionArgument.startIndex); } return CreateArgumentOutOfRangeException(System.ExceptionArgument.endIndex); } public static void ThrowArgumentValidationException(Array array, int start) { throw CreateArgumentValidationException(array, start); } private static Exception CreateArgumentValidationException(Array array, int start) { if (array == null) { return CreateArgumentNullException(System.ExceptionArgument.array); } if ((uint)start > (uint)array.Length) { return CreateArgumentOutOfRangeException(System.ExceptionArgument.start); } return CreateArgumentOutOfRangeException(System.ExceptionArgument.length); } public static void ThrowStartOrEndArgumentValidationException(long start) { throw CreateStartOrEndArgumentValidationException(start); } private static Exception CreateStartOrEndArgumentValidationException(long start) { if (start < 0) { return CreateArgumentOutOfRangeException(System.ExceptionArgument.start); } return CreateArgumentOutOfRangeException(System.ExceptionArgument.length); } } internal enum ExceptionArgument { length, start, minimumBufferSize, elementIndex, comparable, comparer, destination, offset, startSegment, endSegment, startIndex, endIndex, array, culture, manager } internal static class DecimalDecCalc { private static uint D32DivMod1E9(uint hi32, ref uint lo32) { ulong num = ((ulong)hi32 << 32) | lo32; lo32 = (uint)(num / 1000000000); return (uint)(num % 1000000000); } internal static uint DecDivMod1E9(ref MutableDecimal value) { return D32DivMod1E9(D32DivMod1E9(D32DivMod1E9(0u, ref value.High), ref value.Mid), ref value.Low); } internal static void DecAddInt32(ref MutableDecimal value, uint i) { if (D32AddCarry(ref value.Low, i) && D32AddCarry(ref value.Mid, 1u)) { D32AddCarry(ref value.High, 1u); } } private static bool D32AddCarry(ref uint value, uint i) { uint num = value; uint num2 = (value = num + i); if (num2 >= num) { return num2 < i; } return true; } internal static void DecMul10(ref MutableDecimal value) { MutableDecimal d = value; DecShiftLeft(ref value); DecShiftLeft(ref value); DecAdd(ref value, d); DecShiftLeft(ref value); } private static void DecShiftLeft(ref MutableDecimal value) { uint num = (((value.Low & 0x80000000u) != 0) ? 1u : 0u); uint num2 = (((value.Mid & 0x80000000u) != 0) ? 1u : 0u); value.Low <<= 1; value.Mid = (value.Mid << 1) | num; value.High = (value.High << 1) | num2; } private static void DecAdd(ref MutableDecimal value, MutableDecimal d) { if (D32AddCarry(ref value.Low, d.Low) && D32AddCarry(ref value.Mid, 1u)) { D32AddCarry(ref value.High, 1u); } if (D32AddCarry(ref value.Mid, d.Mid)) { D32AddCarry(ref value.High, 1u); } D32AddCarry(ref value.High, d.High); } } internal static class Number { private static class DoubleHelper { public unsafe static uint Exponent(double d) { return (*(uint*)((byte*)(&d) + 4) >> 20) & 0x7FFu; } public unsafe static ulong Mantissa(double d) { return *(uint*)(&d) | ((ulong)(uint)(*(int*)((byte*)(&d) + 4) & 0xFFFFF) << 32); } public unsafe static bool Sign(double d) { return *(uint*)((byte*)(&d) + 4) >> 31 != 0; } } internal const int DECIMAL_PRECISION = 29; private static readonly ulong[] s_rgval64Power10 = new ulong[30] { 11529215046068469760uL, 14411518807585587200uL, 18014398509481984000uL, 11258999068426240000uL, 14073748835532800000uL, 17592186044416000000uL, 10995116277760000000uL, 13743895347200000000uL, 17179869184000000000uL, 10737418240000000000uL, 13421772800000000000uL, 16777216000000000000uL, 10485760000000000000uL, 13107200000000000000uL, 16384000000000000000uL, 14757395258967641293uL, 11805916207174113035uL, 9444732965739290428uL, 15111572745182864686uL, 12089258196146291749uL, 9671406556917033399uL, 15474250491067253438uL, 12379400392853802751uL, 9903520314283042201uL, 15845632502852867522uL, 12676506002282294018uL, 10141204801825835215uL, 16225927682921336344uL, 12980742146337069075uL, 10384593717069655260uL }; private static readonly sbyte[] s_rgexp64Power10 = new sbyte[15] { 4, 7, 10, 14, 17, 20, 24, 27, 30, 34, 37, 40, 44, 47, 50 }; private static readonly ulong[] s_rgval64Power10By16 = new ulong[42] { 10240000000000000000uL, 11368683772161602974uL, 12621774483536188886uL, 14012984643248170708uL, 15557538194652854266uL, 17272337110188889248uL, 9588073174409622172uL, 10644899600020376798uL, 11818212630765741798uL, 13120851772591970216uL, 14567071740625403792uL, 16172698447808779622uL, 17955302187076837696uL, 9967194951097567532uL, 11065809325636130658uL, 12285516299433008778uL, 13639663065038175358uL, 15143067982934716296uL, 16812182738118149112uL, 9332636185032188787uL, 10361307573072618722uL, 16615349947311448416uL, 14965776766268445891uL, 13479973333575319909uL, 12141680576410806707uL, 10936253623915059637uL, 9850501549098619819uL, 17745086042373215136uL, 15983352577617880260uL, 14396524142538228461uL, 12967236152753103031uL, 11679847981112819795uL, 10520271803096747049uL, 9475818434452569218uL, 17070116948172427008uL, 15375394465392026135uL, 13848924157002783096uL, 12474001934591998882uL, 11235582092889474480uL, 10120112665365530972uL, 18230774251475056952uL, 16420821625123739930uL }; private static readonly short[] s_rgexp64Power10By16 = new short[21] { 54, 107, 160, 213, 266, 319, 373, 426, 479, 532, 585, 638, 691, 745, 798, 851, 904, 957, 1010, 1064, 1117 }; public static void RoundNumber(ref NumberBuffer number, int pos) { Span<byte> digits = number.Digits; int i; for (i = 0; i < pos && digits[i] != 0; i++) { } if (i == pos && digits[i] >= 53) { while (i > 0 && digits[i - 1] == 57) { i--; } if (i > 0) { digits[i - 1]++; } else { number.Scale++; digits[0] = 49; i = 1; } } else { while (i > 0 && digits[i - 1] == 48) { i--; } } if (i == 0) { number.Scale = 0; number.IsNegative = false; } digits[i] = 0; } internal static bool NumberBufferToDouble(ref NumberBuffer number, out double value) { double num = NumberToDouble(ref number); uint num2 = DoubleHelper.Exponent(num); ulong num3 = DoubleHelper.Mantissa(num); switch (num2) { case 2047u: value = 0.0; return false; case 0u: if (num3 == 0L) { num = 0.0; } break; } value = num; return true; } public unsafe static bool NumberBufferToDecimal(ref NumberBuffer number, ref decimal value) { MutableDecimal source = default(MutableDecimal); byte* ptr = number.UnsafeDigits; int num = number.Scale; if (*ptr == 0) { if (num > 0) { num = 0; } } else { if (num > 29) { return false; } while ((num > 0 || (*ptr != 0 && num > -28)) && (source.High < 429496729 || (source.High == 429496729 && (source.Mid < 2576980377u || (source.Mid == 2576980377u && (source.Low < 2576980377u || (source.Low == 2576980377u && *ptr <= 53))))))) { DecimalDecCalc.DecMul10(ref source); if (*ptr != 0) { DecimalDecCalc.DecAddInt32(ref source, (uint)(*(ptr++) - 48)); } num--; } if (*(ptr++) >= 53) { bool flag = true; if (*(ptr - 1) == 53 && *(ptr - 2) % 2 == 0) { int num2 = 20; while (*ptr == 48 && num2 != 0) { ptr++; num2--; } if (*ptr == 0 || num2 == 0) { flag = false; } } if (flag) { DecimalDecCalc.DecAddInt32(ref source, 1u); if ((source.High | source.Mid | source.Low) == 0) { source.High = 429496729u; source.Mid = 2576980377u; source.Low = 2576980378u; num++; } } } } if (num > 0) { return false; } if (num <= -29) { source.High = 0u; source.Low = 0u; source.Mid = 0u; source.Scale = 28; } else { source.Scale = -num; } source.IsNegative = number.IsNegative; value = Unsafe.As<MutableDecimal, decimal>(ref source); return true; } public static void DecimalToNumber(decimal value, ref NumberBuffer number) { ref MutableDecimal reference = ref Unsafe.As<decimal, MutableDecimal>(ref value); Span<byte> digits = number.Digits; number.IsNegative = reference.IsNegative; int num = 29; while ((reference.Mid != 0) | (reference.High != 0)) { uint num2 = DecimalDecCalc.DecDivMod1E9(ref reference); for (int i = 0; i < 9; i++) { digits[--num] = (byte)(num2 % 10 + 48); num2 /= 10; } } for (uint num3 = reference.Low; num3 != 0; num3 /= 10) { digits[--num] = (byte)(num3 % 10 + 48); } int num4 = 29 - num; number.Scale = num4 - reference.Scale; Span<byte> digits2 = number.Digits; int index = 0; while (--num4 >= 0) { digits2[index++] = digits[num++]; } digits2[index] = 0; } private static uint DigitsToInt(ReadOnlySpan<byte> digits, int count) { uint value; int bytesConsumed; bool flag = Utf8Parser.TryParse(digits.Slice(0, count), out value, out bytesConsumed, 'D'); return value; } private static ulong Mul32x32To64(uint a, uint b) { return (ulong)a * (ulong)b; } private static ulong Mul64Lossy(ulong a, ulong b, ref int pexp) { ulong num = Mul32x32To64((uint)(a >> 32), (uint)(b >> 32)) + (Mul32x32To64((uint)(a >> 32), (uint)b) >> 32) + (Mul32x32To64((uint)a, (uint)(b >> 32)) >> 32); if ((num & 0x8000000000000000uL) == 0L) { num <<= 1; pexp--; } return num; } private static int abs(int value) { if (value < 0) { return -value; } return value; } private unsafe static double NumberToDouble(ref NumberBuffer number) { ReadOnlySpan<byte> digits = number.Digits; int i = 0; int numDigits = number.NumDigits; int num = numDigits; for (; digits[i] == 48; i++) { num--; } if (num == 0) { return 0.0; } int num2 = Math.Min(num, 9); num -= num2; ulong num3 = DigitsToInt(digits, num2); if (num > 0) { num2 = Math.Min(num, 9); num -= num2; uint b = (uint)(s_rgval64Power10[num2 - 1] >> 64 - s_rgexp64Power10[num2 - 1]); num3 = Mul32x32To64((uint)num3, b) + DigitsToInt(digits.Slice(9), num2); } int num4 = number.Scale - (numDigits - num); int num5 = abs(num4); if (num5 >= 352) { ulong num6 = ((num4 > 0) ? 9218868437227405312uL : 0); if (number.IsNegative) { num6 |= 0x8000000000000000uL; } return *(double*)(&num6); } int pexp = 64; if ((num3 & 0xFFFFFFFF00000000uL) == 0L) { num3 <<= 32; pexp -= 32; } if ((num3 & 0xFFFF000000000000uL) == 0L) { num3 <<= 16; pexp -= 16; } if ((num3 & 0xFF00000000000000uL) == 0L) { num3 <<= 8; pexp -= 8; } if ((num3 & 0xF000000000000000uL) == 0L) { num3 <<= 4; pexp -= 4; } if ((num3 & 0xC000000000000000uL) == 0L) { num3 <<= 2; pexp -= 2; } if ((num3 & 0x8000000000000000uL) == 0L) { num3 <<= 1; pexp--; } int num7 = num5 & 0xF; if (num7 != 0) { int num8 = s_rgexp64Power10[num7 - 1]; pexp += ((num4 < 0) ? (-num8 + 1) : num8); ulong b2 = s_rgval64Power10[num7 + ((num4 < 0) ? 15 : 0) - 1]; num3 = Mul64Lossy(num3, b2, ref pexp); } num7 = num5 >> 4; if (num7 != 0) { int num9 = s_rgexp64Power10By16[num7 - 1]; pexp += ((num4 < 0) ? (-num9 + 1) : num9); ulong b3 = s_rgval64Power10By16[num7 + ((num4 < 0) ? 21 : 0) - 1]; num3 = Mul64Lossy(num3, b3, ref pexp); } if (((uint)(int)num3 & 0x400u) != 0) { ulong num10 = num3 + 1023 + (ulong)(((int)num3 >> 11) & 1); if (num10 < num3) { num10 = (num10 >> 1) | 0x8000000000000000uL; pexp++; } num3 = num10; } pexp += 1022; num3 = ((pexp <= 0) ? ((pexp == -52 && num3 >= 9223372036854775896uL) ? 1 : ((pexp > -52) ? (num3 >> -pexp + 11 + 1) : 0)) : ((pexp < 2047) ? ((ulong)((long)pexp << 52) + ((num3 >> 11) & 0xFFFFFFFFFFFFFL)) : 9218868437227405312uL)); if (number.IsNegative) { num3 |= 0x8000000000000000uL; } return *(double*)(&num3); } } internal ref struct NumberBuffer { public int Scale; public bool IsNegative; public const int BufferSize = 51; private byte _b0; private byte _b1; private byte _b2; private byte _b3; private byte _b4; private byte _b5; private byte _b6; private byte _b7; private byte _b8; private byte _b9; private byte _b10; private byte _b11; private byte _b12; private byte _b13; private byte _b14; private byte _b15; private byte _b16; private byte _b17; private byte _b18; private byte _b19; private byte _b20; private byte _b21; private byte _b22; private byte _b23; private byte _b24; private byte _b25; private byte _b26; private byte _b27; private byte _b28; private byte _b29; private byte _b30; private byte _b31; private byte _b32; private byte _b33; private byte _b34; private byte _b35; private byte _b36; private byte _b37; private byte _b38; private byte _b39; private byte _b40; private byte _b41; private byte _b42; private byte _b43; private byte _b44; private byte _b45; private byte _b46; private byte _b47; private byte _b48; private byte _b49; private byte _b50; public unsafe Span<byte> Digits => new Span<byte>(Unsafe.AsPointer(ref _b0), 51); public unsafe byte* UnsafeDigits => (byte*)Unsafe.AsPointer(ref _b0); public int NumDigits => Digits.IndexOf<byte>(0); [Conditional("DEBUG")] public void CheckConsistency() { } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('['); stringBuilder.Append('"'); Span<byte> digits = Digits; for (int i = 0; i < 51; i++) { byte b = digits[i]; if (b == 0) { break; } stringBuilder.Append((char)b); } stringBuilder.Append('"'); stringBuilder.Append(", Scale = " + Scale); stringBuilder.Append(", IsNegative = " + IsNegative); stringBuilder.Append(']'); return stringBuilder.ToString(); } } [DebuggerTypeProxy(typeof(System.MemoryDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly struct Memory<T> { private readonly object _object; private readonly int _index; private readonly int _length; private const int RemoveFlagsBitMask = int.MaxValue; public static Memory<T> Empty => default(Memory<T>); public int Length => _length & 0x7FFFFFFF; public bool IsEmpty => (_length & 0x7FFFFFFF) == 0; public Span<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Span<T> result; if (_index < 0) { result = ((MemoryManager<T>)_object).GetSpan(); return result.Slice(_index & 0x7FFFFFFF, _length); } if (typeof(T) == typeof(char) && _object is string text) { result = new Span<T>(Unsafe.As<Pinnable<T>>(text), MemoryExtensions.StringAdjustment, text.Length); return result.Slice(_index, _length); } if (_object != null) { return new Span<T>((T[])_object, _index, _length & 0x7FFFFFFF); } result = default(Span<T>); return result; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array) { if (array == null) { this = default(Memory<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } _object = array; _index = 0; _length = array.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(T[] array, int start) { if (array == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(Memory<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = array; _index = start; _length = array.Length - start; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(Memory<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = array; _index = start; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager<T> manager, int length) { if (length < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = manager; _index = int.MinValue; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager<T> manager, int start, int length) { if (length < 0 || start < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = manager; _index = start | int.MinValue; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(object obj, int start, int length) { _object = obj; _index = start; _length = length; } public static implicit operator Memory<T>(T[] array) { return new Memory<T>(array); } public static implicit operator Memory<T>(ArraySegment<T> segment) { return new Memory<T>(segment.Array, segment.Offset, segment.Count); } public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) { return Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory); } public override string ToString() { if (typeof(T) == typeof(char)) { if (!(_object is string text)) { return Span.ToString(); } return text.Substring(_index, _length & 0x7FFFFFFF); } return $"System.Memory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start) { int length = _length; int num = length & 0x7FFFFFFF; if ((uint)start > (uint)num) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new Memory<T>(_object, _index + start, length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start, int length) { int length2 = _length; int num = length2 & 0x7FFFFFFF; if ((uint)start > (uint)num || (uint)length > (uint)(num - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } return new Memory<T>(_object, _index + start, length | (length2 & int.MinValue)); } public void CopyTo(Memory<T> destination) { Span.CopyTo(destination.Span); } public bool TryCopyTo(Memory<T> destination) { return Span.TryCopyTo(destination.Span); } public unsafe MemoryHandle Pin() { if (_index < 0) { return ((MemoryManager<T>)_object).Pin(_index & 0x7FFFFFFF); } if (typeof(T) == typeof(char) && _object is string value) { GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned); void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer, handle); } if (_object is T[] array) { if (_length < 0) { void* pointer2 = Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetReference<T>(array)), _index); return new MemoryHandle(pointer2); } GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned); void* pointer3 = Unsafe.Add<T>((void*)handle2.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer3, handle2); } return default(MemoryHandle); } public T[] ToArray() { return Span.ToArray(); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is ReadOnlyMemory<T> readOnlyMemory) { return readOnlyMemory.Equals(this); } if (obj is Memory<T> other) { return Equals(other); } return false; } public bool Equals(Memory<T> other) { if (_object == other._object && _index == other._index) { return _length == other._length; } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { if (_object == null) { return 0; } int hashCode = _object.GetHashCode(); int index = _index; int hashCode2 = index.GetHashCode(); index = _length; return CombineHashCodes(hashCode, hashCode2, index.GetHashCode()); } private static int CombineHashCodes(int left, int right) { return ((left << 5) + left) ^ right; } private static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } } internal sealed class MemoryDebugView<T> { private readonly ReadOnlyMemory<T> _memory; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => _memory.ToArray(); public MemoryDebugView(Memory<T> memory) { _memory = memory; } public MemoryDebugView(ReadOnlyMemory<T> memory) { _memory = memory; } } public static class MemoryExtensions { internal static readonly IntPtr StringAdjustment = MeasureStringAdjustment(); public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span) { return span.TrimStart().TrimEnd(); } public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span) { int i; for (i = 0; i < span.Length && char.IsWhiteSpace(span[i]); i++) { } return span.Slice(i); } public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span) { int num = span.Length - 1; while (num >= 0 && char.IsWhiteSpace(span[num])) { num--; } return span.Slice(0, num + 1); } public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span, char trimChar) { return span.TrimStart(trimChar).TrimEnd(trimChar); } public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span, char trimChar) { int i; for (i = 0; i < span.Length && span[i] == trimChar; i++) { } return span.Slice(i); } public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span, char trimChar) { int num = span.Length - 1; while (num >= 0 && span[num] == trimChar) { num--; } return span.Slice(0, num + 1); } public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars) { return span.TrimStart(trimChars).TrimEnd(trimChars); } public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars) { if (trimChars.IsEmpty) { return span.TrimStart(); } int i; for (i = 0; i < span.Length; i++) { int num = 0; while (num < trimChars.Length) { if (span[i] != trimChars[num]) { num++; continue; } goto IL_003c; } break; IL_003c:; } return span.Slice(i); } public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars) { if (trimChars.IsEmpty) { return span.TrimEnd(); } int num; for (num = span.Length - 1; num >= 0; num--) { int num2 = 0; while (num2 < trimChars.Length) { if (span[num] != trimChars[num2]) { num2++; continue; } goto IL_0044; } break; IL_0044:; } return span.Slice(0, num + 1); } public static bool IsWhiteSpace(this ReadOnlySpan<char> span) { for (int i = 0; i < span.Length; i++) { if (!char.IsWhiteSpace(span[i])) { return false; } } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this Span<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this Span<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual<T>(this Span<T> span, ReadOnlySpan<T> other) where T : IEquatable<T> { int length = span.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), (NUInt)length * size); } return false; } if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length); } return false; } public static int SequenceCompareTo<T>(this Span<T> span, ReadOnlySpan<T> other) where T : IComparable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(other)), other.Length); } return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this Span<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this Span<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this Span<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this Span<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this Span<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this Span<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) where T : IEquatable<T> { int length = span.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), (NUInt)length * size); } return false; } if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int SequenceCompareTo<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) where T : IComparable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(other)), other.Length); } return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length * size); } return false; } if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length * size); } return false; } if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EndsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = span.Length; int length2 = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size); } return false; } if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EndsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = span.Length; int length2 = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size); } return false; } if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2); } return false; } public static void Reverse<T>(this Span<T> span) { ref T reference = ref MemoryMarshal.GetReference(span); int num = 0; int num2 = span.Length - 1; while (num < num2) { T val = Unsafe.Add(ref reference, num); Unsafe.Add(ref reference, num) = Unsafe.Add(ref reference, num2); Unsafe.Add(ref reference, num2) = val; num++; num2--; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this T[] array) { return new Span<T>(array); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this T[] array, int start, int length) { return new Span<T>(array, start, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this ArraySegment<T> segment) { return new Span<T>(segment.Array, segment.Offset, segment.Count); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this ArraySegment<T> segment, int start) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new Span<T>(segment.Array, segment.Offset + start, segment.Count - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this ArraySegment<T> segment, int start, int length) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } if ((uint)length > segment.Count - start) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length); } return new Span<T>(segment.Array, segment.Offset + start, length); } public static Memory<T> AsMemory<T>(this T[] array) { return new Memory<T>(array); } public static Memory<T> AsMemory<T>(this T[] array, int start) { return new Memory<T>(array, start); } public static Memory<T> AsMemory<T>(this T[] array, int start, int length) { return new Memory<T>(array, start, length); } public static Memory<T> AsMemory<T>(this ArraySegment<T> segment) { return new Memory<T>(segment.Array, segment.Offset, segment.Count); } public static Memory<T> AsMemory<T>(this ArraySegment<T> segment, int start) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new Memory<T>(segment.Array, segment.Offset + start, segment.Count - start); } public static Memory<T> AsMemory<T>(this ArraySegment<T> segment, int start, int length) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } if ((uint)length > segment.Count - start) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length); } return new Memory<T>(segment.Array, segment.Offset + start, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo<T>(this T[] source, Span<T> destination) { new ReadOnlySpan<T>(source).CopyTo(destination); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo<T>(this T[] source, Memory<T> destination) { source.CopyTo(destination.Span); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Overlaps<T>(this Span<T> span, ReadOnlySpan<T> other) { return ((ReadOnlySpan<T>)span).Overlaps(other); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Overlaps<T>(this Span<T> span, ReadOnlySpan<T> other, out int elementOffset) { return ((ReadOnlySpan<T>)span).Overlaps(other, out elementOffset); } public static bool Overlaps<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) { if (span.IsEmpty || other.IsEmpty) { return false; } IntPtr intPtr = Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other)); if (Unsafe.SizeOf<IntPtr>() == 4) { if ((uint)(int)intPtr >= (uint)(span.Length * Unsafe.SizeOf<T>())) { return (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf<T>())); } return true; } if ((ulong)(long)intPtr >= (ulong)((long)span.Length * (long)Unsafe.SizeOf<T>())) { return (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf<T>())); } return true; } public static bool Overlaps<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other, out int elementOffset) { if (span.IsEmpty || other.IsEmpty) { elementOffset = 0; return false; } IntPtr intPtr = Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other)); if (Unsafe.SizeOf<IntPtr>() == 4) { if ((uint)(int)intPtr < (uint)(span.Length * Unsafe.SizeOf<T>()) || (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf<T>()))) { if ((int)intPtr % Unsafe.SizeOf<T>() != 0) { System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); } elementOffset = (int)intPtr / Unsafe.SizeOf<T>(); return true; } elementOffset = 0; return false; } if ((ulong)(long)intPtr < (ulong)((long)span.Length * (long)Unsafe.SizeOf<T>()) || (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf<T>()))) { if ((long)intPtr % Unsafe.SizeOf<T>() != 0L) { System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); } elementOffset = (int)((long)intPtr / Unsafe.SizeOf<T>()); return true; } elementOffset = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T>(this Span<T> span, IComparable<T> comparable) { return span.BinarySearch<T, IComparable<T>>(comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparable>(this Span<T> span, TComparable comparable) where TComparable : IComparable<T> { return BinarySearch((ReadOnlySpan<T>)span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparer>(this Span<T> span, T value, TComparer comparer) where TComparer : IComparer<T> { return ((ReadOnlySpan<T>)span).BinarySearch(value, comparer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T>(this ReadOnlySpan<T> span, IComparable<T> comparable) { return MemoryExtensions.BinarySearch<T, IComparable<T>>(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparable>(this ReadOnlySpan<T> span, TComparable comparable) where TComparable : IComparable<T> { return System.SpanHelpers.BinarySearch(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparer>(this ReadOnlySpan<T> span, T value, TComparer comparer) where TComparer : IComparer<T> { if (comparer == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparer); } System.SpanHelpers.ComparerComparable<T, TComparer> comparable = new System.SpanHelpers.ComparerComparable<T, TComparer>(value, comparer); return BinarySearch(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsTypeComparableAsBytes<T>(out NUInt size) { if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte)) { size = (NUInt)1; return true; } if (typeof(T) == typeof(char) || typeof(T) == typeof(short) || typeof(T) == typeof(ushort)) { size = (NUInt)2; return true; } if (typeof(T) == typeof(int) || typeof(T) == typeof(uint)) { size = (NUInt)4; return true; } if (typeof(T) == typeof(long) || typeof(T) == typeof(ulong)) { size = (NUInt)8; return true; } size = default(NUInt); return false; } public static Span<T> AsSpan<T>(this T[] array, int start) { return Span<T>.Create(array, start); } public static bool Contains(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { return span.IndexOf(value, comparisonType) >= 0; } public static bool Equals(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.Ordinal: return span.SequenceEqual(other); case StringComparison.OrdinalIgnoreCase: if (span.Length != other.Length) { return false; } return EqualsOrdinalIgnoreCase(span, other); default: return span.ToString().Equals(other.ToString(), comparisonType); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool EqualsOrdinalIgnoreCase(ReadOnlySpan<char> span, ReadOnlySpan<char> other) { if (other.Length == 0) { return true; } return CompareToOrdinalIgnoreCase(span, other) == 0; } public static int CompareTo(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType) { return comparisonType switch { StringComparison.Ordinal => span.SequenceCompareTo(other), StringComparison.OrdinalIgnoreCase => CompareToOrdinalIgnoreCase(span, other), _ => string.Compare(span.ToString(), other.ToString(), comparisonType), }; } private unsafe static int CompareToOrdinalIgnoreCase(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB) { int num = Math.Min(strA.Length, strB.Length); int num2 = num; fixed (char* ptr = &MemoryMarshal.GetReference(strA)) { fixed (char* ptr3 = &MemoryMarshal.GetReference(strB)) { char* ptr2 = ptr; char* ptr4 = ptr3; while (num != 0 && *ptr2 <= '\u007f' && *ptr4 <= '\u007f') { int num3 = *ptr2; int num4 = *ptr4; if (num3 == num4) { ptr2++; ptr4++; num--; continue; } if ((uint)(num3 - 97) <= 25u) { num3 -= 32; } if ((uint)(num4 - 97) <= 25u) { num4 -= 32; } if (num3 != num4) { return num3 - num4; } ptr2++; ptr4++; num--; } if (num == 0) { return strA.Length - strB.Length; } num2 -= num; return string.Compare(strA.Slice(num2).ToString(), strB.Slice(num2).ToString(), StringComparison.OrdinalIgnoreCase); } } } public static int IndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { if (comparisonType == StringComparison.Ordinal) { return span.IndexOf(value); } return span.ToString().IndexOf(value.ToString(), comparisonType); } public static int ToLower(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture) { if (culture == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture); } if (destination.Length < source.Length) { return -1; } string text = source.ToString(); string text2 = text.ToLower(culture); AsSpan(text2).CopyTo(destination); return source.Length; } public static int ToLowerInvariant(this ReadOnlySpan<char> source, Span<char> destination) { return source.ToLower(destination, CultureInfo.InvariantCulture); } public static int ToUpper(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture) { if (culture == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture); } if (destination.Length < source.Length) { return -1; } string text = source.ToString(); string text2 = text.ToUpper(culture); AsSpan(text2).CopyTo(destination); return source.Length; } public static int ToUpperInvariant(this ReadOnlySpan<char> source, Span<char> destination) { return source.ToUpper(destination, CultureInfo.InvariantCulture); } public static bool EndsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.Ordinal: return span.EndsWith(value); case StringComparison.OrdinalIgnoreCase: if (value.Length <= span.Length) { return EqualsOrdinalIgnoreCase(span.Slice(span.Length - value.Length), value); } return false; default: { string text = span.ToString(); string value2 = value.ToString(); return text.EndsWith(value2, comparisonType); } } } public static bool StartsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.Ordinal: return span.StartsWith(value); case StringComparison.OrdinalIgnoreCase: if (value.Length <= span.Length) { return EqualsOrdinalIgnoreCase(span.Slice(0, value.Length), value); } return false; default: { string text = span.ToString(); string value2 = value.ToString(); return text.StartsWith(value2, comparisonType); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text) { if (text == null) { return default(ReadOnlySpan<char>); } return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), StringAdjustment, text.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text, int start) { if (text == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlySpan<char>); } if ((uint)start > (uint)text.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), StringAdjustment + start * 2, text.Length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text, int start, int length) { if (text == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlySpan<char>); } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), StringAdjustment + start * 2, length); } public static ReadOnlyMemory<char> AsMemory(this string text) { if (text == null) { return default(ReadOnlyMemory<char>); } return new ReadOnlyMemory<char>(text, 0, text.Length); } public static ReadOnlyMemory<char> AsMemory(this string text, int start) { if (text == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlyMemory<char>); } if ((uint)start > (uint)text.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<char>(text, start, text.Length - start); } public static ReadOnlyMemory<char> AsMemory(this string text, int start, int length) { if (text == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlyMemory<char>); } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<char>(text, start, length); } private unsafe static IntPtr MeasureStringAdjustment() { string text = "a"; fixed (char* source = text) { return Unsafe.ByteOffset(ref Unsafe.As<Pinnable<char>>(text).Data, ref Unsafe.AsRef<char>(source)); } } } [DebuggerTypeProxy(typeof(System.MemoryDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly struct ReadOnlyMemory<T> { private readonly object _object; private readonly int _index; private readonly int _length; internal const int RemoveFlagsBitMask = int.MaxValue; public static ReadOnlyMemory<T> Empty => default(ReadOnlyMemory<T>); public int Length => _length & 0x7FFFFFFF; public bool IsEmpty => (_length & 0x7FFFFFFF) == 0; public ReadOnlySpan<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_index < 0) { return ((MemoryManager<T>)_object).GetSpan().Slice(_index & 0x7FFFFFFF, _length); } ReadOnlySpan<T> result; if (typeof(T) == typeof(char) && _object is string text) { result = new ReadOnlySpan<T>(Unsafe.As<Pinnable<T>>(text), MemoryExtensions.StringAdjustment, text.Length); return result.Slice(_index, _length); } if (_object != null) { return new ReadOnlySpan<T>((T[])_object, _index, _length & 0x7FFFFFFF); } result = default(ReadOnlySpan<T>); return result; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[] array) { if (array == null) { this = default(ReadOnlyMemory<T>); return; } _object = array; _index = 0; _length = array.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(ReadOnlyMemory<T>); return; } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = array; _index = start; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlyMemory(object obj, int start, int length) { _object = obj; _index = start; _length = length; } public static implicit operator ReadOnlyMemory<T>(T[] array) { return new ReadOnlyMemory<T>(array); } public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> segment) { return new ReadOnlyMemory<T>(segment.Array, segment.Offset, segment.Count); } public override string ToString() { if (typeof(T) == typeof(char)) { if (!(_object is string text)) { return Span.ToString(); } return text.Substring(_index, _length & 0x7FFFFFFF); } return $"System.ReadOnlyMemory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory<T> Slice(int start) { int length = _length; int num = length & 0x7FFFFFFF; if ((uint)start > (uint)num) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<T>(_object, _index + start, length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory<T> Slice(int start, int length) { int length2 = _length; int num = _length & 0x7FFFFFFF; if ((uint)start > (uint)num || (uint)length > (uint)(num - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<T>(_object, _index + start, length | (length2 & int.MinValue)); } public void CopyTo(Memory<T> destination) { Span.CopyTo(destination.Span); } public bool TryCopyTo(Memory<T> destination) { return Span.TryCopyTo(destination.Span); } public unsafe MemoryHandle Pin() { if (_index < 0) { return ((MemoryManager<T>)_object).Pin(_index & 0x7FFFFFFF); } if (typeof(T) == typeof(char) && _object is string value) { GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned); void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer, handle); } if (_object is T[] array) { if (_length < 0) { void* pointer2 = Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetReference<T>(array)), _index); return new MemoryHandle(pointer2); } GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned); void* pointer3 = Unsafe.Add<T>((void*)handle2.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer3, handle2); } return default(MemoryHandle); } public T[] ToArray() { return Span.ToArray(); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is ReadOnlyMemory<T> other) { return Equals(other); } if (obj is Memory<T> memory) { return Equals(memory); } return false; } public bool Equals(ReadOnlyMemory<T> other) { if (_object == other._object && _index == other._index) { return _length == other._length; } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { if (_object == null) { return 0; } int hashCode = _object.GetHashCode(); int index = _index; int hashCode2 = index.GetHashCode(); index = _length; return CombineHashCodes(hashCode, hashCode2, index.GetHashCode()); } private static int CombineHashCodes(int left, int right) { return ((left << 5) + left) ^ right; } private static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal object GetObjectStartLength(out int start, out int length) { start = _index; length = _length; return _object; } } [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly ref struct ReadOnlySpan<T> { public ref struct Enumerator { private readonly ReadOnlySpan<T> _span; private int _index; public ref readonly T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _span[_index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(ReadOnlySpan<T> span) { _span = span; _index = -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { int num = _index + 1; if (num < _span.Length) { _index = num; return true; } return false; } } private readonly Pinnable<T> _pinnable; private readonly IntPtr _byteOffset; private readonly int _length; public int Length => _length; public bool IsEmpty => _length == 0; public static ReadOnlySpan<T> Empty => default(ReadOnlySpan<T>); public unsafe ref readonly T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((uint)index >= (uint)_length) { System.ThrowHelper.ThrowIndexOutOfRangeException(); } if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.Add(ref Unsafe.AsRef<T>(byteOffset.ToPointer()), index); } return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset), index); } } internal Pinnable<T> Pinnable => _pinnable; internal IntPtr ByteOffset => _byteOffset; public static bool operator !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right) { return !(left == right); } [Obsolete("Equals() on ReadOnlySpan will always throw an exception. Use == instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { throw new NotSupportedException(System.SR.NotSupported_CannotCallEqualsOnSpan); } [Obsolete("GetHashCode() on ReadOnlySpan will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException(System.SR.NotSupported_CannotCallGetHashCodeOnSpan); } public static implicit operator ReadOnlySpan<T>(T[] array) { return new ReadOnlySpan<T>(array); } public static implicit operator ReadOnlySpan<T>(ArraySegment<T> segment) { return new ReadOnlySpan<T>(segment.Array, segment.Offset, segment.Count); } public Enumerator GetEnumerator() { return new Enumerator(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[] array) { if (array == null) { this = default(ReadOnlySpan<T>); return; } _length = array.Length; _pinnable = Unsafe.As<Pinnable<T>>(array); _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } this = default(ReadOnlySpan<T>); return; } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = Unsafe.As<Pinnable<T>>(array); _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public unsafe ReadOnlySpan(void* pointer, int length) { if (System.SpanHelpers.IsReferenceOrContainsReferences<T>()) { System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } if (length < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = null; _byteOffset = new IntPtr(pointer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlySpan(Pinnable<T> pinnable, IntPtr byteOffset, int length) { _length = length; _pinnable = pinnable; _byteOffset = byteOffset; } [EditorBrowsable(EditorBrowsableState.Never)] public unsafe ref readonly T GetPinnableReference() { if (_length != 0) { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); } return ref Unsafe.AsRef<T>(null); } public void CopyTo(Span<T> destination) { if (!TryCopyTo(destination)) { System.ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } public bool TryCopyTo(Span<T> destination) { int length = _length; int length2 = destination.Length; if (length == 0) { return true; } if ((uint)length > (uint)length2) { return false; } ref T src = ref DangerousGetPinnableReference(); System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length); return true; } public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right) { if (left._length == right._length) { return Unsafe.AreSame(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference()); } return false; } public unsafe override string ToString() { if (typeof(T) == typeof(char)) { if (_byteOffset == MemoryExtensions.StringAdjustment) { object obj = Unsafe.As<object>(_pinnable); if (obj is string text && _length == text.Length) { return text; } } fixed (char* value = &Unsafe.As<T, char>(ref DangerousGetPinnableReference())) { return new string(value, 0, _length); } } return $"System.ReadOnlySpan<{typeof(T).Name}>[{_length}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<T> Slice(int start) { if ((uint)start > (uint)_length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); int length = _length - start; return new ReadOnlySpan<T>(_pinnable, byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); return new ReadOnlySpan<T>(_pinnable, byteOffset, length); } public T[] ToArray() { if (_length == 0) { return System.SpanHelpers.PerTypeValues<T>.EmptyArray; } T[] array = new T[_length]; CopyTo(array); return array; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [EditorBrowsable(EditorBrowsableState.Never)] internal unsafe ref T DangerousGetPinnableReference() { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); } } [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly ref struct Span<T> { public ref struct Enumerator { private readonly Span<T> _span; private int _index; public ref T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _span[_index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(Span<T> span) { _span = span; _index = -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { int num = _index + 1; if (num < _span.Length) { _index = num; return true; } return false; } } private readonly Pinnable<T> _pinnable; private readonly IntPtr _byteOffset; private readonly int _length; public int Length => _length; public bool IsEmpty => _length == 0; public static Span<T> Empty => default(Span<T>); public unsafe ref T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((uint)index >= (uint)_length) { System.ThrowHelper.ThrowIndexOutOfRangeException(); } if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.Add(ref Unsafe.AsRef<T>(byteOffset.ToPointer()), index); } return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset), index); } } internal Pinnable<T> Pinnable => _pinnable; internal IntPtr ByteOffset => _byteOffset; public static bool operator !=(Span<T> left, Span<T> right) { return !(left == right); } [Obsolete("Equals() on Span will always throw an exception. Use == instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { throw new NotSupportedException(System.SR.NotSupported_CannotCallEqualsOnSpan); } [Obsolete("GetHashCode() on Span will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException(System.SR.NotSupported_CannotCallGetHashCodeOnSpan); } public static implicit operator Span<T>(T[] array) { return new Span<T>(array); } public static implicit operator Span<T>(ArraySegment<T> segment) { return new Span<T>(segment.Array, segment.Offset, segment.Count); } public Enumerator GetEnumerator() { return new Enumerator(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array) { if (array == null) { this = default(Span<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } _length = array.Length; _pinnable = Unsafe.As<Pinnable<T>>(array); _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Span<T> Create(T[] array, int start) { if (array == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(Span<T>); } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start); int length = array.Length - start; return new Span<T>(Unsafe.As<Pinnable<T>>(array), byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } this = default(Span<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = Unsafe.As<Pinnable<T>>(array); _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public unsafe Span(void* pointer, int length) { if (System.SpanHelpers.IsReferenceOrContainsReferences<T>()) { System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } if (length < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = null; _byteOffset = new IntPtr(pointer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Span(Pinnable<T> pinnable, IntPtr byteOffset, int length) { _length = length; _pinnable = pinnable; _byteOffset = byteOffset; } [EditorBrowsable(EditorBrowsableState.Never)] public unsafe ref T GetPinnableReference() { if (_length != 0) { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); } return ref Unsafe.AsRef<T>(null); } public unsafe void Clear() { int length = _length; if (length == 0) { return; } UIntPtr byteLength = (UIntPtr)(ulong)((uint)length * Unsafe.SizeOf<T>()); if ((Unsafe.SizeOf<T>() & (sizeof(IntPtr) - 1)) != 0) { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; byte* ptr = (byte*)byteOffset.ToPointer(); System.SpanHelpers.ClearLessThanPointerSized(ptr, byteLength); } else { System.SpanHelpers.ClearLessThanPointerSized(ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset)), byteLength); } } else if (System.SpanHelpers.IsReferenceOrContainsReferences<T>()) { UIntPtr pointerSizeLength = (UIntPtr)(ulong)(length * Unsafe.SizeOf<T>() / sizeof(IntPtr)); System.SpanHelpers.ClearPointerSizedWithReferences(ref Unsafe.As<T, IntPtr>(ref DangerousGetPinnableReference()), pointerSizeLength); } else { System.SpanHelpers.ClearPointerSizedWithoutReferences(ref Unsafe.As<T, byte>(ref DangerousGetPinnableReference()), byteLength); } } public unsafe void Fill(T value) { int length = _length; if (length == 0) { return; } if (Unsafe.SizeOf<T>() == 1) { byte value2 = Unsafe.As<T, byte>(ref value); if (_pinnable == null) { IntPtr byteOffset = _byteOffset; Unsafe.InitBlockUnaligned(byteOffset.ToPointer(), value2, (uint)length); } else { Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset)), value2, (uint)length); } return; } ref T source = ref DangerousGetPinnableReference(); int i; for (i = 0; i < (length & -8); i += 8) { Unsafe.Add(ref source, i) = value; Unsafe.Add(ref source, i + 1) = value; Unsafe.Add(ref source, i + 2) = value; Unsafe.Add(ref source, i + 3) = value; Unsafe.Add(ref source, i + 4) = value; Unsafe.Add(ref source, i + 5) = value; Unsafe.Add(ref source, i + 6) = value; Unsafe.Add(ref source, i + 7) = value; } if (i < (length & -4)) { Unsafe.Add(ref source, i) = value; Unsafe.Add(ref source, i + 1) = value; Unsafe.Add(ref source, i + 2) = value; Unsafe.Add(ref source, i + 3) = value; i += 4; } for (; i < length; i++) { Unsafe.Add(ref source, i) = value; } } public void CopyTo(Span<T> destination) { if (!TryCopyTo(destination)) { System.ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } public bool TryCopyTo(Span<T> destination) { int length = _length; int length2 = destination._length; if (length == 0) { return true; } if ((uint)length > (uint)length2) { return false; } ref T src = ref DangerousGetPinnableReference(); System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length); return true; } public static bool operator ==(Span<T> left, Span<T> right) { if (left._length == right._length) { return Unsafe.AreSame(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference()); } return false; } public static implicit operator ReadOnlySpan<T>(Span<T> span) { return new ReadOnlySpan<T>(span._pinnable, span._byteOffset, span._length); } public unsafe override string ToString() { if (typeof(T) == typeof(char)) { fixed (char* value = &Unsafe.As<T, char>(ref DangerousGetPinnableReference())) { return new string(value, 0, _length); } } return $"System.Span<{typeof(T).Name}>[{_length}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start) { if ((uint)start > (uint)_length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); int length = _length - start; return new Span<T>(_pinnable, byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); return new Span<T>(_pinnable, byteOffset, length); } public T[] ToArray() { if (_length == 0) { return System.SpanHelpers.PerTypeValues<T>.EmptyArray; } T[] array = new T[_length]; CopyTo(array); return array; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [EditorBrowsable(EditorBrowsableState.Never)] internal unsafe ref T DangerousGetPinnableReference() { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); } } internal sealed class SpanDebugView<T> { private readonly T[] _array; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => _array; public SpanDebugView(Span<T> span) { _array = span.ToArray(); } public SpanDebugView(ReadOnlySpan<T> span) { _array = span.ToArray(); } } internal static class SpanHelpers { internal struct ComparerComparable<T, TComparer> : IComparable<T> where TComparer : IComparer<T> { private readonly T _value; private readonly TComparer _comparer; public ComparerComparable(T value, TComparer comparer) { _value = value; _comparer = comparer; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int CompareTo(T other) { return _comparer.Compare(_value, other); } } [StructLayout(LayoutKind.Sequential, Size = 64)] private struct Reg64 { } [StructLayout(LayoutKind.Sequential, Size = 32)] private struct Reg32 { } [StructLayout(LayoutKind.Sequential, Size = 16)] private struct Reg16 { } public static class PerTypeValues<T> { public static readonly bool IsReferenceOrContainsReferences = IsReferenceOrContainsReferencesCore(typeof(T)); public static readonly T[] EmptyArray = new T[0]; public static readonly IntPtr ArrayAdjustment = MeasureArrayAdjustment(); private static IntPtr MeasureArrayAdjustment() { T[] array = new T[1]; return Unsafe.ByteOffset(ref Unsafe.As<Pinnable<T>>(array).Data, ref array[0]); } } private const ulong XorPowerOfTwoToHighByte = 283686952306184uL; private const ulong XorPowerOfTwoToHighChar = 4295098372uL; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparable>(this ReadOnlySpan<T> span, TComparable comparable) where TComparable : IComparable<T> { if (comparable == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparable); } return BinarySearch(ref MemoryMarshal.GetReference(span), span.Length, comparable); } public static int BinarySearch<T, TComparable>(ref T spanStart, int length, TComparable comparable) where TComparable : IComparable<T> { int num = 0; int num2 = length - 1; while (num <= num2) { int num3 = num2 + num >>> 1; int num4 = comparable.CompareTo(Unsafe.Add(ref spanStart, num3)); if (num4 == 0) { return num3; } if (num4 > 0) { num = num3 + 1; } else { num2 = num3 - 1; } } return ~num; } public static int IndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } byte value2 = value; ref byte second = ref Unsafe.Add(ref value, 1); int num = valueLength - 1; int num2 = 0; while (true) { int num3 = searchSpaceLength - num2 - num; if (num3 <= 0) { break; } int num4 = IndexOf(ref Unsafe.Add(ref searchSpace, num2), value2, num3); if (num4 == -1) { break; } num2 += num4; if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num2 + 1), ref second, num)) { return num2; } num2++; } return -1; } public static int IndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } int num = -1; for (int i = 0; i < valueLength; i++) { int num2 = IndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); if ((uint)num2 < (uint)num) { num = num2; searchSpaceLength = num2; if (num == 0) { break; } } } return num; } public static int LastIndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } int num = -1; for (int i = 0; i < valueLength; i++) { int num2 = LastIndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); if (num2 > num) { num = num2; } } return num; } public unsafe static int IndexOf(ref byte searchSpace, byte value, int length) { IntPtr intPtr = (IntPtr)0; IntPtr intPtr2 = (IntPtr)length; if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2) { int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1); intPtr2 = (IntPtr)((Vector<byte>.Count - num) & (Vector<byte>.Count - 1)); } while (true) { if ((nuint)(void*)intPtr2 >= (nuint)8u) { intPtr2 -= 8; if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr)) { goto IL_0242; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1)) { goto IL_024a; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2)) { goto IL_0258; } if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 3)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 4)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 5)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 6)) { if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 7)) { break; } intPtr += 8; continue; } return (int)(void*)(intPtr + 6); } return (int)(void*)(intPtr + 5); } return (int)(void*)(intPtr + 4); } goto IL_0266; } if ((nuint)(void*)intPtr2 >= (nuint)4u) { intPtr2 -= 4; if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr)) { goto IL_0242; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1)) { goto IL_024a; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2)) { goto IL_0258; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 3)) { goto IL_0266; } intPtr += 4; } while ((void*)intPtr2 != null) { intPtr2 -= 1; if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr)) { intPtr += 1; continue; } goto IL_0242; } if (Vector.IsHardwareAccelerated && (int)(void*)intPtr < length) { intPtr2 = (IntPtr)((length - (int)(void*)intPtr) & ~(Vector<byte>.Count - 1)); Vector<byte> vector = GetVector(value); for (; (void*)intPtr2 > (void*)intPtr; intPtr += Vector<byte>.Count) { Vector<byte> vector2 = Vector.Equals(vector, Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, intPtr))); if (!Vector<byte>.Zero.Equals(vector2)) { return (int)(void*)intPtr + LocateFirstFoundByte(vector2); } } if ((int)(void*)intPtr < length) { intPtr2 = (IntPtr)(length - (int)(void*)intPtr); continue; } } return -1; IL_0266: return (int)(void*)(intPtr + 3); IL_0242: return (int)(void*)intPtr; IL_0258: return (int)(void*)(intPtr + 2); IL_024a: return (int)(void*)(intPtr + 1); } return (int)(void*)(intPtr + 7); } public static int LastIndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } byte value2 = value; ref byte second = ref Unsafe.Add(ref value, 1); int num = valueLength - 1; int num2 = 0; while (true) { int num3 = searchSpaceLength - num2 - num; if (num3 <= 0) { break; } int num4 = LastIndexOf(ref searchSpace, value2, num3); if (num4 == -1) { break; } if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num4 + 1), ref second, num)) { return num4; } num2 += num3 - num4; } return -1; } public unsafe static int LastIndexOf(ref byte searchSpace, byte value, int length) { IntPtr intPtr = (IntPtr)length; IntPtr intPtr2 = (IntPtr)length; if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2) { int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1); intPtr2 = (IntPtr)(((length & (Vector<byte>.Count - 1)) + num) & (Vector<byte>.Count - 1)); } while (true) { if ((nuint)(void*)intPtr2 >= (nuint)8u) { intPtr2 -= 8; intPtr -= 8; if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 7)) { break; } if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 6)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 5)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 4)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 3)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 2)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 1)) { if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr)) { continue; } goto IL_0254; } goto IL_025c; } goto IL_026a; } goto IL_0278; } return (int)(void*)(intPtr + 4); } return (int)(void*)(intPtr + 5); } return (int)(void*)(intPtr + 6); } if ((nuint)(void*)intPtr2 >= (nuint)4u) { intPtr2 -= 4; intPtr -= 4; if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 3)) { goto IL_0278; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2)) { goto IL_026a; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1)) { goto IL_025c; } if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr)) { goto IL_0254; } } while ((void*)intPtr2 != null) { intPtr2 -= 1; intPtr -= 1; if (value !
BepInEx/plugins/elytraking-Dread/System.Numerics.Vectors.dll
Decompiled a week ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Diagnostics; using System.Globalization; using System.Numerics; using System.Numerics.Hashing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using FxResources.System.Numerics.Vectors; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Numerics.Vectors")] [assembly: AssemblyDescription("System.Numerics.Vectors")] [assembly: AssemblyDefaultAlias("System.Numerics.Vectors")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.25519.03")] [assembly: AssemblyInformationalVersion("4.6.25519.03 built by: dlab-DDVSOWINAGE013. Commit Hash: 8321c729934c0f8be754953439b88e6e1c120c24")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.1.3.0")] [assembly: TypeForwardedTo(typeof(Matrix3x2))] [assembly: TypeForwardedTo(typeof(Matrix4x4))] [assembly: TypeForwardedTo(typeof(Plane))] [assembly: TypeForwardedTo(typeof(Quaternion))] [assembly: TypeForwardedTo(typeof(Vector2))] [assembly: TypeForwardedTo(typeof(Vector3))] [assembly: TypeForwardedTo(typeof(Vector4))] [module: UnverifiableCode] namespace FxResources.System.Numerics.Vectors { internal static class SR { } } namespace System { internal static class MathF { public const float PI = 3.1415927f; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Abs(float x) { return Math.Abs(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Acos(float x) { return (float)Math.Acos(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Cos(float x) { return (float)Math.Cos(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float IEEERemainder(float x, float y) { return (float)Math.IEEERemainder(x, y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sin(float x) { return (float)Math.Sin(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sqrt(float x) { return (float)Math.Sqrt(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Tan(float x) { return (float)Math.Tan(x); } } internal static class SR { private static ResourceManager s_resourceManager; private const string s_resourcesName = "FxResources.System.Numerics.Vectors.SR"; private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); internal static string Arg_ArgumentOutOfRangeException => GetResourceString("Arg_ArgumentOutOfRangeException", null); internal static string Arg_ElementsInSourceIsGreaterThanDestination => GetResourceString("Arg_ElementsInSourceIsGreaterThanDestination", null); internal static string Arg_NullArgumentNullRef => GetResourceString("Arg_NullArgumentNullRef", null); internal static string Arg_TypeNotSupported => GetResourceString("Arg_TypeNotSupported", null); internal static Type ResourceType => typeof(SR); [MethodImpl(MethodImplOptions.NoInlining)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString) { string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal)) { return defaultString; } return text; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } } } namespace System.Numerics { internal class ConstantHelper { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte GetByteWithAllBitsSet() { byte result = 0; result = byte.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static sbyte GetSByteWithAllBitsSet() { sbyte result = 0; result = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ushort GetUInt16WithAllBitsSet() { ushort result = 0; result = ushort.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short GetInt16WithAllBitsSet() { short result = 0; result = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint GetUInt32WithAllBitsSet() { uint result = 0u; result = uint.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetInt32WithAllBitsSet() { int result = 0; result = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong GetUInt64WithAllBitsSet() { ulong result = 0uL; result = ulong.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long GetInt64WithAllBitsSet() { long result = 0L; result = -1L; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static float GetSingleWithAllBitsSet() { float result = 0f; *(int*)(&result) = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static double GetDoubleWithAllBitsSet() { double result = 0.0; *(long*)(&result) = -1L; return result; } } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property)] internal class JitIntrinsicAttribute : Attribute { } [StructLayout(LayoutKind.Explicit)] internal struct Register { [FieldOffset(0)] internal byte byte_0; [FieldOffset(1)] internal byte byte_1; [FieldOffset(2)] internal byte byte_2; [FieldOffset(3)] internal byte byte_3; [FieldOffset(4)] internal byte byte_4; [FieldOffset(5)] internal byte byte_5; [FieldOffset(6)] internal byte byte_6; [FieldOffset(7)] internal byte byte_7; [FieldOffset(8)] internal byte byte_8; [FieldOffset(9)] internal byte byte_9; [FieldOffset(10)] internal byte byte_10; [FieldOffset(11)] internal byte byte_11; [FieldOffset(12)] internal byte byte_12; [FieldOffset(13)] internal byte byte_13; [FieldOffset(14)] internal byte byte_14; [FieldOffset(15)] internal byte byte_15; [FieldOffset(0)] internal sbyte sbyte_0; [FieldOffset(1)] internal sbyte sbyte_1; [FieldOffset(2)] internal sbyte sbyte_2; [FieldOffset(3)] internal sbyte sbyte_3; [FieldOffset(4)] internal sbyte sbyte_4; [FieldOffset(5)] internal sbyte sbyte_5; [FieldOffset(6)] internal sbyte sbyte_6; [FieldOffset(7)] internal sbyte sbyte_7; [FieldOffset(8)] internal sbyte sbyte_8; [FieldOffset(9)] internal sbyte sbyte_9; [FieldOffset(10)] internal sbyte sbyte_10; [FieldOffset(11)] internal sbyte sbyte_11; [FieldOffset(12)] internal sbyte sbyte_12; [FieldOffset(13)] internal sbyte sbyte_13; [FieldOffset(14)] internal sbyte sbyte_14; [FieldOffset(15)] internal sbyte sbyte_15; [FieldOffset(0)] internal ushort uint16_0; [FieldOffset(2)] internal ushort uint16_1; [FieldOffset(4)] internal ushort uint16_2; [FieldOffset(6)] internal ushort uint16_3; [FieldOffset(8)] internal ushort uint16_4; [FieldOffset(10)] internal ushort uint16_5; [FieldOffset(12)] internal ushort uint16_6; [FieldOffset(14)] internal ushort uint16_7; [FieldOffset(0)] internal short int16_0; [FieldOffset(2)] internal short int16_1; [FieldOffset(4)] internal short int16_2; [FieldOffset(6)] internal short int16_3; [FieldOffset(8)] internal short int16_4; [FieldOffset(10)] internal short int16_5; [FieldOffset(12)] internal short int16_6; [FieldOffset(14)] internal short int16_7; [FieldOffset(0)] internal uint uint32_0; [FieldOffset(4)] internal uint uint32_1; [FieldOffset(8)] internal uint uint32_2; [FieldOffset(12)] internal uint uint32_3; [FieldOffset(0)] internal int int32_0; [FieldOffset(4)] internal int int32_1; [FieldOffset(8)] internal int int32_2; [FieldOffset(12)] internal int int32_3; [FieldOffset(0)] internal ulong uint64_0; [FieldOffset(8)] internal ulong uint64_1; [FieldOffset(0)] internal long int64_0; [FieldOffset(8)] internal long int64_1; [FieldOffset(0)] internal float single_0; [FieldOffset(4)] internal float single_1; [FieldOffset(8)] internal float single_2; [FieldOffset(12)] internal float single_3; [FieldOffset(0)] internal double double_0; [FieldOffset(8)] internal double double_1; } public struct Vector<T> : IEquatable<Vector<T>>, IFormattable where T : struct { private struct VectorSizeHelper { internal Vector<T> _placeholder; internal byte _byte; } private System.Numerics.Register register; private static readonly int s_count = InitializeCount(); private static readonly Vector<T> zero = new Vector<T>(GetZeroValue()); private static readonly Vector<T> one = new Vector<T>(GetOneValue()); private static readonly Vector<T> allOnes = new Vector<T>(GetAllBitsSetValue()); [JitIntrinsic] public static int Count => s_count; [JitIntrinsic] public static Vector<T> Zero => zero; [JitIntrinsic] public static Vector<T> One => one; internal static Vector<T> AllOnes => allOnes; [JitIntrinsic] public unsafe T this[int index] { get { if (index >= Count || index < 0) { throw new IndexOutOfRangeException(System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, index)); } if (typeof(T) == typeof(byte)) { fixed (byte* ptr = ®ister.byte_0) { return (T)(object)ptr[index]; } } if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = ®ister.sbyte_0) { return (T)(object)ptr2[index]; } } if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = ®ister.uint16_0) { return (T)(object)ptr3[index]; } } if (typeof(T) == typeof(short)) { fixed (short* ptr4 = ®ister.int16_0) { return (T)(object)ptr4[index]; } } if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = ®ister.uint32_0) { return (T)(object)ptr5[index]; } } if (typeof(T) == typeof(int)) { fixed (int* ptr6 = ®ister.int32_0) { return (T)(object)ptr6[index]; } } if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = ®ister.uint64_0) { return (T)(object)ptr7[index]; } } if (typeof(T) == typeof(long)) { fixed (long* ptr8 = ®ister.int64_0) { return (T)(object)ptr8[index]; } } if (typeof(T) == typeof(float)) { fixed (float* ptr9 = ®ister.single_0) { return (T)(object)ptr9[index]; } } if (typeof(T) == typeof(double)) { fixed (double* ptr10 = ®ister.double_0) { return (T)(object)ptr10[index]; } } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } } private unsafe static int InitializeCount() { VectorSizeHelper vectorSizeHelper = default(VectorSizeHelper); byte* ptr = &vectorSizeHelper._placeholder.register.byte_0; byte* ptr2 = &vectorSizeHelper._byte; int num = (int)(ptr2 - ptr); int num2 = -1; if (typeof(T) == typeof(byte)) { num2 = 1; } else if (typeof(T) == typeof(sbyte)) { num2 = 1; } else if (typeof(T) == typeof(ushort)) { num2 = 2; } else if (typeof(T) == typeof(short)) { num2 = 2; } else if (typeof(T) == typeof(uint)) { num2 = 4; } else if (typeof(T) == typeof(int)) { num2 = 4; } else if (typeof(T) == typeof(ulong)) { num2 = 8; } else if (typeof(T) == typeof(long)) { num2 = 8; } else if (typeof(T) == typeof(float)) { num2 = 4; } else { if (!(typeof(T) == typeof(double))) { throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } num2 = 8; } return num / num2; } [JitIntrinsic] public unsafe Vector(T value) { this = default(Vector<T>); if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { fixed (byte* ptr = ®ister.byte_0) { for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)value; } } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = ®ister.sbyte_0) { for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)value; } } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = ®ister.uint16_0) { for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)value; } } } else if (typeof(T) == typeof(short)) { fixed (short* ptr4 = ®ister.int16_0) { for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)value; } } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = ®ister.uint32_0) { for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)value; } } } else if (typeof(T) == typeof(int)) { fixed (int* ptr6 = ®ister.int32_0) { for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)value; } } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = ®ister.uint64_0) { for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)value; } } } else if (typeof(T) == typeof(long)) { fixed (long* ptr8 = ®ister.int64_0) { for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)value; } } } else if (typeof(T) == typeof(float)) { fixed (float* ptr9 = ®ister.single_0) { for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)value; } } } else { if (!(typeof(T) == typeof(double))) { return; } fixed (double* ptr10 = ®ister.double_0) { for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)value; } } } } else if (typeof(T) == typeof(byte)) { register.byte_0 = (byte)(object)value; register.byte_1 = (byte)(object)value; register.byte_2 = (byte)(object)value; register.byte_3 = (byte)(object)value; register.byte_4 = (byte)(object)value; register.byte_5 = (byte)(object)value; register.byte_6 = (byte)(object)value; register.byte_7 = (byte)(object)value; register.byte_8 = (byte)(object)value; register.byte_9 = (byte)(object)value; register.byte_10 = (byte)(object)value; register.byte_11 = (byte)(object)value; register.byte_12 = (byte)(object)value; register.byte_13 = (byte)(object)value; register.byte_14 = (byte)(object)value; register.byte_15 = (byte)(object)value; } else if (typeof(T) == typeof(sbyte)) { register.sbyte_0 = (sbyte)(object)value; register.sbyte_1 = (sbyte)(object)value; register.sbyte_2 = (sbyte)(object)value; register.sbyte_3 = (sbyte)(object)value; register.sbyte_4 = (sbyte)(object)value; register.sbyte_5 = (sbyte)(object)value; register.sbyte_6 = (sbyte)(object)value; register.sbyte_7 = (sbyte)(object)value; register.sbyte_8 = (sbyte)(object)value; register.sbyte_9 = (sbyte)(object)value; register.sbyte_10 = (sbyte)(object)value; register.sbyte_11 = (sbyte)(object)value; register.sbyte_12 = (sbyte)(object)value; register.sbyte_13 = (sbyte)(object)value; register.sbyte_14 = (sbyte)(object)value; register.sbyte_15 = (sbyte)(object)value; } else if (typeof(T) == typeof(ushort)) { register.uint16_0 = (ushort)(object)value; register.uint16_1 = (ushort)(object)value; register.uint16_2 = (ushort)(object)value; register.uint16_3 = (ushort)(object)value; register.uint16_4 = (ushort)(object)value; register.uint16_5 = (ushort)(object)value; register.uint16_6 = (ushort)(object)value; register.uint16_7 = (ushort)(object)value; } else if (typeof(T) == typeof(short)) { register.int16_0 = (short)(object)value; register.int16_1 = (short)(object)value; register.int16_2 = (short)(object)value; register.int16_3 = (short)(object)value; register.int16_4 = (short)(object)value; register.int16_5 = (short)(object)value; register.int16_6 = (short)(object)value; register.int16_7 = (short)(object)value; } else if (typeof(T) == typeof(uint)) { register.uint32_0 = (uint)(object)value; register.uint32_1 = (uint)(object)value; register.uint32_2 = (uint)(object)value; register.uint32_3 = (uint)(object)value; } else if (typeof(T) == typeof(int)) { register.int32_0 = (int)(object)value; register.int32_1 = (int)(object)value; register.int32_2 = (int)(object)value; register.int32_3 = (int)(object)value; } else if (typeof(T) == typeof(ulong)) { register.uint64_0 = (ulong)(object)value; register.uint64_1 = (ulong)(object)value; } else if (typeof(T) == typeof(long)) { register.int64_0 = (long)(object)value; register.int64_1 = (long)(object)value; } else if (typeof(T) == typeof(float)) { register.single_0 = (float)(object)value; register.single_1 = (float)(object)value; register.single_2 = (float)(object)value; register.single_3 = (float)(object)value; } else if (typeof(T) == typeof(double)) { register.double_0 = (double)(object)value; register.double_1 = (double)(object)value; } } [JitIntrinsic] public Vector(T[] values) : this(values, 0) { } public unsafe Vector(T[] values, int index) { this = default(Vector<T>); if (values == null) { throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef); } if (index < 0 || values.Length - index < Count) { throw new IndexOutOfRangeException(); } if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { fixed (byte* ptr = ®ister.byte_0) { for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)values[i + index]; } } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = ®ister.sbyte_0) { for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)values[j + index]; } } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = ®ister.uint16_0) { for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)values[k + index]; } } } else if (typeof(T) == typeof(short)) { fixed (short* ptr4 = ®ister.int16_0) { for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)values[l + index]; } } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = ®ister.uint32_0) { for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)values[m + index]; } } } else if (typeof(T) == typeof(int)) { fixed (int* ptr6 = ®ister.int32_0) { for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)values[n + index]; } } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = ®ister.uint64_0) { for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)values[num + index]; } } } else if (typeof(T) == typeof(long)) { fixed (long* ptr8 = ®ister.int64_0) { for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)values[num2 + index]; } } } else if (typeof(T) == typeof(float)) { fixed (float* ptr9 = ®ister.single_0) { for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)values[num3 + index]; } } } else { if (!(typeof(T) == typeof(double))) { return; } fixed (double* ptr10 = ®ister.double_0) { for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)values[num4 + index]; } } } } else if (typeof(T) == typeof(byte)) { fixed (byte* ptr11 = ®ister.byte_0) { *ptr11 = (byte)(object)values[index]; ptr11[1] = (byte)(object)values[1 + index]; ptr11[2] = (byte)(object)values[2 + index]; ptr11[3] = (byte)(object)values[3 + index]; ptr11[4] = (byte)(object)values[4 + index]; ptr11[5] = (byte)(object)values[5 + index]; ptr11[6] = (byte)(object)values[6 + index]; ptr11[7] = (byte)(object)values[7 + index]; ptr11[8] = (byte)(object)values[8 + index]; ptr11[9] = (byte)(object)values[9 + index]; ptr11[10] = (byte)(object)values[10 + index]; ptr11[11] = (byte)(object)values[11 + index]; ptr11[12] = (byte)(object)values[12 + index]; ptr11[13] = (byte)(object)values[13 + index]; ptr11[14] = (byte)(object)values[14 + index]; ptr11[15] = (byte)(object)values[15 + index]; } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr12 = ®ister.sbyte_0) { *ptr12 = (sbyte)(object)values[index]; ptr12[1] = (sbyte)(object)values[1 + index]; ptr12[2] = (sbyte)(object)values[2 + index]; ptr12[3] = (sbyte)(object)values[3 + index]; ptr12[4] = (sbyte)(object)values[4 + index]; ptr12[5] = (sbyte)(object)values[5 + index]; ptr12[6] = (sbyte)(object)values[6 + index]; ptr12[7] = (sbyte)(object)values[7 + index]; ptr12[8] = (sbyte)(object)values[8 + index]; ptr12[9] = (sbyte)(object)values[9 + index]; ptr12[10] = (sbyte)(object)values[10 + index]; ptr12[11] = (sbyte)(object)values[11 + index]; ptr12[12] = (sbyte)(object)values[12 + index]; ptr12[13] = (sbyte)(object)values[13 + index]; ptr12[14] = (sbyte)(object)values[14 + index]; ptr12[15] = (sbyte)(object)values[15 + index]; } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr13 = ®ister.uint16_0) { *ptr13 = (ushort)(object)values[index]; ptr13[1] = (ushort)(object)values[1 + index]; ptr13[2] = (ushort)(object)values[2 + index]; ptr13[3] = (ushort)(object)values[3 + index]; ptr13[4] = (ushort)(object)values[4 + index]; ptr13[5] = (ushort)(object)values[5 + index]; ptr13[6] = (ushort)(object)values[6 + index]; ptr13[7] = (ushort)(object)values[7 + index]; } } else if (typeof(T) == typeof(short)) { fixed (short* ptr14 = ®ister.int16_0) { *ptr14 = (short)(object)values[index]; ptr14[1] = (short)(object)values[1 + index]; ptr14[2] = (short)(object)values[2 + index]; ptr14[3] = (short)(object)values[3 + index]; ptr14[4] = (short)(object)values[4 + index]; ptr14[5] = (short)(object)values[5 + index]; ptr14[6] = (short)(object)values[6 + index]; ptr14[7] = (short)(object)values[7 + index]; } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr15 = ®ister.uint32_0) { *ptr15 = (uint)(object)values[index]; ptr15[1] = (uint)(object)values[1 + index]; ptr15[2] = (uint)(object)values[2 + index]; ptr15[3] = (uint)(object)values[3 + index]; } } else if (typeof(T) == typeof(int)) { fixed (int* ptr16 = ®ister.int32_0) { *ptr16 = (int)(object)values[index]; ptr16[1] = (int)(object)values[1 + index]; ptr16[2] = (int)(object)values[2 + index]; ptr16[3] = (int)(object)values[3 + index]; } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr17 = ®ister.uint64_0) { *ptr17 = (ulong)(object)values[index]; ptr17[1] = (ulong)(object)values[1 + index]; } } else if (typeof(T) == typeof(long)) { fixed (long* ptr18 = ®ister.int64_0) { *ptr18 = (long)(object)values[index]; ptr18[1] = (long)(object)values[1 + index]; } } else if (typeof(T) == typeof(float)) { fixed (float* ptr19 = ®ister.single_0) { *ptr19 = (float)(object)values[index]; ptr19[1] = (float)(object)values[1 + index]; ptr19[2] = (float)(object)values[2 + index]; ptr19[3] = (float)(object)values[3 + index]; } } else if (typeof(T) == typeof(double)) { fixed (double* ptr20 = ®ister.double_0) { *ptr20 = (double)(object)values[index]; ptr20[1] = (double)(object)values[1 + index]; } } } internal unsafe Vector(void* dataPointer) : this(dataPointer, 0) { } internal unsafe Vector(void* dataPointer, int offset) { this = default(Vector<T>); if (typeof(T) == typeof(byte)) { byte* ptr = (byte*)dataPointer; ptr += offset; fixed (byte* ptr2 = ®ister.byte_0) { for (int i = 0; i < Count; i++) { ptr2[i] = ptr[i]; } } return; } if (typeof(T) == typeof(sbyte)) { sbyte* ptr3 = (sbyte*)dataPointer; ptr3 += offset; fixed (sbyte* ptr4 = ®ister.sbyte_0) { for (int j = 0; j < Count; j++) { ptr4[j] = ptr3[j]; } } return; } if (typeof(T) == typeof(ushort)) { ushort* ptr5 = (ushort*)dataPointer; ptr5 += offset; fixed (ushort* ptr6 = ®ister.uint16_0) { for (int k = 0; k < Count; k++) { ptr6[k] = ptr5[k]; } } return; } if (typeof(T) == typeof(short)) { short* ptr7 = (short*)dataPointer; ptr7 += offset; fixed (short* ptr8 = ®ister.int16_0) { for (int l = 0; l < Count; l++) { ptr8[l] = ptr7[l]; } } return; } if (typeof(T) == typeof(uint)) { uint* ptr9 = (uint*)dataPointer; ptr9 += offset; fixed (uint* ptr10 = ®ister.uint32_0) { for (int m = 0; m < Count; m++) { ptr10[m] = ptr9[m]; } } return; } if (typeof(T) == typeof(int)) { int* ptr11 = (int*)dataPointer; ptr11 += offset; fixed (int* ptr12 = ®ister.int32_0) { for (int n = 0; n < Count; n++) { ptr12[n] = ptr11[n]; } } return; } if (typeof(T) == typeof(ulong)) { ulong* ptr13 = (ulong*)dataPointer; ptr13 += offset; fixed (ulong* ptr14 = ®ister.uint64_0) { for (int num = 0; num < Count; num++) { ptr14[num] = ptr13[num]; } } return; } if (typeof(T) == typeof(long)) { long* ptr15 = (long*)dataPointer; ptr15 += offset; fixed (long* ptr16 = ®ister.int64_0) { for (int num2 = 0; num2 < Count; num2++) { ptr16[num2] = ptr15[num2]; } } return; } if (typeof(T) == typeof(float)) { float* ptr17 = (float*)dataPointer; ptr17 += offset; fixed (float* ptr18 = ®ister.single_0) { for (int num3 = 0; num3 < Count; num3++) { ptr18[num3] = ptr17[num3]; } } return; } if (typeof(T) == typeof(double)) { double* ptr19 = (double*)dataPointer; ptr19 += offset; fixed (double* ptr20 = ®ister.double_0) { for (int num4 = 0; num4 < Count; num4++) { ptr20[num4] = ptr19[num4]; } } return; } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } private Vector(ref System.Numerics.Register existingRegister) { register = existingRegister; } [JitIntrinsic] public void CopyTo(T[] destination) { CopyTo(destination, 0); } [JitIntrinsic] public unsafe void CopyTo(T[] destination, int startIndex) { if (destination == null) { throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef); } if (startIndex < 0 || startIndex >= destination.Length) { throw new ArgumentOutOfRangeException("startIndex", System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, startIndex)); } if (destination.Length - startIndex < Count) { throw new ArgumentException(System.SR.Format(System.SR.Arg_ElementsInSourceIsGreaterThanDestination, startIndex)); } if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { fixed (byte* ptr = (byte[])(object)destination) { for (int i = 0; i < Count; i++) { ptr[startIndex + i] = (byte)(object)this[i]; } } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = (sbyte[])(object)destination) { for (int j = 0; j < Count; j++) { ptr2[startIndex + j] = (sbyte)(object)this[j]; } } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = (ushort[])(object)destination) { for (int k = 0; k < Count; k++) { ptr3[startIndex + k] = (ushort)(object)this[k]; } } } else if (typeof(T) == typeof(short)) { fixed (short* ptr4 = (short[])(object)destination) { for (int l = 0; l < Count; l++) { ptr4[startIndex + l] = (short)(object)this[l]; } } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = (uint[])(object)destination) { for (int m = 0; m < Count; m++) { ptr5[startIndex + m] = (uint)(object)this[m]; } } } else if (typeof(T) == typeof(int)) { fixed (int* ptr6 = (int[])(object)destination) { for (int n = 0; n < Count; n++) { ptr6[startIndex + n] = (int)(object)this[n]; } } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = (ulong[])(object)destination) { for (int num = 0; num < Count; num++) { ptr7[startIndex + num] = (ulong)(object)this[num]; } } } else if (typeof(T) == typeof(long)) { fixed (long* ptr8 = (long[])(object)destination) { for (int num2 = 0; num2 < Count; num2++) { ptr8[startIndex + num2] = (long)(object)this[num2]; } } } else if (typeof(T) == typeof(float)) { fixed (float* ptr9 = (float[])(object)destination) { for (int num3 = 0; num3 < Count; num3++) { ptr9[startIndex + num3] = (float)(object)this[num3]; } } } else { if (!(typeof(T) == typeof(double))) { return; } fixed (double* ptr10 = (double[])(object)destination) { for (int num4 = 0; num4 < Count; num4++) { ptr10[startIndex + num4] = (double)(object)this[num4]; } } } } else if (typeof(T) == typeof(byte)) { fixed (byte* ptr11 = (byte[])(object)destination) { ptr11[startIndex] = register.byte_0; ptr11[startIndex + 1] = register.byte_1; ptr11[startIndex + 2] = register.byte_2; ptr11[startIndex + 3] = register.byte_3; ptr11[startIndex + 4] = register.byte_4; ptr11[startIndex + 5] = register.byte_5; ptr11[startIndex + 6] = register.byte_6; ptr11[startIndex + 7] = register.byte_7; ptr11[startIndex + 8] = register.byte_8; ptr11[startIndex + 9] = register.byte_9; ptr11[startIndex + 10] = register.byte_10; ptr11[startIndex + 11] = register.byte_11; ptr11[startIndex + 12] = register.byte_12; ptr11[startIndex + 13] = register.byte_13; ptr11[startIndex + 14] = register.byte_14; ptr11[startIndex + 15] = register.byte_15; } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr12 = (sbyte[])(object)destination) { ptr12[startIndex] = register.sbyte_0; ptr12[startIndex + 1] = register.sbyte_1; ptr12[startIndex + 2] = register.sbyte_2; ptr12[startIndex + 3] = register.sbyte_3; ptr12[startIndex + 4] = register.sbyte_4; ptr12[startIndex + 5] = register.sbyte_5; ptr12[startIndex + 6] = register.sbyte_6; ptr12[startIndex + 7] = register.sbyte_7; ptr12[startIndex + 8] = register.sbyte_8; ptr12[startIndex + 9] = register.sbyte_9; ptr12[startIndex + 10] = register.sbyte_10; ptr12[startIndex + 11] = register.sbyte_11; ptr12[startIndex + 12] = register.sbyte_12; ptr12[startIndex + 13] = register.sbyte_13; ptr12[startIndex + 14] = register.sbyte_14; ptr12[startIndex + 15] = register.sbyte_15; } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr13 = (ushort[])(object)destination) { ptr13[startIndex] = register.uint16_0; ptr13[startIndex + 1] = register.uint16_1; ptr13[startIndex + 2] = register.uint16_2; ptr13[startIndex + 3] = register.uint16_3; ptr13[startIndex + 4] = register.uint16_4; ptr13[startIndex + 5] = register.uint16_5; ptr13[startIndex + 6] = register.uint16_6; ptr13[startIndex + 7] = register.uint16_7; } } else if (typeof(T) == typeof(short)) { fixed (short* ptr14 = (short[])(object)destination) { ptr14[startIndex] = register.int16_0; ptr14[startIndex + 1] = register.int16_1; ptr14[startIndex + 2] = register.int16_2; ptr14[startIndex + 3] = register.int16_3; ptr14[startIndex + 4] = register.int16_4; ptr14[startIndex + 5] = register.int16_5; ptr14[startIndex + 6] = register.int16_6; ptr14[startIndex + 7] = register.int16_7; } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr15 = (uint[])(object)destination) { ptr15[startIndex] = register.uint32_0; ptr15[startIndex + 1] = register.uint32_1; ptr15[startIndex + 2] = register.uint32_2; ptr15[startIndex + 3] = register.uint32_3; } } else if (typeof(T) == typeof(int)) { fixed (int* ptr16 = (int[])(object)destination) { ptr16[startIndex] = register.int32_0; ptr16[startIndex + 1] = register.int32_1; ptr16[startIndex + 2] = register.int32_2; ptr16[startIndex + 3] = register.int32_3; } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr17 = (ulong[])(object)destination) { ptr17[startIndex] = register.uint64_0; ptr17[startIndex + 1] = register.uint64_1; } } else if (typeof(T) == typeof(long)) { fixed (long* ptr18 = (long[])(object)destination) { ptr18[startIndex] = register.int64_0; ptr18[startIndex + 1] = register.int64_1; } } else if (typeof(T) == typeof(float)) { fixed (float* ptr19 = (float[])(object)destination) { ptr19[startIndex] = register.single_0; ptr19[startIndex + 1] = register.single_1; ptr19[startIndex + 2] = register.single_2; ptr19[startIndex + 3] = register.single_3; } } else if (typeof(T) == typeof(double)) { fixed (double* ptr20 = (double[])(object)destination) { ptr20[startIndex] = register.double_0; ptr20[startIndex + 1] = register.double_1; } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { if (!(obj is Vector<T>)) { return false; } return Equals((Vector<T>)obj); } [JitIntrinsic] public bool Equals(Vector<T> other) { if (Vector.IsHardwareAccelerated) { for (int i = 0; i < Count; i++) { if (!ScalarEquals(this[i], other[i])) { return false; } } return true; } if (typeof(T) == typeof(byte)) { if (register.byte_0 == other.register.byte_0 && register.byte_1 == other.register.byte_1 && register.byte_2 == other.register.byte_2 && register.byte_3 == other.register.byte_3 && register.byte_4 == other.register.byte_4 && register.byte_5 == other.register.byte_5 && register.byte_6 == other.register.byte_6 && register.byte_7 == other.register.byte_7 && register.byte_8 == other.register.byte_8 && register.byte_9 == other.register.byte_9 && register.byte_10 == other.register.byte_10 && register.byte_11 == other.register.byte_11 && register.byte_12 == other.register.byte_12 && register.byte_13 == other.register.byte_13 && register.byte_14 == other.register.byte_14) { return register.byte_15 == other.register.byte_15; } return false; } if (typeof(T) == typeof(sbyte)) { if (register.sbyte_0 == other.register.sbyte_0 && register.sbyte_1 == other.register.sbyte_1 && register.sbyte_2 == other.register.sbyte_2 && register.sbyte_3 == other.register.sbyte_3 && register.sbyte_4 == other.register.sbyte_4 && register.sbyte_5 == other.register.sbyte_5 && register.sbyte_6 == other.register.sbyte_6 && register.sbyte_7 == other.register.sbyte_7 && register.sbyte_8 == other.register.sbyte_8 && register.sbyte_9 == other.register.sbyte_9 && register.sbyte_10 == other.register.sbyte_10 && register.sbyte_11 == other.register.sbyte_11 && register.sbyte_12 == other.register.sbyte_12 && register.sbyte_13 == other.register.sbyte_13 && register.sbyte_14 == other.register.sbyte_14) { return register.sbyte_15 == other.register.sbyte_15; } return false; } if (typeof(T) == typeof(ushort)) { if (register.uint16_0 == other.register.uint16_0 && register.uint16_1 == other.register.uint16_1 && register.uint16_2 == other.register.uint16_2 && register.uint16_3 == other.register.uint16_3 && register.uint16_4 == other.register.uint16_4 && register.uint16_5 == other.register.uint16_5 && register.uint16_6 == other.register.uint16_6) { return register.uint16_7 == other.register.uint16_7; } return false; } if (typeof(T) == typeof(short)) { if (register.int16_0 == other.register.int16_0 && register.int16_1 == other.register.int16_1 && register.int16_2 == other.register.int16_2 && register.int16_3 == other.register.int16_3 && register.int16_4 == other.register.int16_4 && register.int16_5 == other.register.int16_5 && register.int16_6 == other.register.int16_6) { return register.int16_7 == other.register.int16_7; } return false; } if (typeof(T) == typeof(uint)) { if (register.uint32_0 == other.register.uint32_0 && register.uint32_1 == other.register.uint32_1 && register.uint32_2 == other.register.uint32_2) { return register.uint32_3 == other.register.uint32_3; } return false; } if (typeof(T) == typeof(int)) { if (register.int32_0 == other.register.int32_0 && register.int32_1 == other.register.int32_1 && register.int32_2 == other.register.int32_2) { return register.int32_3 == other.register.int32_3; } return false; } if (typeof(T) == typeof(ulong)) { if (register.uint64_0 == other.register.uint64_0) { return register.uint64_1 == other.register.uint64_1; } return false; } if (typeof(T) == typeof(long)) { if (register.int64_0 == other.register.int64_0) { return register.int64_1 == other.register.int64_1; } return false; } if (typeof(T) == typeof(float)) { if (register.single_0 == other.register.single_0 && register.single_1 == other.register.single_1 && register.single_2 == other.register.single_2) { return register.single_3 == other.register.single_3; } return false; } if (typeof(T) == typeof(double)) { if (register.double_0 == other.register.double_0) { return register.double_1 == other.register.double_1; } return false; } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } public override int GetHashCode() { int num = 0; if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { for (int i = 0; i < Count; i++) { num = HashHelpers.Combine(num, ((byte)(object)this[i]).GetHashCode()); } return num; } if (typeof(T) == typeof(sbyte)) { for (int j = 0; j < Count; j++) { num = HashHelpers.Combine(num, ((sbyte)(object)this[j]).GetHashCode()); } return num; } if (typeof(T) == typeof(ushort)) { for (int k = 0; k < Count; k++) { num = HashHelpers.Combine(num, ((ushort)(object)this[k]).GetHashCode()); } return num; } if (typeof(T) == typeof(short)) { for (int l = 0; l < Count; l++) { num = HashHelpers.Combine(num, ((short)(object)this[l]).GetHashCode()); } return num; } if (typeof(T) == typeof(uint)) { for (int m = 0; m < Count; m++) { num = HashHelpers.Combine(num, ((uint)(object)this[m]).GetHashCode()); } return num; } if (typeof(T) == typeof(int)) { for (int n = 0; n < Count; n++) { num = HashHelpers.Combine(num, ((int)(object)this[n]).GetHashCode()); } return num; } if (typeof(T) == typeof(ulong)) { for (int num2 = 0; num2 < Count; num2++) { num = HashHelpers.Combine(num, ((ulong)(object)this[num2]).GetHashCode()); } return num; } if (typeof(T) == typeof(long)) { for (int num3 = 0; num3 < Count; num3++) { num = HashHelpers.Combine(num, ((long)(object)this[num3]).GetHashCode()); } return num; } if (typeof(T) == typeof(float)) { for (int num4 = 0; num4 < Count; num4++) { num = HashHelpers.Combine(num, ((float)(object)this[num4]).GetHashCode()); } return num; } if (typeof(T) == typeof(double)) { for (int num5 = 0; num5 < Count; num5++) { num = HashHelpers.Combine(num, ((double)(object)this[num5]).GetHashCode()); } return num; } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } if (typeof(T) == typeof(byte)) { num = HashHelpers.Combine(num, register.byte_0.GetHashCode()); num = HashHelpers.Combine(num, register.byte_1.GetHashCode()); num = HashHelpers.Combine(num, register.byte_2.GetHashCode()); num = HashHelpers.Combine(num, register.byte_3.GetHashCode()); num = HashHelpers.Combine(num, register.byte_4.GetHashCode()); num = HashHelpers.Combine(num, register.byte_5.GetHashCode()); num = HashHelpers.Combine(num, register.byte_6.GetHashCode()); num = HashHelpers.Combine(num, register.byte_7.GetHashCode()); num = HashHelpers.Combine(num, register.byte_8.GetHashCode()); num = HashHelpers.Combine(num, register.byte_9.GetHashCode()); num = HashHelpers.Combine(num, register.byte_10.GetHashCode()); num = HashHelpers.Combine(num, register.byte_11.GetHashCode()); num = HashHelpers.Combine(num, register.byte_12.GetHashCode()); num = HashHelpers.Combine(num, register.byte_13.GetHashCode()); num = HashHelpers.Combine(num, register.byte_14.GetHashCode()); return HashHelpers.Combine(num, register.byte_15.GetHashCode()); } if (typeof(T) == typeof(sbyte)) { num = HashHelpers.Combine(num, register.sbyte_0.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_1.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_2.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_3.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_4.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_5.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_6.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_7.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_8.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_9.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_10.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_11.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_12.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_13.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_14.GetHashCode()); return HashHelpers.Combine(num, register.sbyte_15.GetHashCode()); } if (typeof(T) == typeof(ushort)) { num = HashHelpers.Combine(num, register.uint16_0.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_1.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_2.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_3.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_4.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_5.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_6.GetHashCode()); return HashHelpers.Combine(num, register.uint16_7.GetHashCode()); } if (typeof(T) == typeof(short)) { num = HashHelpers.Combine(num, register.int16_0.GetHashCode()); num = HashHelpers.Combine(num, register.int16_1.GetHashCode()); num = HashHelpers.Combine(num, register.int16_2.GetHashCode()); num = HashHelpers.Combine(num, register.int16_3.GetHashCode()); num = HashHelpers.Combine(num, register.int16_4.GetHashCode()); num = HashHelpers.Combine(num, register.int16_5.GetHashCode()); num = HashHelpers.Combine(num, register.int16_6.GetHashCode()); return HashHelpers.Combine(num, register.int16_7.GetHashCode()); } if (typeof(T) == typeof(uint)) { num = HashHelpers.Combine(num, register.uint32_0.GetHashCode()); num = HashHelpers.Combine(num, register.uint32_1.GetHashCode()); num = HashHelpers.Combine(num, register.uint32_2.GetHashCode()); return HashHelpers.Combine(num, register.uint32_3.GetHashCode()); } if (typeof(T) == typeof(int)) { num = HashHelpers.Combine(num, register.int32_0.GetHashCode()); num = HashHelpers.Combine(num, register.int32_1.GetHashCode()); num = HashHelpers.Combine(num, register.int32_2.GetHashCode()); return HashHelpers.Combine(num, register.int32_3.GetHashCode()); } if (typeof(T) == typeof(ulong)) { num = HashHelpers.Combine(num, register.uint64_0.GetHashCode()); return HashHelpers.Combine(num, register.uint64_1.GetHashCode()); } if (typeof(T) == typeof(long)) { num = HashHelpers.Combine(num, register.int64_0.GetHashCode()); return HashHelpers.Combine(num, register.int64_1.GetHashCode()); } if (typeof(T) == typeof(float)) { num = HashHelpers.Combine(num, register.single_0.GetHashCode()); num = HashHelpers.Combine(num, register.single_1.GetHashCode()); num = HashHelpers.Combine(num, register.single_2.GetHashCode()); return HashHelpers.Combine(num, register.single_3.GetHashCode()); } if (typeof(T) == typeof(double)) { num = HashHelpers.Combine(num, register.double_0.GetHashCode()); return HashHelpers.Combine(num, register.double_1.GetHashCode()); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } public override string ToString() { return ToString("G", CultureInfo.CurrentCulture); } public string ToString(string format) { return ToString(format, CultureInfo.CurrentCulture); } public string ToString(string format, IFormatProvider formatProvider) { StringBuilder stringBuilder = new StringBuilder(); string numberGroupSeparator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; stringBuilder.Append('<'); for (int i = 0; i < Count - 1; i++) { stringBuilder.Append(((IFormattable)(object)this[i]).ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); } stringBuilder.Append(((IFormattable)(object)this[Count - 1]).ToString(format, formatProvider)); stringBuilder.Append('>'); return stringBuilder.ToString(); } public unsafe static Vector<T>operator +(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarAdd(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarAdd(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarAdd(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarAdd(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarAdd(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarAdd(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarAdd(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarAdd(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarAdd(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarAdd(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 + right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 + right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 + right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 + right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 + right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 + right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 + right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 + right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 + right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 + right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 + right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 + right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 + right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 + right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 + right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 + right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 + right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 + right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 + right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 + right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 + right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 + right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 + right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 + right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 + right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 + right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 + right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 + right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 + right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 + right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 + right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 + right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 + right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 + right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 + right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 + right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 + right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 + right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 + right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 + right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 + right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 + right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 + right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 + right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 + right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 + right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 + right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 + right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 + right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 + right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 + right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 + right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 + right.register.int32_0; result.register.int32_1 = left.register.int32_1 + right.register.int32_1; result.register.int32_2 = left.register.int32_2 + right.register.int32_2; result.register.int32_3 = left.register.int32_3 + right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 + right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 + right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 + right.register.int64_0; result.register.int64_1 = left.register.int64_1 + right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 + right.register.single_0; result.register.single_1 = left.register.single_1 + right.register.single_1; result.register.single_2 = left.register.single_2 + right.register.single_2; result.register.single_3 = left.register.single_3 + right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 + right.register.double_0; result.register.double_1 = left.register.double_1 + right.register.double_1; } return result; } public unsafe static Vector<T>operator -(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarSubtract(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarSubtract(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarSubtract(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarSubtract(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarSubtract(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarSubtract(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarSubtract(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarSubtract(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarSubtract(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarSubtract(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 - right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 - right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 - right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 - right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 - right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 - right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 - right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 - right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 - right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 - right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 - right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 - right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 - right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 - right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 - right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 - right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 - right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 - right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 - right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 - right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 - right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 - right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 - right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 - right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 - right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 - right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 - right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 - right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 - right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 - right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 - right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 - right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 - right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 - right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 - right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 - right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 - right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 - right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 - right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 - right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 - right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 - right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 - right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 - right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 - right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 - right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 - right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 - right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 - right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 - right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 - right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 - right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 - right.register.int32_0; result.register.int32_1 = left.register.int32_1 - right.register.int32_1; result.register.int32_2 = left.register.int32_2 - right.register.int32_2; result.register.int32_3 = left.register.int32_3 - right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 - right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 - right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 - right.register.int64_0; result.register.int64_1 = left.register.int64_1 - right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 - right.register.single_0; result.register.single_1 = left.register.single_1 - right.register.single_1; result.register.single_2 = left.register.single_2 - right.register.single_2; result.register.single_3 = left.register.single_3 - right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 - right.register.double_0; result.register.double_1 = left.register.double_1 - right.register.double_1; } return result; } public unsafe static Vector<T>operator *(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarMultiply(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarMultiply(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarMultiply(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarMultiply(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarMultiply(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarMultiply(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarMultiply(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarMultiply(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarMultiply(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarMultiply(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 * right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 * right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 * right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 * right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 * right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 * right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 * right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 * right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 * right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 * right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 * right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 * right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 * right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 * right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 * right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 * right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 * right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 * right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 * right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 * right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 * right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 * right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 * right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 * right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 * right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 * right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 * right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 * right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 * right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 * right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 * right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 * right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 * right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 * right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 * right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 * right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 * right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 * right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 * right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 * right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 * right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 * right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 * right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 * right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 * right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 * right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 * right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 * right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 * right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 * right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 * right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 * right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 * right.register.int32_0; result.register.int32_1 = left.register.int32_1 * right.register.int32_1; result.register.int32_2 = left.register.int32_2 * right.register.int32_2; result.register.int32_3 = left.register.int32_3 * right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 * right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 * right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 * right.register.int64_0; result.register.int64_1 = left.register.int64_1 * right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 * right.register.single_0; result.register.single_1 = left.register.single_1 * right.register.single_1; result.register.single_2 = left.register.single_2 * right.register.single_2; result.register.single_3 = left.register.single_3 * right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 * right.register.double_0; result.register.double_1 = left.register.double_1 * right.register.double_1; } return result; } public static Vector<T>operator *(Vector<T> value, T factor) { if (Vector.IsHardwareAccelerated) { return new Vector<T>(factor) * value; } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor); result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor); result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor); result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor); result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor); result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor); result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor); result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor); result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor); result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor); result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor); result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor); result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor); result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor); result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor); result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor); result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor); result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor); result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor); result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor); result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor); result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor); result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor); result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor); result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor); result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor); result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor); result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor); result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor); result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor); result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor); result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor); result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor); result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor); result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor); result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor); result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor); result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor); result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor); result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor); result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor); result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor); result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor); result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor); result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor; result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor; result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor; result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = value.register.int32_0 * (int)(object)factor; result.register.int32_1 = value.register.int32_1 * (int)(object)factor; result.register.int32_2 = value.register.int32_2 * (int)(object)factor; result.register.int32_3 = value.register.int32_3 * (int)(object)factor; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor; result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = value.register.int64_0 * (long)(object)factor; result.register.int64_1 = value.register.int64_1 * (long)(object)factor; } else if (typeof(T) == typeof(float)) { result.register.single_0 = value.register.single_0 * (float)(object)factor; result.register.single_1 = value.register.single_1 * (float)(object)factor; result.register.single_2 = value.register.single_2 * (float)(object)factor; result.register.single_3 = value.register.single_3 * (float)(object)factor; } else if (typeof(T) == typeof(double)) { result.register.double_0 = value.register.double_0 * (double)(object)factor; result.register.double_1 = value.register.double_1 * (double)(object)factor; } return result; } public static Vector<T>operator *(T factor, Vector<T> value) { if (Vector.IsHardwareAccelerated) { return new Vector<T>(factor) * value; } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor); result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor); result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor); result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor); result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor); result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor); result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor); result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor); result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor); result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor); result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor); result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor); result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor); result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor); result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor); result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor); result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor); result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor); result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor); result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor); result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor); result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor); result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor); result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor); result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor); result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor); result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor); result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor); result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor); result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor); result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor); result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor); result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor); result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor); result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor); result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor); result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor); result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor); result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor); result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor); result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor); result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor); result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor); result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor); result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor; result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor; result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor; result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = value.register.int32_0 * (int)(object)factor; result.register.int32_1 = value.register.int32_1 * (int)(object)factor; result.register.int32_2 = value.register.int32_2 * (int)(object)factor; result.register.int32_3 = value.register.int32_3 * (int)(object)factor; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor; result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = value.register.int64_0 * (long)(object)factor; result.register.int64_1 = value.register.int64_1 * (long)(object)factor; } else if (typeof(T) == typeof(float)) { result.register.single_0 = value.register.single_0 * (float)(object)factor; result.register.single_1 = value.register.single_1 * (float)(object)factor; result.register.single_2 = value.register.single_2 * (float)(object)factor; result.register.single_3 = value.register.single_3 * (float)(object)factor; } else if (typeof(T) == typeof(double)) { result.register.double_0 = value.register.double_0 * (double)(object)factor; result.register.double_1 = value.register.double_1 * (double)(object)factor; } return result; } public unsafe static Vector<T>operator /(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarDivide(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarDivide(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarDivide(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarDivide(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarDivide(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarDivide(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarDivide(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarDivide(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarDivide(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarDivide(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 / right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 / right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 / right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 / right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 / right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 / right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 / right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 / right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 / right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 / right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 / right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 / right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 / right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 / right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 / right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 / right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 / right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 / right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 / right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 / right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 / right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 / right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 / right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 / right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 / right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 / right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 / right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 / right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 / right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 / right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 / right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 / right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 / right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 / right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 / right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 / right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 / right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 / right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 / right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 / right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 / right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 / right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 / right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 / right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 / right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 / right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 / right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 / right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 / right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 / right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 / right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 / right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 / right.register.int32_0; result.register.int32_1 = left.register.int32_1 / right.register.int32_1; result.register.int32_2 = left.register.int32_2 / right.register.int32_2; result.register.int32_3 = left.register.int32_3 / right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 / right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 / right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 / right.register.int64_0; result.register.int64_1 = left.register.int64_1 / right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 / right.register.single_0; result.register.single_1 = left.register.single_1 / right.register.single_1; result.register.single_2 = left.register.single_2 / right.register.single_2; result.register.single_3 = left.register.single_3 / right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 / right.register.double_0; result.register.double_1 = left.register.double_1 / right.register.double_1; } return result; } public static Vector<T>operator -(Vector<T> value) { return Zero - value; } [JitIntrinsic] public unsafe static Vector<T>operator &(Vector<T> left, Vector<T> right) { Vector<T> result = default(Vector<T>); if (Vector.IsHardwareAccelerated) { long* ptr = &result.register.int64_0; long* ptr2 = &left.register.int64_0; long* ptr3 = &right.register.int64_0; for (int i = 0; i < Vector<long>.Count; i++) { ptr[i] = ptr2[i] & ptr3[i]; } } else { result.register.int64_0 = left.register.int64_0 & right.register.int64_0; result.register.int64_1 = left.register.int64_1 & right.register.int64_1; } return result; } [JitIntrinsic] public unsafe static Vector<T>operator |(Vector<T> left, Vector<T> right) { Vector<T> result = default(Vector<T>); if (Vector.IsHardwareAccelerated) { long* ptr = &result.register.int64_0; long* ptr2 = &left.register.int64_0; long* ptr3 = &right.register.int64_0; for (int i = 0; i < Vector<long>.Count; i++) { ptr[i] = ptr2[i] | ptr3[i]; } } else { result.register.int64_0 = left.register.int64_0 | right.register.int64_0; result.register.int64_1 = left.register.int64_1 | right.register.int64_1; } return result; } [JitIntrinsic] public unsafe static Vector<T>operator ^(Vector<T> left, Vector<T> right) { Vector<T> result = default(Vector<T>); if (Vector.IsHardwareAccelerated) { long* ptr = &result.register.int64_0; long* ptr2 = &left.register.int64_0; long* ptr3 = &right.register.int64_0; for (int i = 0; i < Vector<long>.Count; i++) { ptr[i] = ptr2[i] ^ ptr3[i]; } } else { result.register.int64_0 = left.register.int64_0 ^ right.register.int64_0; result.register.int64_1 = left.register.int64_1 ^ right.register.int64_1; } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T>operator ~(Vector<T> value) { return allOnes ^ value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Vector<T> left, Vector<T> right) { return left.Equals(right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Vector<T> left, Vector<T> right) { return !(left == right); } [JitIntrinsic] public static explicit operator Vector<byte>(Vector<T> value) { return new Vector<byte>(ref value.register); } [CLSCompliant(false)] [JitIntrinsic] public static explicit operator Vector<sbyte>(Vector<T> value) { return new Vector<sbyte>(ref value.register); } [CLSCompliant(false)] [JitIntrinsic] public static explicit operator Vector<ushort>(Vector<T> value) { return new Vector<ushort>(ref value.register); } [JitIntrinsic] public static explicit operator Vector<short>(Vector<T> value) { return new Vector<short>(ref value.register); } [CLSCompliant(false)] [JitIntrinsic] public static explicit operator Vector<uint>(Vector<T> value) { return new Vector<uint>(ref value.register); } [JitIntrinsic] public static explicit operator Vector<int>(Vector<T> value) { return new Vector<int>(ref value.register); } [CLSCompliant(false)] [JitIntrinsic] public static explicit operator Vector<ulong>(Vector<T> value) { return new Vector<ulong>(ref value.register); } [JitIntrinsic] public static explicit operator Vector<long>(Vector<T> value) { return new Vector<long>(ref value.register); } [JitIntrinsic] public static explicit operator Vector<float>(Vector<T> value) { return new Vector<float>(ref value.register); } [JitIntrinsic] public static explicit operator Vector<double>(Vector<T> value) { return new Vector<double>(ref value.register); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [JitIntrinsic] internal unsafe static Vector<T> Equals(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(ScalarEquals(left[i], right[i]) ? ConstantHelper.GetByteWithAllBitsSet() : 0); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(ScalarEquals(left[j], right[j]) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] =
BepInEx/plugins/elytraking-Dread/System.Runtime.CompilerServices.Unsafe.dll
Decompiled a week agousing System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyFileVersion("4.0.0.0")] [assembly: AssemblyInformationalVersion("4.0.0.0")] [assembly: AssemblyTitle("System.Runtime.CompilerServices.Unsafe")] [assembly: AssemblyDescription("System.Runtime.CompilerServices.Unsafe")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: CLSCompliant(false)] [assembly: CompilationRelaxations(8)] [assembly: AssemblyVersion("4.0.4.1")] namespace System.Runtime.CompilerServices { public static class Unsafe : Object { [MethodImpl(256)] [NonVersionable] public unsafe static T Read<T>(void* source) { return Unsafe.Read<T>(source); } [MethodImpl(256)] [NonVersionable] public unsafe static T ReadUnaligned<T>(void* source) { return Unsafe.ReadUnaligned<T>(source); } [MethodImpl(256)] [NonVersionable] public static T ReadUnaligned<T>(ref byte source) { return Unsafe.ReadUnaligned<T>(ref source); } [MethodImpl(256)] [NonVersionable] public unsafe static void Write<T>(void* destination, T value) { Unsafe.Write(destination, value); } [MethodImpl(256)] [NonVersionable] public unsafe static void WriteUnaligned<T>(void* destination, T value) { Unsafe.WriteUnaligned(destination, value); } [MethodImpl(256)] [NonVersionable] public static void WriteUnaligned<T>(ref byte destination, T value) { Unsafe.WriteUnaligned(ref destination, value); } [MethodImpl(256)] [NonVersionable] public unsafe static void Copy<T>(void* destination, ref T source) { Unsafe.Write(destination, source); } [MethodImpl(256)] [NonVersionable] public unsafe static void Copy<T>(ref T destination, void* source) { destination = Unsafe.Read<T>(source); } [MethodImpl(256)] [NonVersionable] public unsafe static void* AsPointer<T>(ref T value) { return Unsafe.AsPointer(ref value); } [MethodImpl(256)] [NonVersionable] public static int SizeOf<T>() { return Unsafe.SizeOf<T>(); } [MethodImpl(256)] [NonVersionable] public unsafe static void CopyBlock(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(destination, source, byteCount); } [MethodImpl(256)] [NonVersionable] public static void CopyBlock(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(ref destination, ref source, byteCount); } [MethodImpl(256)] [NonVersionable] public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(destination, source, byteCount); } [MethodImpl(256)] [NonVersionable] public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount); } [MethodImpl(256)] [NonVersionable] public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(startAddress, value, byteCount); } [MethodImpl(256)] [NonVersionable] public static void InitBlock(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(ref startAddress, value, byteCount); } [MethodImpl(256)] [NonVersionable] public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(startAddress, value, byteCount); } [MethodImpl(256)] [NonVersionable] public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount); } [MethodImpl(256)] [NonVersionable] public static T As<T>(object o) where T : class { return (T)o; } [MethodImpl(256)] [NonVersionable] public unsafe static ref T AsRef<T>(void* source) { return ref *(T*)source; } [MethodImpl(256)] [NonVersionable] public static ref T AsRef<T>(in T source) { return ref source; } [MethodImpl(256)] [NonVersionable] public static ref TTo As<TFrom, TTo>(ref TFrom source) { return ref Unsafe.As<TFrom, TTo>(ref source); } [MethodImpl(256)] [NonVersionable] public static ref T Add<T>(ref T source, int elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(256)] [NonVersionable] public unsafe static void* Add<T>(void* source, int elementOffset) { return (byte*)source + (nint)elementOffset * (nint)Unsafe.SizeOf<T>(); } [MethodImpl(256)] [NonVersionable] public static ref T Add<T>(ref T source, System.IntPtr elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(256)] [NonVersionable] public static ref T AddByteOffset<T>(ref T source, System.IntPtr byteOffset) { return ref Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(256)] [NonVersionable] public static ref T Subtract<T>(ref T source, int elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(256)] [NonVersionable] public unsafe static void* Subtract<T>(void* source, int elementOffset) { return (byte*)source - (nint)elementOffset * (nint)Unsafe.SizeOf<T>(); } [MethodImpl(256)] [NonVersionable] public static ref T Subtract<T>(ref T source, System.IntPtr elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(256)] [NonVersionable] public static ref T SubtractByteOffset<T>(ref T source, System.IntPtr byteOffset) { return ref Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(256)] [NonVersionable] public static System.IntPtr ByteOffset<T>(ref T origin, ref T target) { return Unsafe.ByteOffset(target: ref target, origin: ref origin); } [MethodImpl(256)] [NonVersionable] public static bool AreSame<T>(ref T left, ref T right) { return Unsafe.AreSame(ref left, ref right); } [MethodImpl(256)] [NonVersionable] public static bool IsAddressGreaterThan<T>(ref T left, ref T right) { return Unsafe.IsAddressGreaterThan(ref left, ref right); } [MethodImpl(256)] [NonVersionable] public static bool IsAddressLessThan<T>(ref T left, ref T right) { return Unsafe.IsAddressLessThan(ref left, ref right); } } } namespace System.Runtime.Versioning { [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NonVersionableAttribute : Attribute { } } namespace System.Runtime.CompilerServices { internal sealed class IsReadOnlyAttribute : Attribute { } }