using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Tracing; using System.Globalization; using System.IO; using System.Numerics; using System.Numerics.Hashing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Text; using System.Text.Encodings.Web; using System.Text.Internal; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Converters; using System.Text.Unicode; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using FxResources.System.Buffers; using FxResources.System.Memory; using FxResources.System.Numerics.Vectors; using FxResources.System.Text.Encodings.Web; using FxResources.System.Text.Json; using HarmonyLib; using JusticeForF7.Patches; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("JusticeForF7")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+71f93d75d8e2094172051037b5d1d072d12e5995")] [assembly: AssemblyProduct("JusticeForF7")] [assembly: AssemblyTitle("JusticeForF7")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] 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 JusticeForF7 { [BepInPlugin("wow-much.justice-for-f7", "Justice for F7", "2026.217.0")] public sealed class Plugin : BaseUnityPlugin { private Harmony? _harmony; private WorldUIHider? _hider; private void Awake() { //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Expected O, but got Unknown ConfigEntry val = ((BaseUnityPlugin)this).Config.Bind("General", "Enabled", true, "Master switch. When false, F7 behaves as vanilla."); if (!val.Value) { ((BaseUnityPlugin)this).Logger.LogInfo((object)"Justice for F7 v2026.217.0 loaded (disabled via config)"); return; } ConfigEntry val2 = ((BaseUnityPlugin)this).Config.Bind("General", "EnableLogging", true, "Enable debug logging. Set to false to silence all mod log output."); ConfigEntry rescanInterval = ((BaseUnityPlugin)this).Config.Bind("General", "RescanInterval", 30, "Frames between re-scans while UI is hidden (0 = disable re-scan)."); ConfigEntry hideNameplates = ((BaseUnityPlugin)this).Config.Bind("Elements", "HideNameplates", true, "Hide NPC, SimPlayer, and player nameplates."); ConfigEntry hideDamageNumbers = ((BaseUnityPlugin)this).Config.Bind("Elements", "HideDamageNumbers", true, "Hide floating damage and heal numbers."); ConfigEntry hideTargetRings = ((BaseUnityPlugin)this).Config.Bind("Elements", "HideTargetRings", true, "Hide the selection ring under targeted characters."); ConfigEntry hideXPOrbs = ((BaseUnityPlugin)this).Config.Bind("Elements", "HideXPOrbs", true, "Hide XP orb particles."); ConfigEntry hideCastBars = ((BaseUnityPlugin)this).Config.Bind("Elements", "HideCastBars", true, "Hide NPC and SimPlayer cast bars above nameplates."); ConfigEntry hideOtherWorldText = ((BaseUnityPlugin)this).Config.Bind("Elements", "HideOtherWorldText", true, "Hide remaining world-space text (loot prompts, etc.)."); _hider = new WorldUIHider(((BaseUnityPlugin)this).Logger, val2, hideNameplates, hideDamageNumbers, hideTargetRings, hideXPOrbs, hideCastBars, hideOtherWorldText, rescanInterval); TypeTextPatch.Hider = _hider; DmgPopPatch.Hider = _hider; XPBubPatch.Hider = _hider; _harmony = new Harmony("wow-much.justice-for-f7"); _harmony.PatchAll(); SceneManager.sceneLoaded += OnSceneLoaded; if (val2.Value) { ((BaseUnityPlugin)this).Logger.LogInfo((object)"Justice for F7 v2026.217.0 loaded"); } } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { TypeTextPatch.ResetState(); _hider?.OnSceneLoaded(); } private void OnDestroy() { SceneManager.sceneLoaded -= OnSceneLoaded; Harmony? harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } } } internal static class PluginInfo { public const string GUID = "wow-much.justice-for-f7"; public const string Name = "Justice for F7"; public const string Version = "2026.217.0"; } internal sealed class WorldUIHider { private readonly ManualLogSource _log; private readonly ConfigEntry _enableLogging; private readonly ConfigEntry _hideNameplates; private readonly ConfigEntry _hideDamageNumbers; private readonly ConfigEntry _hideTargetRings; private readonly ConfigEntry _hideXPOrbs; private readonly ConfigEntry _hideCastBars; private readonly ConfigEntry _hideOtherWorldText; private readonly ConfigEntry _rescanInterval; private readonly HashSet _disabledRenderers = new HashSet(); private readonly HashSet _disabledGameObjects = new HashSet(); private int _framesSinceLastScan; public bool IsHidden { get; private set; } public bool SuppressDamageNumbers => IsHidden && _hideDamageNumbers.Value; public bool SuppressXPOrbs => IsHidden && _hideXPOrbs.Value; public WorldUIHider(ManualLogSource log, ConfigEntry enableLogging, ConfigEntry hideNameplates, ConfigEntry hideDamageNumbers, ConfigEntry hideTargetRings, ConfigEntry hideXPOrbs, ConfigEntry hideCastBars, ConfigEntry hideOtherWorldText, ConfigEntry rescanInterval) { _log = log; _enableLogging = enableLogging; _hideNameplates = hideNameplates; _hideDamageNumbers = hideDamageNumbers; _hideTargetRings = hideTargetRings; _hideXPOrbs = hideXPOrbs; _hideCastBars = hideCastBars; _hideOtherWorldText = hideOtherWorldText; _rescanInterval = rescanInterval; } public void OnUIHidden() { IsHidden = true; _framesSinceLastScan = 0; ScanAndHide(); } public void OnUIShown() { IsHidden = false; RestoreAll(); } public void Tick() { if (!IsHidden) { return; } int value = _rescanInterval.Value; if (value > 0) { _framesSinceLastScan++; if (_framesSinceLastScan >= value) { _framesSinceLastScan = 0; ScanAndHide(); } } } public void OnSceneLoaded() { _disabledRenderers.Clear(); _disabledGameObjects.Clear(); if (IsHidden) { _framesSinceLastScan = 0; ScanAndHide(); } } private void ScanAndHide() { int num = 0; if (_hideNameplates.Value) { num += HideNameplates(); } if (_hideDamageNumbers.Value) { num += HideDamageNumbers(); } if (_hideTargetRings.Value) { num += HideTargetRings(); } if (_hideXPOrbs.Value) { num += HideXPOrbs(); } if (_hideCastBars.Value) { num += HideCastBars(); } if (_hideOtherWorldText.Value) { num += HideOtherWorldText(); } if (_enableLogging.Value) { _log.LogDebug((object)$"Scan complete: {num} elements hidden"); } } private int HideNameplates() { int num = 0; NamePlate[] array = Object.FindObjectsOfType(); foreach (NamePlate val in array) { Renderer component = ((Component)val).GetComponent(); if ((Object)(object)component != (Object)null && component.enabled) { component.enabled = false; _disabledRenderers.Add(component); num++; } } return num; } private int HideDamageNumbers() { int num = 0; DmgPop[] array = Object.FindObjectsOfType(); foreach (DmgPop val in array) { Renderer val2 = (((Object)(object)val.Num != (Object)null) ? ((Component)val.Num).GetComponent() : null); if ((Object)(object)val2 != (Object)null && val2.enabled) { val2.enabled = false; _disabledRenderers.Add(val2); num++; } } return num; } private int HideTargetRings() { int num = 0; Character[] array = Object.FindObjectsOfType(); foreach (Character val in array) { GameObject targetRing = val.TargetRing; if ((Object)(object)targetRing != (Object)null && targetRing.activeSelf) { targetRing.SetActive(false); _disabledGameObjects.Add(targetRing); num++; } } return num; } private int HideXPOrbs() { int num = 0; XPBub[] array = Object.FindObjectsOfType(); foreach (XPBub val in array) { Renderer component = ((Component)val).GetComponent(); if ((Object)(object)component != (Object)null && component.enabled) { component.enabled = false; _disabledRenderers.Add(component); num++; } } return num; } private int HideCastBars() { int num = 0; FlashUIColors[] array = Object.FindObjectsOfType(); foreach (FlashUIColors val in array) { if (!((Object)(object)val.CastBar == (Object)null)) { Renderer component = ((Component)val.CastBar).GetComponent(); if ((Object)(object)component != (Object)null && component.enabled) { component.enabled = false; _disabledRenderers.Add(component); num++; } } } return num; } private int HideOtherWorldText() { int num = 0; TextMeshPro[] array = Object.FindObjectsOfType(); foreach (TextMeshPro val in array) { if (!((Object)(object)((Component)val).GetComponent() != (Object)null) && !((Object)(object)((Component)val).GetComponent() != (Object)null) && !((Object)(object)((Component)val).GetComponentInParent() != (Object)null)) { Renderer component = ((Component)val).GetComponent(); if ((Object)(object)component != (Object)null && component.enabled) { component.enabled = false; _disabledRenderers.Add(component); num++; } } } return num; } private void RestoreAll() { int num = 0; int num2 = 0; _disabledRenderers.RemoveWhere((Renderer r) => (Object)(object)r == (Object)null); _disabledGameObjects.RemoveWhere((GameObject go) => (Object)(object)go == (Object)null); foreach (Renderer disabledRenderer in _disabledRenderers) { disabledRenderer.enabled = true; num++; } foreach (GameObject disabledGameObject in _disabledGameObjects) { disabledGameObject.SetActive(true); num2++; } _disabledRenderers.Clear(); _disabledGameObjects.Clear(); if (_enableLogging.Value) { _log.LogDebug((object)$"Restored {num} renderers, {num2} game objects"); } } } } namespace JusticeForF7.Patches { internal static class DmgPopPatch { public static WorldUIHider? Hider { get; set; } [HarmonyPatch(typeof(Misc), "GenPopup")] [HarmonyPrefix] public static bool GenPopupPrefix(int _dmg, bool _crit, DamageType _type, Transform _tar) { return Hider == null || !Hider.SuppressDamageNumbers; } [HarmonyPatch(typeof(Misc), "GenPopupString")] [HarmonyPrefix] public static bool GenPopupStringPrefix(string _msg, Transform _tar) { return Hider == null || !Hider.SuppressDamageNumbers; } } [HarmonyPatch(typeof(TypeText), "Update")] internal static class TypeTextPatch { private static bool? _lastCanvasEnabled; public static WorldUIHider? Hider { get; set; } public static void ResetState() { _lastCanvasEnabled = null; } [HarmonyPostfix] public static void Postfix() { if (Hider == null) { return; } Canvas mainCanvas = GameData.MainCanvas; if ((Object)(object)mainCanvas == (Object)null) { return; } bool enabled = ((Behaviour)mainCanvas).enabled; if (!_lastCanvasEnabled.HasValue) { _lastCanvasEnabled = enabled; return; } if (enabled == _lastCanvasEnabled.Value) { Hider.Tick(); return; } _lastCanvasEnabled = enabled; if (!enabled) { Hider.OnUIHidden(); } else { Hider.OnUIShown(); } } } [HarmonyPatch(typeof(Misc), "GetXPBalls")] internal static class XPBubPatch { public static WorldUIHider? Hider { get; set; } [HarmonyPrefix] public static bool Prefix(int amt, Vector3 callPos, Transform _tar) { return Hider == null || !Hider.SuppressXPOrbs; } } } 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 NativeIntegerAttribute : Attribute { public readonly bool[] TransformFlags; public NativeIntegerAttribute() { TransformFlags = new bool[1] { true }; } public NativeIntegerAttribute(bool[] P_0) { TransformFlags = P_0; } } } internal static class AssemblyInfo { public const string AssemblyName = "MonoMod.Backports"; public const string AssemblyVersion = "1.1.2"; } namespace MonoMod.SourceGen.Attributes { [AttributeUsage(AttributeTargets.Class)] internal sealed class EmitILOverloadsAttribute : Attribute { public EmitILOverloadsAttribute(string filename, string kind) { } } internal static class ILOverloadKind { public const string Cursor = "ILCursor"; public const string Matcher = "ILMatcher"; } } namespace MonoMod.Backports { internal static class MethodImplOptionsEx { public const MethodImplOptions Unmanaged = MethodImplOptions.Unmanaged; public const MethodImplOptions NoInlining = MethodImplOptions.NoInlining; public const MethodImplOptions ForwardRef = MethodImplOptions.ForwardRef; public const MethodImplOptions Synchronized = MethodImplOptions.Synchronized; public const MethodImplOptions NoOptimization = MethodImplOptions.NoOptimization; public const MethodImplOptions PreserveSig = MethodImplOptions.PreserveSig; public const MethodImplOptions AggressiveInlining = MethodImplOptions.AggressiveInlining; public const MethodImplOptions AggressiveOptimization = MethodImplOptions.AggressiveOptimization; public const MethodImplOptions InternalCall = MethodImplOptions.InternalCall; } } namespace MonoMod.Backports.ILHelpers { [CLSCompliant(false)] internal static class UnsafeRaw { [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public unsafe static T Read(void* source) { return <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.Read(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public unsafe static T ReadUnaligned(void* source) { return <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.ReadUnaligned(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static T ReadUnaligned(ref byte source) { return <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.ReadUnaligned(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public unsafe static void Write(void* destination, T value) { <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.Write(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public unsafe static void WriteUnaligned(void* destination, T value) { <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.WriteUnaligned(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static void WriteUnaligned(ref byte destination, T value) { <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.WriteUnaligned(ref destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public unsafe static void Copy(void* destination, ref T source) { <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.Copy(destination, ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public unsafe static void Copy(ref T destination, void* source) { <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.Copy(ref destination, source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public unsafe static void* AsPointer(ref T value) { return <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.AsPointer(ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static void SkipInit(out T value) { <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.SkipInit(out value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public unsafe static void CopyBlock(void* destination, void* source, uint byteCount) { <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.CopyBlock(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static void CopyBlock(ref byte destination, ref byte source, uint byteCount) { <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.CopyBlock(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount) { <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.CopyBlockUnaligned(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount) { <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount) { <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.InitBlock(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static void InitBlock(ref byte startAddress, byte value, uint byteCount) { <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.InitBlock(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount) { <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.InitBlockUnaligned(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount) { <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static T As(object o) where T : class { return <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.As(o); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public unsafe static ref T AsRef(void* source) { return ref <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.AsRef(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static ref T AsRef(in T source) { return ref <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.AsRef(in source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static ref TTo As(ref TFrom source) { return ref <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.As(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static ref T Unbox(object box) where T : struct { return ref <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.Unbox(box); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static ref T AddByteOffset(ref T source, nint byteOffset) { return ref <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static ref T AddByteOffset(ref T source, nuint byteOffset) { return ref <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static ref T SubtractByteOffset(ref T source, nint byteOffset) { return ref <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static ref T SubtractByteOffset(ref T source, nuint byteOffset) { return ref <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static nint ByteOffset(ref T origin, ref T target) { return <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.ByteOffset(ref origin, ref target); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static bool AreSame(ref T left, ref T right) { return <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.AreSame(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static bool IsAddressGreaterThan(ref T left, ref T right) { return <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.IsAddressGreaterThan(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static bool IsAddressLessThan(ref T left, ref T right) { return <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.IsAddressLessThan(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static bool IsNullRef(ref T source) { return <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.IsNullRef(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static ref T NullRef() { return ref <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.NullRef(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static int SizeOf() { return <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.SizeOf(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static ref T Add(ref T source, int elementOffset) { return ref <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public unsafe static void* Add(void* source, int elementOffset) { return <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.Add(source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static ref T Add(ref T source, nint elementOffset) { return ref <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static ref T Add(ref T source, nuint elementOffset) { return ref <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static ref T Subtract(ref T source, int elementOffset) { return ref <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public unsafe static void* Subtract(void* source, int elementOffset) { return <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.Subtract(source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static ref T Subtract(ref T source, nint elementOffset) { return ref <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static ref T Subtract(ref T source, nuint elementOffset) { return ref <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.Subtract(ref source, elementOffset); } } } namespace System { internal static class ArrayEx { public static int MaxLength => 1879048191; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T[] Empty() { return Array.Empty(); } } internal static class EnvironmentEx { public static int CurrentManagedThreadId => Environment.CurrentManagedThreadId; } internal sealed class Gen2GcCallback : CriticalFinalizerObject { private readonly Func? _callback0; private readonly Func? _callback1; private GCHandle _weakTargetObj; private Gen2GcCallback(Func callback) { _callback0 = callback; } private Gen2GcCallback(Func callback, object targetObj) { _callback1 = callback; _weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak); } public static void Register(Func callback) { new System.Gen2GcCallback(callback); } public static void Register(Func callback, object targetObj) { new System.Gen2GcCallback(callback, targetObj); } ~Gen2GcCallback() { if (_weakTargetObj.IsAllocated) { object target = _weakTargetObj.Target; if (target == null) { _weakTargetObj.Free(); return; } try { if (!_callback1(target)) { _weakTargetObj.Free(); return; } } catch { } } else { try { if (!_callback0()) { return; } } catch { } } GC.ReRegisterForFinalize(this); } } internal static class MathEx { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte Clamp(byte value, byte min, byte max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Clamp(decimal value, decimal min, decimal max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Clamp(double value, double min, double max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short Clamp(short value, short min, short max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Clamp(int value, int min, int max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long Clamp(long value, long min, long max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static nint Clamp(nint value, nint min, nint max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static sbyte Clamp(sbyte value, sbyte min, sbyte max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Clamp(float value, float min, float max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ushort Clamp(ushort value, ushort min, ushort max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint Clamp(uint value, uint min, uint max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong Clamp(ulong value, ulong min, ulong max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static nuint Clamp(nuint value, nuint min, nuint max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [DoesNotReturn] private static void ThrowMinMaxException(T min, T max) { throw new ArgumentException($"Minimum {min} is less than maximum {max}"); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class NonVersionableAttribute : Attribute { } internal static class StringComparerEx { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static StringComparer FromComparison(StringComparison comparisonType) { return StringComparer.FromComparison(comparisonType); } } internal static class StringExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string Replace(this string self, string oldValue, string newValue, StringComparison comparison) { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(self, <23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.self); <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(oldValue, <23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.oldValue); <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(newValue, <23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.newValue); return self.Replace(oldValue, newValue, comparison); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Contains(this string self, string value, StringComparison comparison) { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(self, <23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.self); <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(value, <23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.value); return self.Contains(value, comparison); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Contains(this string self, char value, StringComparison comparison) { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(self, <23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.self); return self.Contains(value, comparison); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetHashCode(this string self, StringComparison comparison) { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(self, <23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.self); return self.GetHashCode(comparison); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf(this string self, char value, StringComparison comparison) { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(self, <23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.self); return self.IndexOf(value, comparison); } } internal static class <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void ThrowIfArgumentNull([NotNull] object? obj, <23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument argument) { if (obj == null) { ThrowArgumentNullException(argument); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void ThrowIfArgumentNull([NotNull] object? obj, string argument, string? message = null) { if (obj == null) { ThrowArgumentNullException(argument, message); } } [DoesNotReturn] internal static void ThrowArgumentNullException(<23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument argument) { throw CreateArgumentNullException(argument); } [DoesNotReturn] internal static void ThrowArgumentNullException(string argument, string? message = null) { throw CreateArgumentNullException(argument, message); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentNullException(<23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument argument) { return CreateArgumentNullException(argument.ToString()); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentNullException(string argument, string? message = null) { return new ArgumentNullException(argument, message); } [DoesNotReturn] internal static void ThrowArrayTypeMismatchException() { throw CreateArrayTypeMismatchException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArrayTypeMismatchException() { return new ArrayTypeMismatchException(); } [DoesNotReturn] internal static void ThrowArgumentException_InvalidTypeWithPointersNotSupported(Type type) { throw CreateArgumentException_InvalidTypeWithPointersNotSupported(type); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException_InvalidTypeWithPointersNotSupported(Type type) { return new ArgumentException($"Type {type} with managed pointers cannot be used in a Span"); } [DoesNotReturn] internal static void ThrowArgumentException_DestinationTooShort() { throw CreateArgumentException_DestinationTooShort(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException_DestinationTooShort() { return new ArgumentException("Destination too short"); } [DoesNotReturn] internal static void ThrowArgumentException(string message, string? argument = null) { throw CreateArgumentException(message, argument); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException(string message, string? argument) { return new ArgumentException(message, argument ?? ""); } [DoesNotReturn] internal static void ThrowIndexOutOfRangeException() { throw CreateIndexOutOfRangeException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateIndexOutOfRangeException() { return new IndexOutOfRangeException(); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException() { throw CreateArgumentOutOfRangeException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException() { return new ArgumentOutOfRangeException(); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException(<23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument argument) { throw CreateArgumentOutOfRangeException(argument); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException(<23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument argument) { return new ArgumentOutOfRangeException(argument.ToString()); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException_PrecisionTooLarge() { throw CreateArgumentOutOfRangeException_PrecisionTooLarge(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_PrecisionTooLarge() { return new ArgumentOutOfRangeException("precision", $"Precision too large (max: {99})"); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException_SymbolDoesNotFit() { throw CreateArgumentOutOfRangeException_SymbolDoesNotFit(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_SymbolDoesNotFit() { return new ArgumentOutOfRangeException("symbol", "Bad format specifier"); } [DoesNotReturn] internal static void ThrowInvalidOperationException() { throw CreateInvalidOperationException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException() { return new InvalidOperationException(); } [DoesNotReturn] internal static void ThrowInvalidOperationException_OutstandingReferences() { throw CreateInvalidOperationException_OutstandingReferences(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException_OutstandingReferences() { return new InvalidOperationException("Outstanding references"); } [DoesNotReturn] internal static void ThrowInvalidOperationException_UnexpectedSegmentType() { throw CreateInvalidOperationException_UnexpectedSegmentType(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException_UnexpectedSegmentType() { return new InvalidOperationException("Unexpected segment type"); } [DoesNotReturn] internal static void ThrowInvalidOperationException_EndPositionNotReached() { throw CreateInvalidOperationException_EndPositionNotReached(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException_EndPositionNotReached() { return new InvalidOperationException("End position not reached"); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException_PositionOutOfRange() { throw CreateArgumentOutOfRangeException_PositionOutOfRange(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_PositionOutOfRange() { return new ArgumentOutOfRangeException("position"); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException_OffsetOutOfRange() { throw CreateArgumentOutOfRangeException_OffsetOutOfRange(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_OffsetOutOfRange() { return new ArgumentOutOfRangeException("offset"); } [DoesNotReturn] internal static void ThrowObjectDisposedException_ArrayMemoryPoolBuffer() { throw CreateObjectDisposedException_ArrayMemoryPoolBuffer(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateObjectDisposedException_ArrayMemoryPoolBuffer() { return new ObjectDisposedException("ArrayMemoryPoolBuffer"); } [DoesNotReturn] internal static void ThrowFormatException_BadFormatSpecifier() { throw CreateFormatException_BadFormatSpecifier(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateFormatException_BadFormatSpecifier() { return new FormatException("Bad format specifier"); } [DoesNotReturn] internal static void ThrowArgumentException_OverlapAlignmentMismatch() { throw CreateArgumentException_OverlapAlignmentMismatch(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException_OverlapAlignmentMismatch() { return new ArgumentException("Overlap alignment mismatch"); } [DoesNotReturn] internal static void ThrowNotSupportedException(string? msg = null) { throw CreateThrowNotSupportedException(msg); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateThrowNotSupportedException(string? msg) { return new NotSupportedException(); } [DoesNotReturn] internal static void ThrowKeyNullException() { ThrowArgumentNullException(<23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.key); } [DoesNotReturn] internal static void ThrowValueNullException() { throw CreateThrowValueNullException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateThrowValueNullException() { return new ArgumentException("Value is null"); } [DoesNotReturn] internal static void ThrowOutOfMemoryException() { throw CreateOutOfMemoryException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateOutOfMemoryException() { return new OutOfMemoryException(); } public static bool TryFormatThrowFormatException(out int bytesWritten) { bytesWritten = 0; ThrowFormatException_BadFormatSpecifier(); return false; } public static bool TryParseThrowFormatException(out T value, out int bytesConsumed) { value = default(T); bytesConsumed = 0; ThrowFormatException_BadFormatSpecifier(); return false; } [DoesNotReturn] public static void ThrowArgumentValidationException(ReadOnlySequenceSegment? startSegment, int startIndex, ReadOnlySequenceSegment? endSegment) { throw CreateArgumentValidationException(startSegment, startIndex, endSegment); } private static Exception CreateArgumentValidationException(ReadOnlySequenceSegment? startSegment, int startIndex, ReadOnlySequenceSegment? endSegment) { if (startSegment == null) { return CreateArgumentNullException(<23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.startSegment); } if (endSegment == null) { return CreateArgumentNullException(<23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.endSegment); } if (startSegment != endSegment && startSegment.RunningIndex > endSegment.RunningIndex) { return CreateArgumentOutOfRangeException(<23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.endSegment); } if ((uint)startSegment.Memory.Length < (uint)startIndex) { return CreateArgumentOutOfRangeException(<23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.startIndex); } return CreateArgumentOutOfRangeException(<23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.endIndex); } [DoesNotReturn] 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(<23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.array); } if ((uint)start > (uint)array.Length) { return CreateArgumentOutOfRangeException(<23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.start); } return CreateArgumentOutOfRangeException(<23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.length); } [DoesNotReturn] internal static void ThrowArgumentException_TupleIncorrectType(object other) { throw new ArgumentException($"Value tuple of incorrect type (found {other.GetType()})", "other"); } [DoesNotReturn] public static void ThrowStartOrEndArgumentValidationException(long start) { throw CreateStartOrEndArgumentValidationException(start); } private static Exception CreateStartOrEndArgumentValidationException(long start) { if (start < 0) { return CreateArgumentOutOfRangeException(<23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.start); } return CreateArgumentOutOfRangeException(<23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.length); } } internal enum <23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument { length, start, bufferSize, minimumBufferSize, elementIndex, comparable, comparer, destination, offset, startSegment, endSegment, startIndex, endIndex, array, culture, manager, key, collection, index, type, self, value, oldValue, newValue } internal static class TypeExtensions { public static bool IsByRefLike(this Type type) { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(type, <23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.type); if ((object)type == null) { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowArgumentNullException(<23e83c09-da64-4f5d-8118-db579398253b>ExceptionArgument.type); } return type.IsByRefLike; } } } namespace System.Threading { internal static class MonitorEx { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Enter(object obj, ref bool lockTaken) { Monitor.Enter(obj, ref lockTaken); } } } namespace System.Text { internal static class StringBuilderExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static StringBuilder Clear(this StringBuilder builder) { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(builder, "builder"); return builder.Clear(); } } } namespace System.Numerics { internal static class BitOperations { private static ReadOnlySpan TrailingZeroCountDeBruijn => new byte[32] { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; private static ReadOnlySpan Log2DeBruijn => new byte[32] { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int LeadingZeroCount(uint value) { if (value == 0) { return 32; } return 0x1F ^ Log2SoftwareFallback(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int LeadingZeroCount(ulong value) { uint num = (uint)(value >> 32); if (num == 0) { return 32 + LeadingZeroCount((uint)value); } return LeadingZeroCount(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int Log2(uint value) { value |= 1u; return Log2SoftwareFallback(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int Log2(ulong value) { value |= 1; uint num = (uint)(value >> 32); if (num == 0) { return Log2((uint)value); } return 32 + Log2(num); } private static int Log2SoftwareFallback(uint value) { value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; return <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(Log2DeBruijn), (IntPtr)(int)(value * 130329821 >> 27)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int Log2Ceiling(uint value) { int num = Log2(value); if (PopCount(value) != 1) { num++; } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int Log2Ceiling(ulong value) { int num = Log2(value); if (PopCount(value) != 1) { num++; } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int PopCount(uint value) { return SoftwareFallback(value); static int SoftwareFallback(uint value) { value -= (value >> 1) & 0x55555555; value = (value & 0x33333333) + ((value >> 2) & 0x33333333); value = ((value + (value >> 4)) & 0xF0F0F0F) * 16843009 >> 24; return (int)value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int PopCount(ulong value) { if (IntPtr.Size == 8) { return PopCount((uint)value) + PopCount((uint)(value >> 32)); } return SoftwareFallback(value); static int SoftwareFallback(ulong value) { value -= (value >> 1) & 0x5555555555555555L; value = (value & 0x3333333333333333L) + ((value >> 2) & 0x3333333333333333L); value = ((value + (value >> 4)) & 0xF0F0F0F0F0F0F0FL) * 72340172838076673L >> 56; return (int)value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int TrailingZeroCount(int value) { return TrailingZeroCount((uint)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int TrailingZeroCount(uint value) { if (value == 0) { return 32; } return <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(TrailingZeroCountDeBruijn), (IntPtr)(int)((value & (0 - value)) * 125613361 >> 27)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int TrailingZeroCount(long value) { return TrailingZeroCount((ulong)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int TrailingZeroCount(ulong value) { uint num = (uint)value; if (num == 0) { return 32 + TrailingZeroCount((uint)(value >> 32)); } return TrailingZeroCount(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint RotateLeft(uint value, int offset) { return (value << offset) | (value >> 32 - offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong RotateLeft(ulong value, int offset) { return (value << offset) | (value >> 64 - offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint RotateRight(uint value, int offset) { return (value >> offset) | (value << 32 - offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong RotateRight(ulong value, int offset) { return (value >> offset) | (value << 64 - offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static uint ResetLowestSetBit(uint value) { return value & (value - 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static uint ResetBit(uint value, int bitPos) { return value & (uint)(~(1 << bitPos)); } } internal static class BitOperationsEx { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsPow2(int value) { if ((value & (value - 1)) == 0) { return value > 0; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool IsPow2(uint value) { if ((value & (value - 1)) == 0) { return value != 0; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsPow2(long value) { if ((value & (value - 1)) == 0L) { return value > 0; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool IsPow2(ulong value) { if ((value & (value - 1)) == 0L) { return value != 0; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsPow2(nint value) { if ((value & (value - 1)) == 0) { return value > 0; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool IsPow2(nuint value) { if ((value & (value - 1)) == 0) { return value != 0; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint RoundUpToPowerOf2(uint value) { value--; value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; return value + 1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong RoundUpToPowerOf2(ulong value) { value--; value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; value |= value >> 32; return value + 1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static nuint RoundUpToPowerOf2(nuint value) { if (IntPtr.Size == 8) { return (nuint)RoundUpToPowerOf2((ulong)value); } return RoundUpToPowerOf2((uint)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int LeadingZeroCount(uint value) { return BitOperations.LeadingZeroCount(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int LeadingZeroCount(ulong value) { return BitOperations.LeadingZeroCount(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int LeadingZeroCount(nuint value) { if (IntPtr.Size == 8) { return LeadingZeroCount((ulong)value); } return LeadingZeroCount((uint)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int Log2(uint value) { return BitOperations.Log2(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int Log2(ulong value) { return BitOperations.Log2(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int Log2(nuint value) { if (IntPtr.Size == 8) { return Log2((ulong)value); } return Log2((uint)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int PopCount(uint value) { return BitOperations.PopCount(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int PopCount(ulong value) { return BitOperations.PopCount(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int PopCount(nuint value) { if (IntPtr.Size == 8) { return PopCount((ulong)value); } return PopCount((uint)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int TrailingZeroCount(int value) { return BitOperations.TrailingZeroCount(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int TrailingZeroCount(uint value) { return BitOperations.TrailingZeroCount(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int TrailingZeroCount(long value) { return BitOperations.TrailingZeroCount(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int TrailingZeroCount(ulong value) { return BitOperations.TrailingZeroCount(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int TrailingZeroCount(nint value) { if (IntPtr.Size == 8) { return TrailingZeroCount((long)value); } return TrailingZeroCount((int)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int TrailingZeroCount(nuint value) { if (IntPtr.Size == 8) { return TrailingZeroCount((ulong)value); } return TrailingZeroCount((uint)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint RotateLeft(uint value, int offset) { return BitOperations.RotateLeft(value, offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong RotateLeft(ulong value, int offset) { return BitOperations.RotateLeft(value, offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static nuint RotateLeft(nuint value, int offset) { if (IntPtr.Size == 8) { return (nuint)RotateLeft((ulong)value, offset); } return RotateLeft((uint)value, offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint RotateRight(uint value, int offset) { return BitOperations.RotateRight(value, offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong RotateRight(ulong value, int offset) { return BitOperations.RotateRight(value, offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static nuint RotateRight(nuint value, int offset) { if (IntPtr.Size == 8) { return (nuint)RotateRight((ulong)value, offset); } return RotateRight((uint)value, offset); } } } namespace System.IO { internal static class StreamExtensions { public static void CopyTo(this Stream src, Stream destination) { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(src, "src"); src.CopyTo(destination); } public static void CopyTo(this Stream src, Stream destination, int bufferSize) { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(src, "src"); src.CopyTo(destination, bufferSize); } } } namespace System.Collections { internal static class HashHelpers { public const uint HashCollisionThreshold = 100u; public const int MaxPrimeArrayLength = 2147483587; public const int HashPrime = 101; private static readonly int[] s_primes = new int[72] { 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369 }; public static bool IsPrime(int candidate) { if (((uint)candidate & (true ? 1u : 0u)) != 0) { int num = (int)Math.Sqrt(candidate); for (int i = 3; i <= num; i += 2) { if (candidate % i == 0) { return false; } } return true; } return candidate == 2; } public static int GetPrime(int min) { if (min < 0) { throw new ArgumentException("Prime minimum cannot be less than zero"); } int[] array = s_primes; foreach (int num in array) { if (num >= min) { return num; } } for (int j = min | 1; j < int.MaxValue; j += 2) { if (IsPrime(j) && (j - 1) % 101 != 0) { return j; } } return min; } public static int ExpandPrime(int oldSize) { int num = 2 * oldSize; if ((uint)num > 2147483587u && 2147483587 > oldSize) { return 2147483587; } return GetPrime(num); } public static ulong GetFastModMultiplier(uint divisor) { return ulong.MaxValue / (ulong)divisor + 1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint FastMod(uint value, uint divisor, ulong multiplier) { return (uint)(((multiplier * value >> 32) + 1) * divisor >> 32); } } } namespace System.Collections.Concurrent { internal static class ConcurrentExtensions { public static void Clear(this ConcurrentBag bag) { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(bag, "bag"); bag.Clear(); } public static void Clear(this ConcurrentQueue queue) { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(queue, "queue"); queue.Clear(); } public static TValue AddOrUpdate(this ConcurrentDictionary dict, TKey key, Func addValueFactory, Func updateValueFactory, TArg factoryArgument) where TKey : notnull { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(dict, "dict"); return dict.AddOrUpdate(key, addValueFactory, updateValueFactory, factoryArgument); } public static TValue GetOrAdd(this ConcurrentDictionary dict, TKey key, Func valueFactory, TArg factoryArgument) where TKey : notnull { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(dict, "dict"); return dict.GetOrAdd(key, valueFactory, factoryArgument); } public static bool TryRemove(this ConcurrentDictionary dict, KeyValuePair item) where TKey : notnull { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(dict, "dict"); if (dict.TryRemove(item.Key, out TValue value)) { if (EqualityComparer.Default.Equals(item.Value, value)) { return true; } dict.AddOrUpdate(item.Key, (TKey _) => value, (TKey _, TValue _) => value); return false; } return false; } } } namespace System.Runtime { internal struct DependentHandle : IDisposable { private sealed class DependentHolder : CriticalFinalizerObject { public GCHandle TargetHandle; private IntPtr dependent; public object? Dependent { get { return GCHandle.FromIntPtr(dependent).Target; } set { IntPtr value2 = GCHandle.ToIntPtr(GCHandle.Alloc(value, GCHandleType.Normal)); IntPtr intPtr; do { intPtr = dependent; } while (Interlocked.CompareExchange(ref dependent, value2, intPtr) == intPtr); GCHandle.FromIntPtr(intPtr).Free(); } } public DependentHolder(GCHandle targetHandle, object dependent) { TargetHandle = targetHandle; this.dependent = GCHandle.ToIntPtr(GCHandle.Alloc(dependent, GCHandleType.Normal)); } ~DependentHolder() { if (!AppDomain.CurrentDomain.IsFinalizingForUnload() && (!Environment.HasShutdownStarted && (TargetHandle.IsAllocated && TargetHandle.Target != null))) { GC.ReRegisterForFinalize(this); } else { GCHandle.FromIntPtr(dependent).Free(); } } } private GCHandle dependentHandle; private volatile bool allocated; public bool IsAllocated => allocated; public object? Target { get { if (!allocated) { throw new InvalidOperationException(); } return UnsafeGetTarget(); } set { if (!allocated || value != null) { throw new InvalidOperationException(); } UnsafeSetTargetToNull(); } } public object? Dependent { get { if (!allocated) { throw new InvalidOperationException(); } return UnsafeGetHolder()?.Dependent; } set { if (!allocated) { throw new InvalidOperationException(); } UnsafeSetDependent(value); } } public (object? Target, object? Dependent) TargetAndDependent { get { if (!allocated) { throw new InvalidOperationException(); } return (UnsafeGetTarget(), Dependent); } } public DependentHandle(object? target, object? dependent) { GCHandle targetHandle = GCHandle.Alloc(target, GCHandleType.WeakTrackResurrection); dependentHandle = AllocDepHolder(targetHandle, dependent); GC.KeepAlive(target); allocated = true; } private static GCHandle AllocDepHolder(GCHandle targetHandle, object? dependent) { return GCHandle.Alloc((dependent != null) ? new DependentHolder(targetHandle, dependent) : null, GCHandleType.WeakTrackResurrection); } private DependentHolder? UnsafeGetHolder() { return <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.As(dependentHandle.Target); } internal object? UnsafeGetTarget() { return UnsafeGetHolder()?.TargetHandle.Target; } internal object? UnsafeGetTargetAndDependent(out object? dependent) { dependent = null; DependentHolder dependentHolder = UnsafeGetHolder(); if (dependentHolder == null) { return null; } object target = dependentHolder.TargetHandle.Target; if (target == null) { return null; } dependent = dependentHolder.Dependent; return target; } internal void UnsafeSetTargetToNull() { Free(); } internal void UnsafeSetDependent(object? value) { DependentHolder dependentHolder = UnsafeGetHolder(); if (dependentHolder != null) { if (!dependentHolder.TargetHandle.IsAllocated) { Free(); } else { dependentHolder.Dependent = value; } } } private void FreeDependentHandle() { if (allocated) { UnsafeGetHolder()?.TargetHandle.Free(); dependentHandle.Free(); } allocated = false; } private void Free() { FreeDependentHandle(); } public void Dispose() { Free(); allocated = false; } } } namespace System.Runtime.InteropServices { internal static class MarshalEx { private static readonly MethodInfo? Marshal_SetLastWin32Error_Meth = typeof(Marshal).GetMethod("SetLastPInvokeError", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ?? typeof(Marshal).GetMethod("SetLastWin32Error", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); private static readonly Action? Marshal_SetLastWin32Error = (((object)Marshal_SetLastWin32Error_Meth == null) ? null : ((Action)Delegate.CreateDelegate(typeof(Action), Marshal_SetLastWin32Error_Meth))); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetLastPInvokeError() { return Marshal.GetLastWin32Error(); } public static void SetLastPInvokeError(int error) { (Marshal_SetLastWin32Error ?? throw new PlatformNotSupportedException("Cannot set last P/Invoke error (no method Marshal.SetLastWin32Error or Marshal.SetLastPInvokeError)"))(error); } } } namespace System.Runtime.CompilerServices { [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal static class IsExternalInit { } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } internal interface ICWTEnumerable { IEnumerable SelfEnumerable { get; } IEnumerator GetEnumerator(); } internal sealed class CWTEnumerable : IEnumerable>, IEnumerable where TKey : class where TValue : class? { private readonly ConditionalWeakTable cwt; public CWTEnumerable(ConditionalWeakTable table) { cwt = table; } public IEnumerator> GetEnumerator() { return cwt.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal static class ConditionalWeakTableExtensions { public static IEnumerable> AsEnumerable(this ConditionalWeakTable self) where TKey : class where TValue : class? { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(self, "self"); if (self != null) { return self; } if (self is ICWTEnumerable> iCWTEnumerable) { return iCWTEnumerable.SelfEnumerable; } return new CWTEnumerable(self); } public static IEnumerator> GetEnumerator(this ConditionalWeakTable self) where TKey : class where TValue : class? { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(self, "self"); if (self != null) { return ((IEnumerable>)self).GetEnumerator(); } if (self is ICWTEnumerable> iCWTEnumerable) { return iCWTEnumerable.GetEnumerator(); } throw new PlatformNotSupportedException("This version of MonoMod.Backports was built targeting a version of the framework where ConditionalWeakTable is enumerable, but it isn't!"); } public static void Clear(this ConditionalWeakTable self) where TKey : class where TValue : class? { <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(self, "self"); self.Clear(); } public static bool TryAdd(this ConditionalWeakTable self, TKey key, TValue value) where TKey : class where TValue : class? { TValue value2 = value; <23e83c09-da64-4f5d-8118-db579398253b>ThrowHelper.ThrowIfArgumentNull(self, "self"); bool didAdd = false; self.GetValue(key, delegate { didAdd = true; return value2; }); return didAdd; } } [InterpolatedStringHandler] internal ref struct DefaultInterpolatedStringHandler { private const int GuessedLengthPerHole = 11; private const int MinimumArrayPoolLength = 256; private readonly IFormatProvider? _provider; private char[]? _arrayToReturnToPool; private Span _chars; private int _pos; private readonly bool _hasCustomFormatter; internal ReadOnlySpan Text => _chars.Slice(0, _pos); public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _provider = null; _chars = (_arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount))); _pos = 0; _hasCustomFormatter = false; } public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider) { _provider = provider; _chars = (_arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount))); _pos = 0; _hasCustomFormatter = provider != null && HasCustomFormatter(provider); } public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider, Span initialBuffer) { _provider = provider; _chars = initialBuffer; _arrayToReturnToPool = null; _pos = 0; _hasCustomFormatter = provider != null && HasCustomFormatter(provider); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int GetDefaultLength(int literalLength, int formattedCount) { return Math.Max(256, literalLength + formattedCount * 11); } public override string ToString() { return Text.ToString(); } public string ToStringAndClear() { string result = Text.ToString(); Clear(); return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void Clear() { char[] arrayToReturnToPool = _arrayToReturnToPool; this = default(DefaultInterpolatedStringHandler); if (arrayToReturnToPool != null) { ArrayPool.Shared.Return(arrayToReturnToPool); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendLiteral(string value) { if (value.Length == 1) { Span chars = _chars; int pos = _pos; if ((uint)pos < (uint)chars.Length) { chars[pos] = value[0]; _pos = pos + 1; } else { GrowThenCopyString(value); } } else if (value.Length == 2) { Span chars2 = _chars; int pos2 = _pos; if ((uint)pos2 < chars2.Length - 1) { MemoryExtensions.AsSpan(value).CopyTo(chars2.Slice(pos2)); _pos = pos2 + 2; } else { GrowThenCopyString(value); } } else { AppendStringDirect(value); } } private void AppendStringDirect(string value) { if (MemoryExtensions.AsSpan(value).TryCopyTo(_chars.Slice(_pos))) { _pos += value.Length; } else { GrowThenCopyString(value); } } public void AppendFormatted(T value) { if (_hasCustomFormatter) { AppendCustomFormatter(value, null); return; } if (typeof(T) == typeof(IntPtr)) { AppendFormatted(<157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.As(ref value)); return; } if (typeof(T) == typeof(UIntPtr)) { AppendFormatted(<157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.As(ref value)); return; } string text = ((!(value is IFormattable)) ? value?.ToString() : ((IFormattable)(object)value).ToString(null, _provider)); if (text != null) { AppendStringDirect(text); } } public void AppendFormatted(T value, string? format) { if (_hasCustomFormatter) { AppendCustomFormatter(value, format); return; } if (typeof(T) == typeof(IntPtr)) { AppendFormatted(<157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.As(ref value), format); return; } if (typeof(T) == typeof(UIntPtr)) { AppendFormatted(<157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe.As(ref value), format); return; } string text = ((!(value is IFormattable)) ? value?.ToString() : ((IFormattable)(object)value).ToString(format, _provider)); if (text != null) { AppendStringDirect(text); } } public void AppendFormatted(T value, int alignment) { int pos = _pos; AppendFormatted(value); if (alignment != 0) { AppendOrInsertAlignmentIfNeeded(pos, alignment); } } public void AppendFormatted(T value, int alignment, string? format) { int pos = _pos; AppendFormatted(value, format); if (alignment != 0) { AppendOrInsertAlignmentIfNeeded(pos, alignment); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AppendFormatted(IntPtr value) { if (IntPtr.Size == 4) { AppendFormatted((int)value); } else { AppendFormatted((long)value); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AppendFormatted(IntPtr value, string? format) { if (IntPtr.Size == 4) { AppendFormatted((int)value, format); } else { AppendFormatted((long)value, format); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AppendFormatted(UIntPtr value) { if (UIntPtr.Size == 4) { AppendFormatted((uint)value); } else { AppendFormatted((ulong)value); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AppendFormatted(UIntPtr value, string? format) { if (UIntPtr.Size == 4) { AppendFormatted((uint)value, format); } else { AppendFormatted((ulong)value, format); } } public void AppendFormatted(ReadOnlySpan value) { if (value.TryCopyTo(_chars.Slice(_pos))) { _pos += value.Length; } else { GrowThenCopySpan(value); } } public void AppendFormatted(ReadOnlySpan value, int alignment = 0, string? format = null) { bool flag = false; if (alignment < 0) { flag = true; alignment = -alignment; } int num = alignment - value.Length; if (num <= 0) { AppendFormatted(value); return; } EnsureCapacityForAdditionalChars(value.Length + num); if (flag) { value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; _chars.Slice(_pos, num).Fill(' '); _pos += num; } else { _chars.Slice(_pos, num).Fill(' '); _pos += num; value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; } } public void AppendFormatted(string? value) { if (!_hasCustomFormatter && value != null && MemoryExtensions.AsSpan(value).TryCopyTo(_chars.Slice(_pos))) { _pos += value.Length; } else { AppendFormattedSlow(value); } } [MethodImpl(MethodImplOptions.NoInlining)] private void AppendFormattedSlow(string? value) { if (_hasCustomFormatter) { AppendCustomFormatter(value, null); } else if (value != null) { EnsureCapacityForAdditionalChars(value.Length); MemoryExtensions.AsSpan(value).CopyTo(_chars.Slice(_pos)); _pos += value.Length; } } public void AppendFormatted(string? value, int alignment = 0, string? format = null) { this.AppendFormatted(value, alignment, format); } public void AppendFormatted(object? value, int alignment = 0, string? format = null) { this.AppendFormatted(value, alignment, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool HasCustomFormatter(IFormatProvider provider) { if (provider.GetType() != typeof(CultureInfo)) { return provider.GetFormat(typeof(ICustomFormatter)) != null; } return false; } [MethodImpl(MethodImplOptions.NoInlining)] private void AppendCustomFormatter(T value, string? format) { ICustomFormatter customFormatter = (ICustomFormatter)_provider.GetFormat(typeof(ICustomFormatter)); if (customFormatter != null) { string text = customFormatter.Format(format, value, _provider); if (text != null) { AppendStringDirect(text); } } } private void AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment) { int num = _pos - startingPos; bool flag = false; if (alignment < 0) { flag = true; alignment = -alignment; } int num2 = alignment - num; if (num2 > 0) { EnsureCapacityForAdditionalChars(num2); if (flag) { _chars.Slice(_pos, num2).Fill(' '); } else { _chars.Slice(startingPos, num).CopyTo(_chars.Slice(startingPos + num2)); _chars.Slice(startingPos, num2).Fill(' '); } _pos += num2; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void EnsureCapacityForAdditionalChars(int additionalChars) { if (_chars.Length - _pos < additionalChars) { Grow(additionalChars); } } [MethodImpl(MethodImplOptions.NoInlining)] private void GrowThenCopyString(string value) { Grow(value.Length); MemoryExtensions.AsSpan(value).CopyTo(_chars.Slice(_pos)); _pos += value.Length; } [MethodImpl(MethodImplOptions.NoInlining)] private void GrowThenCopySpan(ReadOnlySpan value) { Grow(value.Length); value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; } [MethodImpl(MethodImplOptions.NoInlining)] private void Grow(int additionalChars) { GrowCore((uint)(_pos + additionalChars)); } [MethodImpl(MethodImplOptions.NoInlining)] private void Grow() { GrowCore((uint)(_chars.Length + 1)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void GrowCore(uint requiredMinCapacity) { int minimumLength = (int)MathEx.Clamp(Math.Max(requiredMinCapacity, Math.Min((uint)(_chars.Length * 2), uint.MaxValue)), 256u, 2147483647u); char[] array = ArrayPool.Shared.Rent(minimumLength); _chars.Slice(0, _pos).CopyTo(array); char[] arrayToReturnToPool = _arrayToReturnToPool; _chars = (_arrayToReturnToPool = array); if (arrayToReturnToPool != null) { ArrayPool.Shared.Return(arrayToReturnToPool); } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)] internal sealed class DisableRuntimeMarshallingAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] internal sealed class InterpolatedStringHandlerAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class InterpolatedStringHandlerArgumentAttribute : Attribute { public string[] Arguments { get; } public InterpolatedStringHandlerArgumentAttribute(string argument) { Arguments = new string[1] { argument }; } public InterpolatedStringHandlerArgumentAttribute(params string[] arguments) { Arguments = arguments; } } internal interface ITuple { int Length { get; } object? this[int index] { get; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class ModuleInitializerAttribute : Attribute { } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class <23e83c09-da64-4f5d-8118-db579398253b>MemberNotNullAttribute : Attribute { public string[] Members { get; } public <23e83c09-da64-4f5d-8118-db579398253b>MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public <23e83c09-da64-4f5d-8118-db579398253b>MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class <23e83c09-da64-4f5d-8118-db579398253b>MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public <23e83c09-da64-4f5d-8118-db579398253b>MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public <23e83c09-da64-4f5d-8118-db579398253b>MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } internal static class ExtraDynamicallyAccessedMemberTypes { public const <23e83c09-da64-4f5d-8118-db579398253b>DynamicallyAccessedMemberTypes Interfaces = (<23e83c09-da64-4f5d-8118-db579398253b>DynamicallyAccessedMemberTypes)8192; } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] internal sealed class <23e83c09-da64-4f5d-8118-db579398253b>DynamicallyAccessedMembersAttribute : Attribute { public <23e83c09-da64-4f5d-8118-db579398253b>DynamicallyAccessedMemberTypes MemberTypes { get; } public <23e83c09-da64-4f5d-8118-db579398253b>DynamicallyAccessedMembersAttribute(<23e83c09-da64-4f5d-8118-db579398253b>DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [Flags] internal enum <23e83c09-da64-4f5d-8118-db579398253b>DynamicallyAccessedMemberTypes { None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, All = -1 } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class UnscopedRefAttribute : Attribute { } } [CompilerGenerated] internal sealed class <23e83c09-da64-4f5d-8118-db579398253b> { [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 32)] private struct __StaticArrayInitTypeSize=32 { } [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 288)] private struct __StaticArrayInitTypeSize=288 { } internal static readonly __StaticArrayInitTypeSize=32 3BF63951626584EB1653F9B8DBB590A5EE1EAE1135A904B9317C3773896DF076/* Not supported: data(00 01 1C 02 1D 0E 18 03 1E 16 14 0F 19 11 04 08 1F 1B 0D 17 15 13 10 07 1A 0C 12 06 0B 05 0A 09) */; internal static readonly __StaticArrayInitTypeSize=32 4BCD43D478B9229AB7A13406353712C7944B60348C36B4D0E6B789D10F697652/* Not supported: data(00 09 01 0A 0D 15 02 1D 0B 0E 10 12 16 19 03 1E 08 0C 14 1C 0F 11 18 07 13 1B 17 06 1A 05 04 1F) */; internal static readonly __StaticArrayInitTypeSize=288 74BCD6ED20AF2231F2BB1CDE814C5F4FF48E54BAC46029EEF90DDF4A208E2B20/* Not supported: data(03 00 00 00 07 00 00 00 0B 00 00 00 11 00 00 00 17 00 00 00 1D 00 00 00 25 00 00 00 2F 00 00 00 3B 00 00 00 47 00 00 00 59 00 00 00 6B 00 00 00 83 00 00 00 A3 00 00 00 C5 00 00 00 EF 00 00 00 25 01 00 00 61 01 00 00 AF 01 00 00 09 02 00 00 77 02 00 00 F9 02 00 00 97 03 00 00 4F 04 00 00 2F 05 00 00 3D 06 00 00 8B 07 00 00 1D 09 00 00 F1 0A 00 00 2B 0D 00 00 D1 0F 00 00 FD 12 00 00 CF 16 00 00 65 1B 00 00 E3 20 00 00 77 27 00 00 6F 2F 00 00 FF 38 00 00 6F 44 00 00 1F 52 00 00 8D 62 00 00 55 76 00 00 01 8E 00 00 6B AA 00 00 89 CC 00 00 83 F5 00 00 A7 26 01 00 9B 61 01 00 57 A8 01 00 3B FD 01 00 15 63 02 00 67 DD 02 00 1B 70 03 00 23 20 04 00 61 F3 04 00 ED F0 05 00 25 21 07 00 31 8E 08 00 3B 44 0A 00 EB 51 0C 00 C1 C8 0E 00 BF BD 11 00 3F 4A 15 00 4F 8C 19 00 67 A8 1E 00 19 CA 24 00 C1 25 2C 00 1B FA 34 00 8F 92 3F 00 87 49 4C 00 6F 8B 5B 00 89 DA 6D 00) */; } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class <157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionableAttribute : Attribute { } } namespace System.Runtime.CompilerServices { internal sealed class IsReadOnlyAttribute : Attribute { } } namespace MonoMod { internal static class ILHelpers { [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static T TailCallDelegatePtr(IntPtr source) { return ((delegate*)source)(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T TailCallFunc(Func func) { return func(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static ref T ObjectAsRef(object obj) { fixed (object obj2 = obj) { T** ptr = (T**)(&obj2); return ref *(*ptr); } } } } namespace System.Runtime.CompilerServices { internal static class <157889e7-97fa-408c-a5f2-46fc03c50572>Unsafe { [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public unsafe static T Read(void* source) { return Unsafe.Read(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public unsafe static T ReadUnaligned(void* source) { return Unsafe.ReadUnaligned(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static T ReadUnaligned(ref byte source) { return Unsafe.ReadUnaligned(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public unsafe static void Write(void* destination, T value) { Unsafe.Write(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public unsafe static void WriteUnaligned(void* destination, T value) { Unsafe.WriteUnaligned(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static void WriteUnaligned(ref byte destination, T value) { Unsafe.WriteUnaligned(ref destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public unsafe static void Copy(void* destination, ref T source) { Unsafe.Write(destination, source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public unsafe static void Copy(ref T destination, void* source) { destination = Unsafe.Read(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public unsafe static void* AsPointer(ref T value) { return Unsafe.AsPointer(ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static void SkipInit(out T value) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static int SizeOf() { return Unsafe.SizeOf(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public unsafe static void CopyBlock(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static void CopyBlock(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static void InitBlock(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static T As(object o) where T : class { return (T)o; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public unsafe static ref T AsRef(void* source) { return ref *(T*)source; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static ref T AsRef(in T source) { return ref source; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static ref TTo As(ref TFrom source) { return ref Unsafe.As(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static ref T Unbox(object box) where T : struct { return ref (T)box; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static ref T Add(ref T source, int elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public unsafe static void* Add(void* source, int elementOffset) { return (byte*)source + (nint)elementOffset * (nint)Unsafe.SizeOf(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static ref T Add(ref T source, nint elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static ref T Add(ref T source, nuint elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static ref T AddByteOffset(ref T source, nint byteOffset) { return ref Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static ref T AddByteOffset(ref T source, nuint byteOffset) { return ref Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static ref T Subtract(ref T source, int elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public unsafe static void* Subtract(void* source, int elementOffset) { return (byte*)source - (nint)elementOffset * (nint)Unsafe.SizeOf(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static ref T Subtract(ref T source, nint elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static ref T Subtract(ref T source, nuint elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static ref T SubtractByteOffset(ref T source, nint byteOffset) { return ref Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static ref T SubtractByteOffset(ref T source, nuint byteOffset) { return ref Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static nint ByteOffset(ref T origin, ref T target) { return Unsafe.ByteOffset(target: ref target, origin: ref origin); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static bool AreSame(ref T left, ref T right) { return Unsafe.AreSame(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static bool IsAddressGreaterThan(ref T left, ref T right) { return Unsafe.IsAddressGreaterThan(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public static bool IsAddressLessThan(ref T left, ref T right) { return Unsafe.IsAddressLessThan(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public unsafe static bool IsNullRef(ref T source) { return Unsafe.AsPointer(ref source) == null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<157889e7-97fa-408c-a5f2-46fc03c50572>NonVersionable] public unsafe static ref T NullRef() { return ref *(T*)null; } } } namespace FxResources.System.Buffers { internal static class SR { } } namespace System { internal static class <081c3ecc-60b8-44f9-a6aa-b9d202311a05>SR { private static ResourceManager s_resourceManager; private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); internal static Type ResourceType { get; } = typeof(FxResources.System.Buffers.SR); internal static string ArgumentException_BufferNotFromPool => GetResourceString("ArgumentException_BufferNotFromPool", null); [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 <081c3ecc-60b8-44f9-a6aa-b9d202311a05>__BlockReflectionAttribute : Attribute { } } namespace System.Buffers { internal abstract class ArrayPool { private static ArrayPool s_sharedInstance; public static ArrayPool Shared { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Volatile.Read(ref s_sharedInstance) ?? EnsureSharedCreated(); } } [MethodImpl(MethodImplOptions.NoInlining)] private static ArrayPool EnsureSharedCreated() { Interlocked.CompareExchange(ref s_sharedInstance, Create(), null); return s_sharedInstance; } public static ArrayPool Create() { return new DefaultArrayPool(); } public static ArrayPool Create(int maxArrayLength, int maxArraysPerBucket) { return new DefaultArrayPool(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 = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferId) }; ptr[1] = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferSize) }; ptr[2] = new EventData { Size = 4, DataPointer = (IntPtr)(&poolId) }; ptr[3] = new EventData { Size = 4, 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 = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferId) }; ptr[1] = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferSize) }; ptr[2] = new EventData { Size = 4, DataPointer = (IntPtr)(&poolId) }; ptr[3] = new EventData { Size = 4, DataPointer = (IntPtr)(&bucketId) }; ptr[4] = new EventData { Size = 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 : ArrayPool { 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(<081c3ecc-60b8-44f9-a6aa-b9d202311a05>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; } } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsByRefLikeAttribute : Attribute { } } namespace FxResources.System.Memory { internal static class SR { } } namespace System { internal readonly struct SequencePosition : IEquatable { 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 <364de6aa-3638-4f0c-b478-eff7d6f86309>HashHelpers.Combine(_object?.GetHashCode() ?? 0, _integer); } } internal static class <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper { internal static void ThrowArgumentNullException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument argument) { throw CreateArgumentNullException(argument); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentNullException(<364de6aa-3638-4f0c-b478-eff7d6f86309>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(<364de6aa-3638-4f0c-b478-eff7d6f86309>SR.Format(<364de6aa-3638-4f0c-b478-eff7d6f86309>SR.Argument_InvalidTypeWithPointersNotSupported, type)); } internal static void ThrowArgumentException_DestinationTooShort() { throw CreateArgumentException_DestinationTooShort(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException_DestinationTooShort() { return new ArgumentException(<364de6aa-3638-4f0c-b478-eff7d6f86309>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(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument argument) { throw CreateArgumentOutOfRangeException(argument); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>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", <364de6aa-3638-4f0c-b478-eff7d6f86309>SR.Format(<364de6aa-3638-4f0c-b478-eff7d6f86309>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", <364de6aa-3638-4f0c-b478-eff7d6f86309>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(<364de6aa-3638-4f0c-b478-eff7d6f86309>SR.OutstandingReferences); } internal static void ThrowInvalidOperationException_UnexpectedSegmentType() { throw CreateInvalidOperationException_UnexpectedSegmentType(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException_UnexpectedSegmentType() { return new InvalidOperationException(<364de6aa-3638-4f0c-b478-eff7d6f86309>SR.UnexpectedSegmentType); } internal static void ThrowInvalidOperationException_EndPositionNotReached() { throw CreateInvalidOperationException_EndPositionNotReached(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException_EndPositionNotReached() { return new InvalidOperationException(<364de6aa-3638-4f0c-b478-eff7d6f86309>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(<364de6aa-3638-4f0c-b478-eff7d6f86309>SR.Argument_BadFormatSpecifier); } internal static void ThrowArgumentException_OverlapAlignmentMismatch() { throw CreateArgumentException_OverlapAlignmentMismatch(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException_OverlapAlignmentMismatch() { return new ArgumentException(<364de6aa-3638-4f0c-b478-eff7d6f86309>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(out T value, out int bytesConsumed) { value = default(T); bytesConsumed = 0; ThrowFormatException_BadFormatSpecifier(); return false; } public static void ThrowArgumentValidationException(ReadOnlySequenceSegment startSegment, int startIndex, ReadOnlySequenceSegment endSegment) { throw CreateArgumentValidationException(startSegment, startIndex, endSegment); } private static Exception CreateArgumentValidationException(ReadOnlySequenceSegment startSegment, int startIndex, ReadOnlySequenceSegment endSegment) { if (startSegment == null) { return CreateArgumentNullException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.startSegment); } if (endSegment == null) { return CreateArgumentNullException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.endSegment); } if (startSegment != endSegment && startSegment.RunningIndex > endSegment.RunningIndex) { return CreateArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.endSegment); } if ((uint)startSegment.Memory.Length < (uint)startIndex) { return CreateArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.startIndex); } return CreateArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>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(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.array); } if ((uint)start > (uint)array.Length) { return CreateArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } return CreateArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.length); } public static void ThrowStartOrEndArgumentValidationException(long start) { throw CreateStartOrEndArgumentValidationException(start); } private static Exception CreateStartOrEndArgumentValidationException(long start) { if (start < 0) { return CreateArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } return CreateArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.length); } } internal enum <364de6aa-3638-4f0c-b478-eff7d6f86309>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 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(ref source); return true; } public static void DecimalToNumber(decimal value, ref NumberBuffer number) { ref MutableDecimal reference = ref Unsafe.As(ref value); Span 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 digits2 = number.Digits; int index = 0; while (--num4 >= 0) { digits2[index++] = digits[num++]; } digits2[index] = 0; } private static uint DigitsToInt(ReadOnlySpan 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 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 Digits => new Span(Unsafe.AsPointer(ref _b0), 51); public unsafe byte* UnsafeDigits => (byte*)Unsafe.AsPointer(ref _b0); public int NumDigits => Digits.IndexOf(0); [Conditional("DEBUG")] public void CheckConsistency() { } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('['); stringBuilder.Append('"'); Span 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}")] internal readonly struct Memory { private readonly object _object; private readonly int _index; private readonly int _length; private const int RemoveFlagsBitMask = int.MaxValue; public static Memory Empty => default(Memory); public int Length => _length & 0x7FFFFFFF; public bool IsEmpty => (_length & 0x7FFFFFFF) == 0; public Span Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Span result; if (_index < 0) { result = ((MemoryManager)_object).GetSpan(); return result.Slice(_index & 0x7FFFFFFF, _length); } if (typeof(T) == typeof(char) && _object is string text) { result = new Span(Unsafe.As>(text), MemoryExtensions.StringAdjustment, text.Length); return result.Slice(_index, _length); } if (_object != null) { return new Span((T[])_object, _index, _length & 0x7FFFFFFF); } result = default(Span); return result; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array) { if (array == null) { this = default(Memory); return; } if (default(T) == null && array.GetType() != typeof(T[])) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArrayTypeMismatchException(); } _object = array; _index = 0; _length = array.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(T[] array, int start) { if (array == null) { if (start != 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(Memory); return; } if (default(T) == null && array.GetType() != typeof(T[])) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length) { <364de6aa-3638-4f0c-b478-eff7d6f86309>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) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(Memory); return; } if (default(T) == null && array.GetType() != typeof(T[])) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = array; _index = start; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager manager, int length) { if (length < 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = manager; _index = int.MinValue; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager manager, int start, int length) { if (length < 0 || start < 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>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[] array) { return new Memory(array); } public static implicit operator Memory(ArraySegment segment) { return new Memory(segment.Array, segment.Offset, segment.Count); } public static implicit operator ReadOnlyMemory(Memory memory) { return Unsafe.As, ReadOnlyMemory>(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 Slice(int start) { int length = _length; int num = length & 0x7FFFFFFF; if ((uint)start > (uint)num) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } return new Memory(_object, _index + start, length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory Slice(int start, int length) { int length2 = _length; int num = length2 & 0x7FFFFFFF; if ((uint)start > (uint)num || (uint)length > (uint)(num - start)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(); } return new Memory(_object, _index + start, length | (length2 & int.MinValue)); } public void CopyTo(Memory destination) { Span.CopyTo(destination.Span); } public bool TryCopyTo(Memory destination) { return Span.TryCopyTo(destination.Span); } public unsafe MemoryHandle Pin() { if (_index < 0) { return ((MemoryManager)_object).Pin(_index & 0x7FFFFFFF); } if (typeof(T) == typeof(char) && _object is string value) { GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned); void* pointer = Unsafe.Add((void*)handle.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer, handle); } if (_object is T[] array) { if (_length < 0) { void* pointer2 = Unsafe.Add(Unsafe.AsPointer(ref MemoryMarshal.GetReference(array)), _index); return new MemoryHandle(pointer2); } GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned); void* pointer3 = Unsafe.Add((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 readOnlyMemory) { return readOnlyMemory.Equals(this); } if (obj is Memory other) { return Equals(other); } return false; } public bool Equals(Memory 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 { private readonly ReadOnlyMemory _memory; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => _memory.ToArray(); public MemoryDebugView(Memory memory) { _memory = memory; } public MemoryDebugView(ReadOnlyMemory memory) { _memory = memory; } } internal static class MemoryExtensions { internal static readonly IntPtr StringAdjustment = MeasureStringAdjustment(); public static ReadOnlySpan Trim(this ReadOnlySpan span) { return span.TrimStart().TrimEnd(); } public static ReadOnlySpan TrimStart(this ReadOnlySpan span) { int i; for (i = 0; i < span.Length && char.IsWhiteSpace(span[i]); i++) { } return span.Slice(i); } public static ReadOnlySpan TrimEnd(this ReadOnlySpan span) { int num = span.Length - 1; while (num >= 0 && char.IsWhiteSpace(span[num])) { num--; } return span.Slice(0, num + 1); } public static ReadOnlySpan Trim(this ReadOnlySpan span, char trimChar) { return span.TrimStart(trimChar).TrimEnd(trimChar); } public static ReadOnlySpan TrimStart(this ReadOnlySpan span, char trimChar) { int i; for (i = 0; i < span.Length && span[i] == trimChar; i++) { } return span.Slice(i); } public static ReadOnlySpan TrimEnd(this ReadOnlySpan span, char trimChar) { int num = span.Length - 1; while (num >= 0 && span[num] == trimChar) { num--; } return span.Slice(0, num + 1); } public static ReadOnlySpan Trim(this ReadOnlySpan span, ReadOnlySpan trimChars) { return span.TrimStart(trimChars).TrimEnd(trimChars); } public static ReadOnlySpan TrimStart(this ReadOnlySpan span, ReadOnlySpan 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 TrimEnd(this ReadOnlySpan span, ReadOnlySpan 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 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(this Span span, T value) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf(this Span span, ReadOnlySpan value) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(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(this Span span, T value) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf(this Span span, ReadOnlySpan value) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(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(this Span span, ReadOnlySpan other) where T : IEquatable { int length = span.Length; if (default(T) != null && IsTypeComparableAsBytes(out var size)) { if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), ref Unsafe.As(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(this Span span, ReadOnlySpan other) where T : IComparable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(other)), other.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(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(this ReadOnlySpan span, T value) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf(this ReadOnlySpan span, ReadOnlySpan value) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(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(this ReadOnlySpan span, T value) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf(this ReadOnlySpan span, ReadOnlySpan value) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(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(this Span span, T value0, T value1) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny(this Span span, T value0, T value1, T value2) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), Unsafe.As(ref value2), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny(this Span span, ReadOnlySpan values) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(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(this ReadOnlySpan span, T value0, T value1) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny(this ReadOnlySpan span, T value0, T value1, T value2) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), Unsafe.As(ref value2), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny(this ReadOnlySpan span, ReadOnlySpan values) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(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(this Span span, T value0, T value1) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny(this Span span, T value0, T value1, T value2) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), Unsafe.As(ref value2), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny(this Span span, ReadOnlySpan values) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(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(this ReadOnlySpan span, T value0, T value1) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny(this ReadOnlySpan span, T value0, T value1, T value2) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), Unsafe.As(ref value2), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny(this ReadOnlySpan span, ReadOnlySpan values) where T : IEquatable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(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(this ReadOnlySpan span, ReadOnlySpan other) where T : IEquatable { int length = span.Length; if (default(T) != null && IsTypeComparableAsBytes(out var size)) { if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), ref Unsafe.As(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(this ReadOnlySpan span, ReadOnlySpan other) where T : IComparable { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(other)), other.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(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(this Span span, ReadOnlySpan value) where T : IEquatable { int length = value.Length; if (default(T) != null && IsTypeComparableAsBytes(out var size)) { if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), ref Unsafe.As(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(this ReadOnlySpan span, ReadOnlySpan value) where T : IEquatable { int length = value.Length; if (default(T) != null && IsTypeComparableAsBytes(out var size)) { if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), ref Unsafe.As(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(this Span span, ReadOnlySpan value) where T : IEquatable { int length = span.Length; int length2 = value.Length; if (default(T) != null && IsTypeComparableAsBytes(out var size)) { if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As(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(this ReadOnlySpan span, ReadOnlySpan value) where T : IEquatable { int length = span.Length; int length2 = value.Length; if (default(T) != null && IsTypeComparableAsBytes(out var size)) { if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As(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(this Span 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 AsSpan(this T[] array) { return new Span(array); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this T[] array, int start, int length) { return new Span(array, start, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this ArraySegment segment) { return new Span(segment.Array, segment.Offset, segment.Count); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this ArraySegment segment, int start) { if ((uint)start > segment.Count) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } return new Span(segment.Array, segment.Offset + start, segment.Count - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this ArraySegment segment, int start, int length) { if ((uint)start > segment.Count) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } if ((uint)length > segment.Count - start) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.length); } return new Span(segment.Array, segment.Offset + start, length); } public static Memory AsMemory(this T[] array) { return new Memory(array); } public static Memory AsMemory(this T[] array, int start) { return new Memory(array, start); } public static Memory AsMemory(this T[] array, int start, int length) { return new Memory(array, start, length); } public static Memory AsMemory(this ArraySegment segment) { return new Memory(segment.Array, segment.Offset, segment.Count); } public static Memory AsMemory(this ArraySegment segment, int start) { if ((uint)start > segment.Count) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } return new Memory(segment.Array, segment.Offset + start, segment.Count - start); } public static Memory AsMemory(this ArraySegment segment, int start, int length) { if ((uint)start > segment.Count) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } if ((uint)length > segment.Count - start) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.length); } return new Memory(segment.Array, segment.Offset + start, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo(this T[] source, Span destination) { new ReadOnlySpan(source).CopyTo(destination); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo(this T[] source, Memory destination) { source.CopyTo(destination.Span); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Overlaps(this Span span, ReadOnlySpan other) { return ((ReadOnlySpan)span).Overlaps(other); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Overlaps(this Span span, ReadOnlySpan other, out int elementOffset) { return ((ReadOnlySpan)span).Overlaps(other, out elementOffset); } public static bool Overlaps(this ReadOnlySpan span, ReadOnlySpan other) { if (span.IsEmpty || other.IsEmpty) { return false; } IntPtr intPtr = Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other)); if (Unsafe.SizeOf() == 4) { if ((uint)(int)intPtr >= (uint)(span.Length * Unsafe.SizeOf())) { return (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf())); } return true; } if ((ulong)(long)intPtr >= (ulong)((long)span.Length * (long)Unsafe.SizeOf())) { return (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf())); } return true; } public static bool Overlaps(this ReadOnlySpan span, ReadOnlySpan 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() == 4) { if ((uint)(int)intPtr < (uint)(span.Length * Unsafe.SizeOf()) || (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf()))) { if ((int)intPtr % Unsafe.SizeOf() != 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); } elementOffset = (int)intPtr / Unsafe.SizeOf(); return true; } elementOffset = 0; return false; } if ((ulong)(long)intPtr < (ulong)((long)span.Length * (long)Unsafe.SizeOf()) || (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf()))) { if ((long)intPtr % Unsafe.SizeOf() != 0L) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); } elementOffset = (int)((long)intPtr / Unsafe.SizeOf()); return true; } elementOffset = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch(this Span span, IComparable comparable) { return span.BinarySearch>(comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch(this Span span, TComparable comparable) where TComparable : IComparable { return BinarySearch((ReadOnlySpan)span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch(this Span span, T value, TComparer comparer) where TComparer : IComparer { return ((ReadOnlySpan)span).BinarySearch(value, comparer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch(this ReadOnlySpan span, IComparable comparable) { return MemoryExtensions.BinarySearch>(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch(this ReadOnlySpan span, TComparable comparable) where TComparable : IComparable { return System.SpanHelpers.BinarySearch(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch(this ReadOnlySpan span, T value, TComparer comparer) where TComparer : IComparer { if (comparer == null) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentNullException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.comparer); } System.SpanHelpers.ComparerComparable comparable = new System.SpanHelpers.ComparerComparable(value, comparer); return BinarySearch(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsTypeComparableAsBytes(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 AsSpan(this T[] array, int start) { return Span.Create(array, start); } public static bool Contains(this ReadOnlySpan span, ReadOnlySpan value, StringComparison comparisonType) { return span.IndexOf(value, comparisonType) >= 0; } public static bool Equals(this ReadOnlySpan span, ReadOnlySpan 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 span, ReadOnlySpan other) { if (other.Length == 0) { return true; } return CompareToOrdinalIgnoreCase(span, other) == 0; } public static int CompareTo(this ReadOnlySpan span, ReadOnlySpan 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 strA, ReadOnlySpan 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 span, ReadOnlySpan value, StringComparison comparisonType) { if (comparisonType == StringComparison.Ordinal) { return span.IndexOf(value); } return span.ToString().IndexOf(value.ToString(), comparisonType); } public static int ToLower(this ReadOnlySpan source, Span destination, CultureInfo culture) { if (culture == null) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentNullException(<364de6aa-3638-4f0c-b478-eff7d6f86309>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 source, Span destination) { return source.ToLower(destination, CultureInfo.InvariantCulture); } public static int ToUpper(this ReadOnlySpan source, Span destination, CultureInfo culture) { if (culture == null) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentNullException(<364de6aa-3638-4f0c-b478-eff7d6f86309>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 source, Span destination) { return source.ToUpper(destination, CultureInfo.InvariantCulture); } public static bool EndsWith(this ReadOnlySpan span, ReadOnlySpan 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 span, ReadOnlySpan 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 AsSpan(this string text) { if (text == null) { return default(ReadOnlySpan); } return new ReadOnlySpan(Unsafe.As>(text), StringAdjustment, text.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan AsSpan(this string text, int start) { if (text == null) { if (start != 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } return default(ReadOnlySpan); } if ((uint)start > (uint)text.Length) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } return new ReadOnlySpan(Unsafe.As>(text), StringAdjustment + start * 2, text.Length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan AsSpan(this string text, int start, int length) { if (text == null) { if (start != 0 || length != 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } return default(ReadOnlySpan); } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } return new ReadOnlySpan(Unsafe.As>(text), StringAdjustment + start * 2, length); } public static ReadOnlyMemory AsMemory(this string text) { if (text == null) { return default(ReadOnlyMemory); } return new ReadOnlyMemory(text, 0, text.Length); } public static ReadOnlyMemory AsMemory(this string text, int start) { if (text == null) { if (start != 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } return default(ReadOnlyMemory); } if ((uint)start > (uint)text.Length) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } return new ReadOnlyMemory(text, start, text.Length - start); } public static ReadOnlyMemory AsMemory(this string text, int start, int length) { if (text == null) { if (start != 0 || length != 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } return default(ReadOnlyMemory); } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } return new ReadOnlyMemory(text, start, length); } private unsafe static IntPtr MeasureStringAdjustment() { string text = "a"; fixed (char* source = text) { return Unsafe.ByteOffset(ref Unsafe.As>(text).Data, ref Unsafe.AsRef(source)); } } } [DebuggerTypeProxy(typeof(System.MemoryDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] internal readonly struct ReadOnlyMemory { private readonly object _object; private readonly int _index; private readonly int _length; internal const int RemoveFlagsBitMask = int.MaxValue; public static ReadOnlyMemory Empty => default(ReadOnlyMemory); public int Length => _length & 0x7FFFFFFF; public bool IsEmpty => (_length & 0x7FFFFFFF) == 0; public ReadOnlySpan Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_index < 0) { return ((MemoryManager)_object).GetSpan().Slice(_index & 0x7FFFFFFF, _length); } ReadOnlySpan result; if (typeof(T) == typeof(char) && _object is string text) { result = new ReadOnlySpan(Unsafe.As>(text), MemoryExtensions.StringAdjustment, text.Length); return result.Slice(_index, _length); } if (_object != null) { return new ReadOnlySpan((T[])_object, _index, _length & 0x7FFFFFFF); } result = default(ReadOnlySpan); return result; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[] array) { if (array == null) { this = default(ReadOnlyMemory); 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) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(ReadOnlyMemory); return; } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>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[] array) { return new ReadOnlyMemory(array); } public static implicit operator ReadOnlyMemory(ArraySegment segment) { return new ReadOnlyMemory(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 Slice(int start) { int length = _length; int num = length & 0x7FFFFFFF; if ((uint)start > (uint)num) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } return new ReadOnlyMemory(_object, _index + start, length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory Slice(int start, int length) { int length2 = _length; int num = _length & 0x7FFFFFFF; if ((uint)start > (uint)num || (uint)length > (uint)(num - start)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } return new ReadOnlyMemory(_object, _index + start, length | (length2 & int.MinValue)); } public void CopyTo(Memory destination) { Span.CopyTo(destination.Span); } public bool TryCopyTo(Memory destination) { return Span.TryCopyTo(destination.Span); } public unsafe MemoryHandle Pin() { if (_index < 0) { return ((MemoryManager)_object).Pin(_index & 0x7FFFFFFF); } if (typeof(T) == typeof(char) && _object is string value) { GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned); void* pointer = Unsafe.Add((void*)handle.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer, handle); } if (_object is T[] array) { if (_length < 0) { void* pointer2 = Unsafe.Add(Unsafe.AsPointer(ref MemoryMarshal.GetReference(array)), _index); return new MemoryHandle(pointer2); } GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned); void* pointer3 = Unsafe.Add((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 other) { return Equals(other); } if (obj is Memory memory) { return Equals(memory); } return false; } public bool Equals(ReadOnlyMemory 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<>))] internal readonly ref struct ReadOnlySpan { public ref struct Enumerator { private readonly ReadOnlySpan _span; private int _index; public ref readonly T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _span[_index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(ReadOnlySpan 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 _pinnable; private readonly IntPtr _byteOffset; private readonly int _length; public int Length => _length; public bool IsEmpty => _length == 0; public static ReadOnlySpan Empty => default(ReadOnlySpan); public unsafe ref readonly T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((uint)index >= (uint)_length) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowIndexOutOfRangeException(); } if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.Add(ref Unsafe.AsRef(byteOffset.ToPointer()), index); } return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset), index); } } internal Pinnable Pinnable => _pinnable; internal IntPtr ByteOffset => _byteOffset; public static bool operator !=(ReadOnlySpan left, ReadOnlySpan 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(<364de6aa-3638-4f0c-b478-eff7d6f86309>SR.NotSupported_CannotCallEqualsOnSpan); } [Obsolete("GetHashCode() on ReadOnlySpan will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException(<364de6aa-3638-4f0c-b478-eff7d6f86309>SR.NotSupported_CannotCallGetHashCodeOnSpan); } public static implicit operator ReadOnlySpan(T[] array) { return new ReadOnlySpan(array); } public static implicit operator ReadOnlySpan(ArraySegment segment) { return new ReadOnlySpan(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); return; } _length = array.Length; _pinnable = Unsafe.As>(array); _byteOffset = System.SpanHelpers.PerTypeValues.ArrayAdjustment; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } this = default(ReadOnlySpan); return; } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } _length = length; _pinnable = Unsafe.As>(array); _byteOffset = System.SpanHelpers.PerTypeValues.ArrayAdjustment.Add(start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public unsafe ReadOnlySpan(void* pointer, int length) { if (System.SpanHelpers.IsReferenceOrContainsReferences()) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } if (length < 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } _length = length; _pinnable = null; _byteOffset = new IntPtr(pointer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlySpan(Pinnable 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(byteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); } return ref Unsafe.AsRef(null); } public void CopyTo(Span destination) { if (!TryCopyTo(destination)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } public bool TryCopyTo(Span 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 left, ReadOnlySpan 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(_pinnable); if (obj is string text && _length == text.Length) { return text; } } fixed (char* value = &Unsafe.As(ref DangerousGetPinnableReference())) { return new string(value, 0, _length); } } return $"System.ReadOnlySpan<{typeof(T).Name}>[{_length}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan Slice(int start) { if ((uint)start > (uint)_length) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add(start); int length = _length - start; return new ReadOnlySpan(_pinnable, byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add(start); return new ReadOnlySpan(_pinnable, byteOffset, length); } public T[] ToArray() { if (_length == 0) { return System.SpanHelpers.PerTypeValues.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(byteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); } } [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] internal readonly ref struct Span { public ref struct Enumerator { private readonly Span _span; private int _index; public ref T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _span[_index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(Span 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 _pinnable; private readonly IntPtr _byteOffset; private readonly int _length; public int Length => _length; public bool IsEmpty => _length == 0; public static Span Empty => default(Span); public unsafe ref T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((uint)index >= (uint)_length) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowIndexOutOfRangeException(); } if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref Unsafe.Add(ref Unsafe.AsRef(byteOffset.ToPointer()), index); } return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset), index); } } internal Pinnable Pinnable => _pinnable; internal IntPtr ByteOffset => _byteOffset; public static bool operator !=(Span left, Span 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(<364de6aa-3638-4f0c-b478-eff7d6f86309>SR.NotSupported_CannotCallEqualsOnSpan); } [Obsolete("GetHashCode() on Span will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException(<364de6aa-3638-4f0c-b478-eff7d6f86309>SR.NotSupported_CannotCallGetHashCodeOnSpan); } public static implicit operator Span(T[] array) { return new Span(array); } public static implicit operator Span(ArraySegment segment) { return new Span(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); return; } if (default(T) == null && array.GetType() != typeof(T[])) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArrayTypeMismatchException(); } _length = array.Length; _pinnable = Unsafe.As>(array); _byteOffset = System.SpanHelpers.PerTypeValues.ArrayAdjustment; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Span Create(T[] array, int start) { if (array == null) { if (start != 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } return default(Span); } if (default(T) == null && array.GetType() != typeof(T[])) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } IntPtr byteOffset = System.SpanHelpers.PerTypeValues.ArrayAdjustment.Add(start); int length = array.Length - start; return new Span(Unsafe.As>(array), byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } this = default(Span); return; } if (default(T) == null && array.GetType() != typeof(T[])) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } _length = length; _pinnable = Unsafe.As>(array); _byteOffset = System.SpanHelpers.PerTypeValues.ArrayAdjustment.Add(start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public unsafe Span(void* pointer, int length) { if (System.SpanHelpers.IsReferenceOrContainsReferences()) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } if (length < 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } _length = length; _pinnable = null; _byteOffset = new IntPtr(pointer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Span(Pinnable 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(byteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); } return ref Unsafe.AsRef(null); } public unsafe void Clear() { int length = _length; if (length == 0) { return; } UIntPtr byteLength = (UIntPtr)(ulong)((uint)length * Unsafe.SizeOf()); if ((Unsafe.SizeOf() & (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(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset)), byteLength); } } else if (System.SpanHelpers.IsReferenceOrContainsReferences()) { UIntPtr pointerSizeLength = (UIntPtr)(ulong)(length * Unsafe.SizeOf() / sizeof(IntPtr)); System.SpanHelpers.ClearPointerSizedWithReferences(ref Unsafe.As(ref DangerousGetPinnableReference()), pointerSizeLength); } else { System.SpanHelpers.ClearPointerSizedWithoutReferences(ref Unsafe.As(ref DangerousGetPinnableReference()), byteLength); } } public unsafe void Fill(T value) { int length = _length; if (length == 0) { return; } if (Unsafe.SizeOf() == 1) { byte value2 = Unsafe.As(ref value); if (_pinnable == null) { IntPtr byteOffset = _byteOffset; Unsafe.InitBlockUnaligned(byteOffset.ToPointer(), value2, (uint)length); } else { Unsafe.InitBlockUnaligned(ref Unsafe.As(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 destination) { if (!TryCopyTo(destination)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } public bool TryCopyTo(Span 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 left, Span right) { if (left._length == right._length) { return Unsafe.AreSame(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference()); } return false; } public static implicit operator ReadOnlySpan(Span span) { return new ReadOnlySpan(span._pinnable, span._byteOffset, span._length); } public unsafe override string ToString() { if (typeof(T) == typeof(char)) { fixed (char* value = &Unsafe.As(ref DangerousGetPinnableReference())) { return new string(value, 0, _length); } } return $"System.Span<{typeof(T).Name}>[{_length}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span Slice(int start) { if ((uint)start > (uint)_length) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add(start); int length = _length - start; return new Span(_pinnable, byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add(start); return new Span(_pinnable, byteOffset, length); } public T[] ToArray() { if (_length == 0) { return System.SpanHelpers.PerTypeValues.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(byteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset); } } internal sealed class SpanDebugView { private readonly T[] _array; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => _array; public SpanDebugView(Span span) { _array = span.ToArray(); } public SpanDebugView(ReadOnlySpan span) { _array = span.ToArray(); } } internal static class SpanHelpers { internal struct ComparerComparable : IComparable where TComparer : IComparer { 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 { 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>(array).Data, ref array[0]); } } private const ulong XorPowerOfTwoToHighByte = 283686952306184uL; private const ulong XorPowerOfTwoToHighChar = 4295098372uL; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch(this ReadOnlySpan span, TComparable comparable) where TComparable : IComparable { if (comparable == null) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentNullException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.comparable); } return BinarySearch(ref MemoryMarshal.GetReference(span), span.Length, comparable); } public static int BinarySearch(ref T spanStart, int length, TComparable comparable) where TComparable : IComparable { 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.Count * 2) { int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); intPtr2 = (IntPtr)((Vector.Count - num) & (Vector.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.Count - 1)); Vector vector = GetVector(value); for (; (void*)intPtr2 > (void*)intPtr; intPtr += Vector.Count) { Vector vector2 = Vector.Equals(vector, Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref searchSpace, intPtr))); if (!Vector.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.Count * 2) { int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); intPtr2 = (IntPtr)(((length & (Vector.Count - 1)) + num) & (Vector.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 != Unsafe.AddByteOffset(ref searchSpace, intPtr)) { continue; } goto IL_0254; } if (Vector.IsHardwareAccelerated && (void*)intPtr != null) { intPtr2 = (IntPtr)((int)(void*)intPtr & ~(Vector.Count - 1)); Vector vector = GetVector(value); for (; (nuint)(void*)intPtr2 > (nuint)(Vector.Count - 1); intPtr2 -= Vector.Count) { Vector vector2 = Vector.Equals(vector, Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref searchSpace, intPtr - Vector.Count))); if (Vector.Zero.Equals(vector2)) { intPtr -= Vector.Count; continue; } return (int)intPtr - Vector.Count + LocateLastFoundByte(vector2); } if ((void*)intPtr != null) { intPtr2 = intPtr; continue; } } return -1; IL_0254: return (int)(void*)intPtr; IL_026a: return (int)(void*)(intPtr + 2); IL_0278: return (int)(void*)(intPtr + 3); IL_025c: return (int)(void*)(intPtr + 1); } return (int)(void*)(intPtr + 7); } public unsafe static int IndexOfAny(ref byte searchSpace, byte value0, byte value1, int length) { IntPtr intPtr = (IntPtr)0; IntPtr intPtr2 = (IntPtr)length; if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); intPtr2 = (IntPtr)((Vector.Count - num) & (Vector.Count - 1)); } while (true) { if ((nuint)(void*)intPtr2 >= (nuint)8u) { intPtr2 -= 8; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 == num2 || value1 == num2) { goto IL_02ff; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); if (value0 == num2 || value1 == num2) { goto IL_0307; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); if (value0 == num2 || value1 == num2) { goto IL_0315; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); if (value0 != num2 && value1 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 4); if (value0 != num2 && value1 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 5); if (value0 != num2 && value1 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 6); if (value0 != num2 && value1 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 7); if (value0 == num2 || value1 == num2) { break; } intPtr += 8; continue; } return (int)(void*)(intPtr + 6); } return (int)(void*)(intPtr + 5); } return (int)(void*)(intPtr + 4); } goto IL_0323; } if ((nuint)(void*)intPtr2 >= (nuint)4u) { intPtr2 -= 4; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 == num2 || value1 == num2) { goto IL_02ff; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); if (value0 == num2 || value1 == num2) { goto IL_0307; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); if (value0 == num2 || value1 == num2) { goto IL_0315; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); if (value0 == num2 || value1 == num2) { goto IL_0323; } intPtr += 4; } while ((void*)intPtr2 != null) { intPtr2 -= 1; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 != num2 && value1 != num2) { intPtr += 1; continue; } goto IL_02ff; } if (Vector.IsHardwareAccelerated && (int)(void*)intPtr < length) { intPtr2 = (IntPtr)((length - (int)(void*)intPtr) & ~(Vector.Count - 1)); Vector vector = GetVector(value0); Vector vector2 = GetVector(value1); for (; (void*)intPtr2 > (void*)intPtr; intPtr += Vector.Count) { Vector left = Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref searchSpace, intPtr)); Vector vector3 = Vector.BitwiseOr(Vector.Equals(left, vector), Vector.Equals(left, vector2)); if (!Vector.Zero.Equals(vector3)) { return (int)(void*)intPtr + LocateFirstFoundByte(vector3); } } if ((int)(void*)intPtr < length) { intPtr2 = (IntPtr)(length - (int)(void*)intPtr); continue; } } return -1; IL_02ff: return (int)(void*)intPtr; IL_0315: return (int)(void*)(intPtr + 2); IL_0307: return (int)(void*)(intPtr + 1); IL_0323: return (int)(void*)(intPtr + 3); } return (int)(void*)(intPtr + 7); } public unsafe static int IndexOfAny(ref byte searchSpace, byte value0, byte value1, byte value2, int length) { IntPtr intPtr = (IntPtr)0; IntPtr intPtr2 = (IntPtr)length; if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); intPtr2 = (IntPtr)((Vector.Count - num) & (Vector.Count - 1)); } while (true) { if ((nuint)(void*)intPtr2 >= (nuint)8u) { intPtr2 -= 8; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 == num2 || value1 == num2 || value2 == num2) { goto IL_0393; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); if (value0 == num2 || value1 == num2 || value2 == num2) { goto IL_039b; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); if (value0 == num2 || value1 == num2 || value2 == num2) { goto IL_03a9; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); if (value0 != num2 && value1 != num2 && value2 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 4); if (value0 != num2 && value1 != num2 && value2 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 5); if (value0 != num2 && value1 != num2 && value2 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 6); if (value0 != num2 && value1 != num2 && value2 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 7); if (value0 == num2 || value1 == num2 || value2 == num2) { break; } intPtr += 8; continue; } return (int)(void*)(intPtr + 6); } return (int)(void*)(intPtr + 5); } return (int)(void*)(intPtr + 4); } goto IL_03b7; } if ((nuint)(void*)intPtr2 >= (nuint)4u) { intPtr2 -= 4; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 == num2 || value1 == num2 || value2 == num2) { goto IL_0393; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); if (value0 == num2 || value1 == num2 || value2 == num2) { goto IL_039b; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); if (value0 == num2 || value1 == num2 || value2 == num2) { goto IL_03a9; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); if (value0 == num2 || value1 == num2 || value2 == num2) { goto IL_03b7; } intPtr += 4; } while ((void*)intPtr2 != null) { intPtr2 -= 1; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 != num2 && value1 != num2 && value2 != num2) { intPtr += 1; continue; } goto IL_0393; } if (Vector.IsHardwareAccelerated && (int)(void*)intPtr < length) { intPtr2 = (IntPtr)((length - (int)(void*)intPtr) & ~(Vector.Count - 1)); Vector vector = GetVector(value0); Vector vector2 = GetVector(value1); Vector vector3 = GetVector(value2); for (; (void*)intPtr2 > (void*)intPtr; intPtr += Vector.Count) { Vector left = Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref searchSpace, intPtr)); Vector vector4 = Vector.BitwiseOr(Vector.BitwiseOr(Vector.Equals(left, vector), Vector.Equals(left, vector2)), Vector.Equals(left, vector3)); if (!Vector.Zero.Equals(vector4)) { return (int)(void*)intPtr + LocateFirstFoundByte(vector4); } } if ((int)(void*)intPtr < length) { intPtr2 = (IntPtr)(length - (int)(void*)intPtr); continue; } } return -1; IL_0393: return (int)(void*)intPtr; IL_039b: return (int)(void*)(intPtr + 1); IL_03b7: return (int)(void*)(intPtr + 3); IL_03a9: return (int)(void*)(intPtr + 2); } return (int)(void*)(intPtr + 7); } public unsafe static int LastIndexOfAny(ref byte searchSpace, byte value0, byte value1, int length) { IntPtr intPtr = (IntPtr)length; IntPtr intPtr2 = (IntPtr)length; if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); intPtr2 = (IntPtr)(((length & (Vector.Count - 1)) + num) & (Vector.Count - 1)); } while (true) { if ((nuint)(void*)intPtr2 >= (nuint)8u) { intPtr2 -= 8; intPtr -= 8; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 7); if (value0 == num2 || value1 == num2) { break; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 6); if (value0 != num2 && value1 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 5); if (value0 != num2 && value1 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 4); if (value0 != num2 && value1 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); if (value0 != num2 && value1 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); if (value0 != num2 && value1 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); if (value0 != num2 && value1 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 != num2 && value1 != num2) { continue; } goto IL_0314; } goto IL_031c; } goto IL_032a; } goto IL_0338; } 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; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); if (value0 == num2 || value1 == num2) { goto IL_0338; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); if (value0 == num2 || value1 == num2) { goto IL_032a; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); if (value0 == num2 || value1 == num2) { goto IL_031c; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 == num2 || value1 == num2) { goto IL_0314; } } while ((void*)intPtr2 != null) { intPtr2 -= 1; intPtr -= 1; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 != num2 && value1 != num2) { continue; } goto IL_0314; } if (Vector.IsHardwareAccelerated && (void*)intPtr != null) { intPtr2 = (IntPtr)((int)(void*)intPtr & ~(Vector.Count - 1)); Vector vector = GetVector(value0); Vector vector2 = GetVector(value1); for (; (nuint)(void*)intPtr2 > (nuint)(Vector.Count - 1); intPtr2 -= Vector.Count) { Vector left = Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref searchSpace, intPtr - Vector.Count)); Vector vector3 = Vector.BitwiseOr(Vector.Equals(left, vector), Vector.Equals(left, vector2)); if (Vector.Zero.Equals(vector3)) { intPtr -= Vector.Count; continue; } return (int)intPtr - Vector.Count + LocateLastFoundByte(vector3); } if ((void*)intPtr != null) { intPtr2 = intPtr; continue; } } return -1; IL_0314: return (int)(void*)intPtr; IL_0338: return (int)(void*)(intPtr + 3); IL_031c: return (int)(void*)(intPtr + 1); IL_032a: return (int)(void*)(intPtr + 2); } return (int)(void*)(intPtr + 7); } public unsafe static int LastIndexOfAny(ref byte searchSpace, byte value0, byte value1, byte value2, int length) { IntPtr intPtr = (IntPtr)length; IntPtr intPtr2 = (IntPtr)length; if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); intPtr2 = (IntPtr)(((length & (Vector.Count - 1)) + num) & (Vector.Count - 1)); } while (true) { if ((nuint)(void*)intPtr2 >= (nuint)8u) { intPtr2 -= 8; intPtr -= 8; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 7); if (value0 == num2 || value1 == num2 || value2 == num2) { break; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 6); if (value0 != num2 && value1 != num2 && value2 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 5); if (value0 != num2 && value1 != num2 && value2 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 4); if (value0 != num2 && value1 != num2 && value2 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); if (value0 != num2 && value1 != num2 && value2 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); if (value0 != num2 && value1 != num2 && value2 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); if (value0 != num2 && value1 != num2 && value2 != num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 != num2 && value1 != num2 && value2 != num2) { continue; } goto IL_03ab; } goto IL_03b3; } goto IL_03c1; } goto IL_03cf; } 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; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); if (value0 == num2 || value1 == num2 || value2 == num2) { goto IL_03cf; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); if (value0 == num2 || value1 == num2 || value2 == num2) { goto IL_03c1; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); if (value0 == num2 || value1 == num2 || value2 == num2) { goto IL_03b3; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 == num2 || value1 == num2 || value2 == num2) { goto IL_03ab; } } while ((void*)intPtr2 != null) { intPtr2 -= 1; intPtr -= 1; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 != num2 && value1 != num2 && value2 != num2) { continue; } goto IL_03ab; } if (Vector.IsHardwareAccelerated && (void*)intPtr != null) { intPtr2 = (IntPtr)((int)(void*)intPtr & ~(Vector.Count - 1)); Vector vector = GetVector(value0); Vector vector2 = GetVector(value1); Vector vector3 = GetVector(value2); for (; (nuint)(void*)intPtr2 > (nuint)(Vector.Count - 1); intPtr2 -= Vector.Count) { Vector left = Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref searchSpace, intPtr - Vector.Count)); Vector vector4 = Vector.BitwiseOr(Vector.BitwiseOr(Vector.Equals(left, vector), Vector.Equals(left, vector2)), Vector.Equals(left, vector3)); if (Vector.Zero.Equals(vector4)) { intPtr -= Vector.Count; continue; } return (int)intPtr - Vector.Count + LocateLastFoundByte(vector4); } if ((void*)intPtr != null) { intPtr2 = intPtr; continue; } } return -1; IL_03ab: return (int)(void*)intPtr; IL_03cf: return (int)(void*)(intPtr + 3); IL_03c1: return (int)(void*)(intPtr + 2); IL_03b3: return (int)(void*)(intPtr + 1); } return (int)(void*)(intPtr + 7); } public unsafe static bool SequenceEqual(ref byte first, ref byte second, NUInt length) { if (Unsafe.AreSame(ref first, ref second)) { goto IL_013d; } IntPtr intPtr = (IntPtr)0; IntPtr intPtr2 = (IntPtr)(void*)length; if (Vector.IsHardwareAccelerated && (nuint)(void*)intPtr2 >= (nuint)Vector.Count) { intPtr2 -= Vector.Count; while (true) { if ((void*)intPtr2 > (void*)intPtr) { if (Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref first, intPtr)) != Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref second, intPtr))) { break; } intPtr += Vector.Count; continue; } return Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref first, intPtr2)) == Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref second, intPtr2)); } } else { if ((nuint)(void*)intPtr2 < (nuint)sizeof(UIntPtr)) { while ((void*)intPtr2 > (void*)intPtr) { if (Unsafe.AddByteOffset(ref first, intPtr) == Unsafe.AddByteOffset(ref second, intPtr)) { intPtr += 1; continue; } goto IL_013f; } goto IL_013d; } intPtr2 -= sizeof(UIntPtr); while (true) { if ((void*)intPtr2 > (void*)intPtr) { if (Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref first, intPtr)) != Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref second, intPtr))) { break; } intPtr += sizeof(UIntPtr); continue; } return Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref first, intPtr2)) == Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref second, intPtr2)); } } goto IL_013f; IL_013d: return true; IL_013f: return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateFirstFoundByte(Vector match) { Vector vector = Vector.AsVectorUInt64(match); ulong num = 0uL; int i; for (i = 0; i < Vector.Count; i++) { num = vector[i]; if (num != 0L) { break; } } return i * 8 + LocateFirstFoundByte(num); } public unsafe static int SequenceCompareTo(ref byte first, int firstLength, ref byte second, int secondLength) { if (!Unsafe.AreSame(ref first, ref second)) { IntPtr intPtr = (IntPtr)((firstLength < secondLength) ? firstLength : secondLength); IntPtr intPtr2 = (IntPtr)0; IntPtr intPtr3 = (IntPtr)(void*)intPtr; if (Vector.IsHardwareAccelerated && (nuint)(void*)intPtr3 > (nuint)Vector.Count) { intPtr3 -= Vector.Count; for (; (void*)intPtr3 > (void*)intPtr2 && !(Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref first, intPtr2)) != Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref second, intPtr2))); intPtr2 += Vector.Count) { } } else if ((nuint)(void*)intPtr3 > (nuint)sizeof(UIntPtr)) { intPtr3 -= sizeof(UIntPtr); for (; (void*)intPtr3 > (void*)intPtr2 && !(Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref first, intPtr2)) != Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref second, intPtr2))); intPtr2 += sizeof(UIntPtr)) { } } for (; (void*)intPtr > (void*)intPtr2; intPtr2 += 1) { int num = Unsafe.AddByteOffset(ref first, intPtr2).CompareTo(Unsafe.AddByteOffset(ref second, intPtr2)); if (num != 0) { return num; } } } return firstLength - secondLength; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateLastFoundByte(Vector match) { Vector vector = Vector.AsVectorUInt64(match); ulong num = 0uL; int num2; for (num2 = Vector.Count - 1; num2 >= 0; num2--) { num = vector[num2]; if (num != 0L) { break; } } return num2 * 8 + LocateLastFoundByte(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateFirstFoundByte(ulong match) { ulong num = match ^ (match - 1); return (int)(num * 283686952306184L >> 57); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateLastFoundByte(ulong match) { int num = 7; while ((long)match > 0L) { match <<= 8; num--; } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Vector GetVector(byte vectorByte) { return Vector.AsVectorByte(new Vector((uint)(vectorByte * 16843009))); } public unsafe static int SequenceCompareTo(ref char first, int firstLength, ref char second, int secondLength) { int result = firstLength - secondLength; if (!Unsafe.AreSame(ref first, ref second)) { IntPtr intPtr = (IntPtr)((firstLength < secondLength) ? firstLength : secondLength); IntPtr intPtr2 = (IntPtr)0; if ((nuint)(void*)intPtr >= (nuint)(sizeof(UIntPtr) / 2)) { if (Vector.IsHardwareAccelerated && (nuint)(void*)intPtr >= (nuint)Vector.Count) { IntPtr intPtr3 = intPtr - Vector.Count; while (!(Unsafe.ReadUnaligned>(ref Unsafe.As(ref Unsafe.Add(ref first, intPtr2))) != Unsafe.ReadUnaligned>(ref Unsafe.As(ref Unsafe.Add(ref second, intPtr2))))) { intPtr2 += Vector.Count; if ((void*)intPtr3 < (void*)intPtr2) { break; } } } for (; (void*)intPtr >= (void*)(intPtr2 + sizeof(UIntPtr) / 2) && !(Unsafe.ReadUnaligned(ref Unsafe.As(ref Unsafe.Add(ref first, intPtr2))) != Unsafe.ReadUnaligned(ref Unsafe.As(ref Unsafe.Add(ref second, intPtr2)))); intPtr2 += sizeof(UIntPtr) / 2) { } } if (sizeof(UIntPtr) > 4 && (void*)intPtr >= (void*)(intPtr2 + 2) && Unsafe.ReadUnaligned(ref Unsafe.As(ref Unsafe.Add(ref first, intPtr2))) == Unsafe.ReadUnaligned(ref Unsafe.As(ref Unsafe.Add(ref second, intPtr2)))) { intPtr2 += 2; } for (; (void*)intPtr2 < (void*)intPtr; intPtr2 += 1) { int num = Unsafe.Add(ref first, intPtr2).CompareTo(Unsafe.Add(ref second, intPtr2)); if (num != 0) { return num; } } } return result; } public unsafe static int IndexOf(ref char searchSpace, char value, int length) { fixed (char* ptr = &searchSpace) { char* ptr2 = ptr; char* ptr3 = ptr2 + length; if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { int num = ((int)ptr2 & (Unsafe.SizeOf>() - 1)) / 2; length = (Vector.Count - num) & (Vector.Count - 1); } while (true) { if (length >= 4) { length -= 4; if (*ptr2 == value) { break; } if (ptr2[1] != value) { if (ptr2[2] != value) { if (ptr2[3] != value) { ptr2 += 4; continue; } ptr2++; } ptr2++; } ptr2++; break; } while (length > 0) { length--; if (*ptr2 == value) { goto end_IL_0079; } ptr2++; } if (Vector.IsHardwareAccelerated && ptr2 < ptr3) { length = (int)((ptr3 - ptr2) & ~(Vector.Count - 1)); Vector left = new Vector(value); while (length > 0) { Vector vector = Vector.Equals(left, Unsafe.Read>(ptr2)); if (Vector.Zero.Equals(vector)) { ptr2 += Vector.Count; length -= Vector.Count; continue; } return (int)(ptr2 - ptr) + LocateFirstFoundChar(vector); } if (ptr2 < ptr3) { length = (int)(ptr3 - ptr2); continue; } } return -1; continue; end_IL_0079: break; } return (int)(ptr2 - ptr); } } public unsafe static int LastIndexOf(ref char searchSpace, char value, int length) { fixed (char* ptr = &searchSpace) { char* ptr2 = ptr + length; char* ptr3 = ptr; if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { length = ((int)ptr2 & (Unsafe.SizeOf>() - 1)) / 2; } while (true) { if (length >= 4) { length -= 4; ptr2 -= 4; if (ptr2[3] == value) { break; } if (ptr2[2] != value) { if (ptr2[1] != value) { if (*ptr2 != value) { continue; } goto IL_011d; } return (int)(ptr2 - ptr3) + 1; } return (int)(ptr2 - ptr3) + 2; } while (length > 0) { length--; ptr2--; if (*ptr2 != value) { continue; } goto IL_011d; } if (Vector.IsHardwareAccelerated && ptr2 > ptr3) { length = (int)((ptr2 - ptr3) & ~(Vector.Count - 1)); Vector left = new Vector(value); while (length > 0) { char* ptr4 = ptr2 - Vector.Count; Vector vector = Vector.Equals(left, Unsafe.Read>(ptr4)); if (Vector.Zero.Equals(vector)) { ptr2 -= Vector.Count; length -= Vector.Count; continue; } return (int)(ptr4 - ptr3) + LocateLastFoundChar(vector); } if (ptr2 > ptr3) { length = (int)(ptr2 - ptr3); continue; } } return -1; IL_011d: return (int)(ptr2 - ptr3); } return (int)(ptr2 - ptr3) + 3; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateFirstFoundChar(Vector match) { Vector vector = Vector.AsVectorUInt64(match); ulong num = 0uL; int i; for (i = 0; i < Vector.Count; i++) { num = vector[i]; if (num != 0L) { break; } } return i * 4 + LocateFirstFoundChar(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateFirstFoundChar(ulong match) { ulong num = match ^ (match - 1); return (int)(num * 4295098372L >> 49); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateLastFoundChar(Vector match) { Vector vector = Vector.AsVectorUInt64(match); ulong num = 0uL; int num2; for (num2 = Vector.Count - 1; num2 >= 0; num2--) { num = vector[num2]; if (num != 0L) { break; } } return num2 * 4 + LocateLastFoundChar(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateLastFoundChar(ulong match) { int num = 3; while ((long)match > 0L) { match <<= 16; num--; } return num; } public static int IndexOf(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) where T : IEquatable { if (valueLength == 0) { return 0; } T value2 = value; ref T 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 unsafe static int IndexOf(ref T searchSpace, T value, int length) where T : IEquatable { IntPtr intPtr = (IntPtr)0; while (true) { if (length >= 8) { length -= 8; if (!value.Equals(Unsafe.Add(ref searchSpace, intPtr))) { if (value.Equals(Unsafe.Add(ref searchSpace, intPtr + 1))) { goto IL_020a; } if (value.Equals(Unsafe.Add(ref searchSpace, intPtr + 2))) { goto IL_0218; } if (!value.Equals(Unsafe.Add(ref searchSpace, intPtr + 3))) { if (!value.Equals(Unsafe.Add(ref searchSpace, intPtr + 4))) { if (!value.Equals(Unsafe.Add(ref searchSpace, intPtr + 5))) { if (!value.Equals(Unsafe.Add(ref searchSpace, intPtr + 6))) { if (value.Equals(Unsafe.Add(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_0226; } } else { if (length >= 4) { length -= 4; if (value.Equals(Unsafe.Add(ref searchSpace, intPtr))) { goto IL_0202; } if (value.Equals(Unsafe.Add(ref searchSpace, intPtr + 1))) { goto IL_020a; } if (value.Equals(Unsafe.Add(ref searchSpace, intPtr + 2))) { goto IL_0218; } if (value.Equals(Unsafe.Add(ref searchSpace, intPtr + 3))) { goto IL_0226; } intPtr += 4; } while (true) { if (length > 0) { if (value.Equals(Unsafe.Add(ref searchSpace, intPtr))) { break; } intPtr += 1; length--; continue; } return -1; } } goto IL_0202; IL_0218: return (int)(void*)(intPtr + 2); IL_0202: return (int)(void*)intPtr; IL_020a: return (int)(void*)(intPtr + 1); IL_0226: return (int)(void*)(intPtr + 3); } return (int)(void*)(intPtr + 7); } public static int IndexOfAny(ref T searchSpace, T value0, T value1, int length) where T : IEquatable { int num = 0; while (true) { if (length - num >= 8) { T other = Unsafe.Add(ref searchSpace, num); if (!value0.Equals(other) && !value1.Equals(other)) { other = Unsafe.Add(ref searchSpace, num + 1); if (value0.Equals(other) || value1.Equals(other)) { goto IL_02cb; } other = Unsafe.Add(ref searchSpace, num + 2); if (value0.Equals(other) || value1.Equals(other)) { goto IL_02cf; } other = Unsafe.Add(ref searchSpace, num + 3); if (!value0.Equals(other) && !value1.Equals(other)) { other = Unsafe.Add(ref searchSpace, num + 4); if (!value0.Equals(other) && !value1.Equals(other)) { other = Unsafe.Add(ref searchSpace, num + 5); if (!value0.Equals(other) && !value1.Equals(other)) { other = Unsafe.Add(ref searchSpace, num + 6); if (!value0.Equals(other) && !value1.Equals(other)) { other = Unsafe.Add(ref searchSpace, num + 7); if (value0.Equals(other) || value1.Equals(other)) { break; } num += 8; continue; } return num + 6; } return num + 5; } return num + 4; } goto IL_02d3; } } else { if (length - num >= 4) { T other = Unsafe.Add(ref searchSpace, num); if (value0.Equals(other) || value1.Equals(other)) { goto IL_02c9; } other = Unsafe.Add(ref searchSpace, num + 1); if (value0.Equals(other) || value1.Equals(other)) { goto IL_02cb; } other = Unsafe.Add(ref searchSpace, num + 2); if (value0.Equals(other) || value1.Equals(other)) { goto IL_02cf; } other = Unsafe.Add(ref searchSpace, num + 3); if (value0.Equals(other) || value1.Equals(other)) { goto IL_02d3; } num += 4; } while (true) { if (num < length) { T other = Unsafe.Add(ref searchSpace, num); if (value0.Equals(other) || value1.Equals(other)) { break; } num++; continue; } return -1; } } goto IL_02c9; IL_02cf: return num + 2; IL_02cb: return num + 1; IL_02d3: return num + 3; IL_02c9: return num; } return num + 7; } public static int IndexOfAny(ref T searchSpace, T value0, T value1, T value2, int length) where T : IEquatable { int num = 0; while (true) { if (length - num >= 8) { T other = Unsafe.Add(ref searchSpace, num); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { other = Unsafe.Add(ref searchSpace, num + 1); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_03c2; } other = Unsafe.Add(ref searchSpace, num + 2); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_03c6; } other = Unsafe.Add(ref searchSpace, num + 3); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { other = Unsafe.Add(ref searchSpace, num + 4); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { other = Unsafe.Add(ref searchSpace, num + 5); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { other = Unsafe.Add(ref searchSpace, num + 6); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { other = Unsafe.Add(ref searchSpace, num + 7); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { break; } num += 8; continue; } return num + 6; } return num + 5; } return num + 4; } goto IL_03ca; } } else { if (length - num >= 4) { T other = Unsafe.Add(ref searchSpace, num); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_03c0; } other = Unsafe.Add(ref searchSpace, num + 1); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_03c2; } other = Unsafe.Add(ref searchSpace, num + 2); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_03c6; } other = Unsafe.Add(ref searchSpace, num + 3); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_03ca; } num += 4; } while (true) { if (num < length) { T other = Unsafe.Add(ref searchSpace, num); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { break; } num++; continue; } return -1; } } goto IL_03c0; IL_03c0: return num; IL_03c6: return num + 2; IL_03c2: return num + 1; IL_03ca: return num + 3; } return num + 7; } public static int IndexOfAny(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) where T : IEquatable { 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 LastIndexOf(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) where T : IEquatable { if (valueLength == 0) { return 0; } T value2 = value; ref T 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 static int LastIndexOf(ref T searchSpace, T value, int length) where T : IEquatable { while (true) { if (length >= 8) { length -= 8; if (value.Equals(Unsafe.Add(ref searchSpace, length + 7))) { break; } if (value.Equals(Unsafe.Add(ref searchSpace, length + 6))) { return length + 6; } if (value.Equals(Unsafe.Add(ref searchSpace, length + 5))) { return length + 5; } if (value.Equals(Unsafe.Add(ref searchSpace, length + 4))) { return length + 4; } if (value.Equals(Unsafe.Add(ref searchSpace, length + 3))) { goto IL_01c2; } if (value.Equals(Unsafe.Add(ref searchSpace, length + 2))) { goto IL_01be; } if (value.Equals(Unsafe.Add(ref searchSpace, length + 1))) { goto IL_01ba; } if (!value.Equals(Unsafe.Add(ref searchSpace, length))) { continue; } } else { if (length >= 4) { length -= 4; if (value.Equals(Unsafe.Add(ref searchSpace, length + 3))) { goto IL_01c2; } if (value.Equals(Unsafe.Add(ref searchSpace, length + 2))) { goto IL_01be; } if (value.Equals(Unsafe.Add(ref searchSpace, length + 1))) { goto IL_01ba; } if (value.Equals(Unsafe.Add(ref searchSpace, length))) { goto IL_01b8; } } do { if (length > 0) { length--; continue; } return -1; } while (!value.Equals(Unsafe.Add(ref searchSpace, length))); } goto IL_01b8; IL_01be: return length + 2; IL_01c2: return length + 3; IL_01ba: return length + 1; IL_01b8: return length; } return length + 7; } public static int LastIndexOfAny(ref T searchSpace, T value0, T value1, int length) where T : IEquatable { while (true) { if (length >= 8) { length -= 8; T other = Unsafe.Add(ref searchSpace, length + 7); if (value0.Equals(other) || value1.Equals(other)) { break; } other = Unsafe.Add(ref searchSpace, length + 6); if (value0.Equals(other) || value1.Equals(other)) { return length + 6; } other = Unsafe.Add(ref searchSpace, length + 5); if (value0.Equals(other) || value1.Equals(other)) { return length + 5; } other = Unsafe.Add(ref searchSpace, length + 4); if (value0.Equals(other) || value1.Equals(other)) { return length + 4; } other = Unsafe.Add(ref searchSpace, length + 3); if (value0.Equals(other) || value1.Equals(other)) { goto IL_02cd; } other = Unsafe.Add(ref searchSpace, length + 2); if (value0.Equals(other) || value1.Equals(other)) { goto IL_02c9; } other = Unsafe.Add(ref searchSpace, length + 1); if (value0.Equals(other) || value1.Equals(other)) { goto IL_02c5; } other = Unsafe.Add(ref searchSpace, length); if (!value0.Equals(other) && !value1.Equals(other)) { continue; } } else { T other; if (length >= 4) { length -= 4; other = Unsafe.Add(ref searchSpace, length + 3); if (value0.Equals(other) || value1.Equals(other)) { goto IL_02cd; } other = Unsafe.Add(ref searchSpace, length + 2); if (value0.Equals(other) || value1.Equals(other)) { goto IL_02c9; } other = Unsafe.Add(ref searchSpace, length + 1); if (value0.Equals(other) || value1.Equals(other)) { goto IL_02c5; } other = Unsafe.Add(ref searchSpace, length); if (value0.Equals(other) || value1.Equals(other)) { goto IL_02c3; } } do { if (length > 0) { length--; other = Unsafe.Add(ref searchSpace, length); continue; } return -1; } while (!value0.Equals(other) && !value1.Equals(other)); } goto IL_02c3; IL_02c9: return length + 2; IL_02c5: return length + 1; IL_02c3: return length; IL_02cd: return length + 3; } return length + 7; } public static int LastIndexOfAny(ref T searchSpace, T value0, T value1, T value2, int length) where T : IEquatable { while (true) { if (length >= 8) { length -= 8; T other = Unsafe.Add(ref searchSpace, length + 7); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { break; } other = Unsafe.Add(ref searchSpace, length + 6); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { return length + 6; } other = Unsafe.Add(ref searchSpace, length + 5); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { return length + 5; } other = Unsafe.Add(ref searchSpace, length + 4); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { return length + 4; } other = Unsafe.Add(ref searchSpace, length + 3); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_03da; } other = Unsafe.Add(ref searchSpace, length + 2); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_03d5; } other = Unsafe.Add(ref searchSpace, length + 1); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_03d0; } other = Unsafe.Add(ref searchSpace, length); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { continue; } } else { T other; if (length >= 4) { length -= 4; other = Unsafe.Add(ref searchSpace, length + 3); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_03da; } other = Unsafe.Add(ref searchSpace, length + 2); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_03d5; } other = Unsafe.Add(ref searchSpace, length + 1); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_03d0; } other = Unsafe.Add(ref searchSpace, length); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_03cd; } } do { if (length > 0) { length--; other = Unsafe.Add(ref searchSpace, length); continue; } return -1; } while (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)); } goto IL_03cd; IL_03d0: return length + 1; IL_03d5: return length + 2; IL_03da: return length + 3; IL_03cd: return length; } return length + 7; } public static int LastIndexOfAny(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) where T : IEquatable { 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 static bool SequenceEqual(ref T first, ref T second, int length) where T : IEquatable { if (!Unsafe.AreSame(ref first, ref second)) { IntPtr intPtr = (IntPtr)0; while (true) { if (length >= 8) { length -= 8; if (Unsafe.Add(ref first, intPtr).Equals(Unsafe.Add(ref second, intPtr)) && Unsafe.Add(ref first, intPtr + 1).Equals(Unsafe.Add(ref second, intPtr + 1)) && Unsafe.Add(ref first, intPtr + 2).Equals(Unsafe.Add(ref second, intPtr + 2)) && Unsafe.Add(ref first, intPtr + 3).Equals(Unsafe.Add(ref second, intPtr + 3)) && Unsafe.Add(ref first, intPtr + 4).Equals(Unsafe.Add(ref second, intPtr + 4)) && Unsafe.Add(ref first, intPtr + 5).Equals(Unsafe.Add(ref second, intPtr + 5)) && Unsafe.Add(ref first, intPtr + 6).Equals(Unsafe.Add(ref second, intPtr + 6)) && Unsafe.Add(ref first, intPtr + 7).Equals(Unsafe.Add(ref second, intPtr + 7))) { intPtr += 8; continue; } goto IL_028b; } if (length >= 4) { length -= 4; if (!Unsafe.Add(ref first, intPtr).Equals(Unsafe.Add(ref second, intPtr)) || !Unsafe.Add(ref first, intPtr + 1).Equals(Unsafe.Add(ref second, intPtr + 1)) || !Unsafe.Add(ref first, intPtr + 2).Equals(Unsafe.Add(ref second, intPtr + 2)) || !Unsafe.Add(ref first, intPtr + 3).Equals(Unsafe.Add(ref second, intPtr + 3))) { goto IL_028b; } intPtr += 4; } while (length > 0) { if (Unsafe.Add(ref first, intPtr).Equals(Unsafe.Add(ref second, intPtr))) { intPtr += 1; length--; continue; } goto IL_028b; } break; IL_028b: return false; } } return true; } public static int SequenceCompareTo(ref T first, int firstLength, ref T second, int secondLength) where T : IComparable { int num = firstLength; if (num > secondLength) { num = secondLength; } for (int i = 0; i < num; i++) { int num2 = Unsafe.Add(ref first, i).CompareTo(Unsafe.Add(ref second, i)); if (num2 != 0) { return num2; } } return firstLength.CompareTo(secondLength); } public unsafe static void CopyTo(ref T dst, int dstLength, ref T src, int srcLength) { IntPtr intPtr = Unsafe.ByteOffset(ref src, ref Unsafe.Add(ref src, srcLength)); IntPtr intPtr2 = Unsafe.ByteOffset(ref dst, ref Unsafe.Add(ref dst, dstLength)); IntPtr intPtr3 = Unsafe.ByteOffset(ref src, ref dst); bool num; if (sizeof(IntPtr) != 4) { if ((ulong)(long)intPtr3 >= (ulong)(long)intPtr) { num = (ulong)(long)intPtr3 > (ulong)(-(long)intPtr2); goto IL_006f; } } else if ((uint)(int)intPtr3 >= (uint)(int)intPtr) { num = (uint)(int)intPtr3 > (uint)(-(int)intPtr2); goto IL_006f; } goto IL_00de; IL_00de: bool flag = ((sizeof(IntPtr) == 4) ? ((uint)(int)intPtr3 > (uint)(-(int)intPtr2)) : ((ulong)(long)intPtr3 > (ulong)(-(long)intPtr2))); int num2 = (flag ? 1 : (-1)); int num3 = ((!flag) ? (srcLength - 1) : 0); int i; for (i = 0; i < (srcLength & -8); i += 8) { Unsafe.Add(ref dst, num3) = Unsafe.Add(ref src, num3); Unsafe.Add(ref dst, num3 + num2) = Unsafe.Add(ref src, num3 + num2); Unsafe.Add(ref dst, num3 + num2 * 2) = Unsafe.Add(ref src, num3 + num2 * 2); Unsafe.Add(ref dst, num3 + num2 * 3) = Unsafe.Add(ref src, num3 + num2 * 3); Unsafe.Add(ref dst, num3 + num2 * 4) = Unsafe.Add(ref src, num3 + num2 * 4); Unsafe.Add(ref dst, num3 + num2 * 5) = Unsafe.Add(ref src, num3 + num2 * 5); Unsafe.Add(ref dst, num3 + num2 * 6) = Unsafe.Add(ref src, num3 + num2 * 6); Unsafe.Add(ref dst, num3 + num2 * 7) = Unsafe.Add(ref src, num3 + num2 * 7); num3 += num2 * 8; } if (i < (srcLength & -4)) { Unsafe.Add(ref dst, num3) = Unsafe.Add(ref src, num3); Unsafe.Add(ref dst, num3 + num2) = Unsafe.Add(ref src, num3 + num2); Unsafe.Add(ref dst, num3 + num2 * 2) = Unsafe.Add(ref src, num3 + num2 * 2); Unsafe.Add(ref dst, num3 + num2 * 3) = Unsafe.Add(ref src, num3 + num2 * 3); num3 += num2 * 4; i += 4; } for (; i < srcLength; i++) { Unsafe.Add(ref dst, num3) = Unsafe.Add(ref src, num3); num3 += num2; } return; IL_006f: if (!num && !IsReferenceOrContainsReferences()) { ref byte source = ref Unsafe.As(ref dst); ref byte source2 = ref Unsafe.As(ref src); ulong num4 = (ulong)(long)intPtr; uint num6; for (ulong num5 = 0uL; num5 < num4; num5 += num6) { num6 = (uint)((num4 - num5 > uint.MaxValue) ? uint.MaxValue : (num4 - num5)); Unsafe.CopyBlock(ref Unsafe.Add(ref source, (IntPtr)(long)num5), ref Unsafe.Add(ref source2, (IntPtr)(long)num5), num6); } return; } goto IL_00de; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static IntPtr Add(this IntPtr start, int index) { if (sizeof(IntPtr) == 4) { uint num = (uint)(index * Unsafe.SizeOf()); return (IntPtr)((byte*)(void*)start + num); } ulong num2 = (ulong)index * (ulong)Unsafe.SizeOf(); return (IntPtr)((byte*)(void*)start + num2); } public static bool IsReferenceOrContainsReferences() { return PerTypeValues.IsReferenceOrContainsReferences; } private static bool IsReferenceOrContainsReferencesCore(Type type) { if (type.GetTypeInfo().IsPrimitive) { return false; } if (!type.GetTypeInfo().IsValueType) { return true; } Type underlyingType = Nullable.GetUnderlyingType(type); if (underlyingType != null) { type = underlyingType; } if (type.GetTypeInfo().IsEnum) { return false; } foreach (FieldInfo declaredField in type.GetTypeInfo().DeclaredFields) { if (!declaredField.IsStatic && IsReferenceOrContainsReferencesCore(declaredField.FieldType)) { return true; } } return false; } public unsafe static void ClearLessThanPointerSized(byte* ptr, UIntPtr byteLength) { if (sizeof(UIntPtr) == 4) { Unsafe.InitBlockUnaligned(ptr, 0, (uint)byteLength); return; } ulong num = (ulong)byteLength; uint num2 = (uint)(num & 0xFFFFFFFFu); Unsafe.InitBlockUnaligned(ptr, 0, num2); num -= num2; ptr += num2; while (num != 0) { num2 = (uint)((num >= uint.MaxValue) ? uint.MaxValue : num); Unsafe.InitBlockUnaligned(ptr, 0, num2); ptr += num2; num -= num2; } } public unsafe static void ClearLessThanPointerSized(ref byte b, UIntPtr byteLength) { if (sizeof(UIntPtr) == 4) { Unsafe.InitBlockUnaligned(ref b, 0, (uint)byteLength); return; } ulong num = (ulong)byteLength; uint num2 = (uint)(num & 0xFFFFFFFFu); Unsafe.InitBlockUnaligned(ref b, 0, num2); num -= num2; long num3 = num2; while (num != 0) { num2 = (uint)((num >= uint.MaxValue) ? uint.MaxValue : num); Unsafe.InitBlockUnaligned(ref Unsafe.Add(ref b, (IntPtr)num3), 0, num2); num3 += num2; num -= num2; } } public unsafe static void ClearPointerSizedWithoutReferences(ref byte b, UIntPtr byteLength) { IntPtr zero; for (zero = IntPtr.Zero; zero.LessThanEqual(byteLength - sizeof(Reg64)); zero += sizeof(Reg64)) { Unsafe.As(ref Unsafe.Add(ref b, zero)) = default(Reg64); } if (zero.LessThanEqual(byteLength - sizeof(Reg32))) { Unsafe.As(ref Unsafe.Add(ref b, zero)) = default(Reg32); zero += sizeof(Reg32); } if (zero.LessThanEqual(byteLength - sizeof(Reg16))) { Unsafe.As(ref Unsafe.Add(ref b, zero)) = default(Reg16); zero += sizeof(Reg16); } if (zero.LessThanEqual(byteLength - 8)) { Unsafe.As(ref Unsafe.Add(ref b, zero)) = 0L; zero += 8; } if (sizeof(IntPtr) == 4 && zero.LessThanEqual(byteLength - 4)) { Unsafe.As(ref Unsafe.Add(ref b, zero)) = 0; zero += 4; } } public static void ClearPointerSizedWithReferences(ref IntPtr ip, UIntPtr pointerSizeLength) { IntPtr intPtr = IntPtr.Zero; IntPtr zero = IntPtr.Zero; while ((zero = intPtr + 8).LessThanEqual(pointerSizeLength)) { Unsafe.Add(ref ip, intPtr + 0) = default(IntPtr); Unsafe.Add(ref ip, intPtr + 1) = default(IntPtr); Unsafe.Add(ref ip, intPtr + 2) = default(IntPtr); Unsafe.Add(ref ip, intPtr + 3) = default(IntPtr); Unsafe.Add(ref ip, intPtr + 4) = default(IntPtr); Unsafe.Add(ref ip, intPtr + 5) = default(IntPtr); Unsafe.Add(ref ip, intPtr + 6) = default(IntPtr); Unsafe.Add(ref ip, intPtr + 7) = default(IntPtr); intPtr = zero; } if ((zero = intPtr + 4).LessThanEqual(pointerSizeLength)) { Unsafe.Add(ref ip, intPtr + 0) = default(IntPtr); Unsafe.Add(ref ip, intPtr + 1) = default(IntPtr); Unsafe.Add(ref ip, intPtr + 2) = default(IntPtr); Unsafe.Add(ref ip, intPtr + 3) = default(IntPtr); intPtr = zero; } if ((zero = intPtr + 2).LessThanEqual(pointerSizeLength)) { Unsafe.Add(ref ip, intPtr + 0) = default(IntPtr); Unsafe.Add(ref ip, intPtr + 1) = default(IntPtr); intPtr = zero; } if ((intPtr + 1).LessThanEqual(pointerSizeLength)) { Unsafe.Add(ref ip, intPtr) = default(IntPtr); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe static bool LessThanEqual(this IntPtr index, UIntPtr length) { if (sizeof(UIntPtr) != 4) { return (long)index <= (long)(ulong)length; } return (int)index <= (int)(uint)length; } } internal struct NUInt { private unsafe readonly void* _value; private unsafe NUInt(uint value) { _value = (void*)value; } private unsafe NUInt(ulong value) { _value = (void*)value; } public static implicit operator NUInt(uint value) { return new NUInt(value); } public unsafe static implicit operator IntPtr(NUInt value) { return (IntPtr)value._value; } public static explicit operator NUInt(int value) { return new NUInt((uint)value); } public unsafe static explicit operator void*(NUInt value) { return value._value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static NUInt operator *(NUInt left, NUInt right) { if (sizeof(IntPtr) != 4) { return new NUInt((ulong)left._value * (ulong)right._value); } return new NUInt((uint)((int)left._value * (int)right._value)); } } [StructLayout(LayoutKind.Sequential)] internal sealed class Pinnable { public T Data; } internal static class NotImplemented { internal static Exception ByDesign => new NotImplementedException(); internal static Exception ByDesignWithMessage(string message) { return new NotImplementedException(message); } internal static Exception ActiveIssue(string issue) { return new NotImplementedException(); } } internal struct MutableDecimal { public uint Flags; public uint High; public uint Low; public uint Mid; private const uint SignMask = 2147483648u; private const uint ScaleMask = 16711680u; private const int ScaleShift = 16; public bool IsNegative { get { return (Flags & 0x80000000u) != 0; } set { Flags = (Flags & 0x7FFFFFFFu) | (value ? 2147483648u : 0u); } } public int Scale { get { return (byte)(Flags >> 16); } set { Flags = (Flags & 0xFF00FFFFu) | (uint)(value << 16); } } } internal static class <364de6aa-3638-4f0c-b478-eff7d6f86309>SR { private static ResourceManager s_resourceManager; private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); internal static Type ResourceType { get; } = typeof(FxResources.System.Memory.SR); internal static string NotSupported_CannotCallEqualsOnSpan => GetResourceString("NotSupported_CannotCallEqualsOnSpan", null); internal static string NotSupported_CannotCallGetHashCodeOnSpan => GetResourceString("NotSupported_CannotCallGetHashCodeOnSpan", null); internal static string Argument_InvalidTypeWithPointersNotSupported => GetResourceString("Argument_InvalidTypeWithPointersNotSupported", null); internal static string Argument_DestinationTooShort => GetResourceString("Argument_DestinationTooShort", null); internal static string MemoryDisposed => GetResourceString("MemoryDisposed", null); internal static string OutstandingReferences => GetResourceString("OutstandingReferences", null); internal static string Argument_BadFormatSpecifier => GetResourceString("Argument_BadFormatSpecifier", null); internal static string Argument_GWithPrecisionNotSupported => GetResourceString("Argument_GWithPrecisionNotSupported", null); internal static string Argument_CannotParsePrecision => GetResourceString("Argument_CannotParsePrecision", null); internal static string Argument_PrecisionTooLarge => GetResourceString("Argument_PrecisionTooLarge", null); internal static string Argument_OverlapAlignmentMismatch => GetResourceString("Argument_OverlapAlignmentMismatch", null); internal static string EndPositionNotReached => GetResourceString("EndPositionNotReached", null); internal static string UnexpectedSegmentType => GetResourceString("UnexpectedSegmentType", null); [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.Hashing { internal static class <364de6aa-3638-4f0c-b478-eff7d6f86309>HashHelpers { public static readonly int RandomSeed = Guid.NewGuid().GetHashCode(); public static int Combine(int h1, int h2) { uint num = (uint)(h1 << 5) | ((uint)h1 >> 27); return ((int)num + h1) ^ h2; } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.All)] internal class <364de6aa-3638-4f0c-b478-eff7d6f86309>__BlockReflectionAttribute : Attribute { } } namespace System.Runtime.InteropServices { internal static class SequenceMarshal { public static bool TryGetReadOnlySequenceSegment(ReadOnlySequence sequence, out ReadOnlySequenceSegment startSegment, out int startIndex, out ReadOnlySequenceSegment endSegment, out int endIndex) { return sequence.TryGetReadOnlySequenceSegment(out startSegment, out startIndex, out endSegment, out endIndex); } public static bool TryGetArray(ReadOnlySequence sequence, out ArraySegment segment) { return sequence.TryGetArray(out segment); } public static bool TryGetReadOnlyMemory(ReadOnlySequence sequence, out ReadOnlyMemory memory) { if (!sequence.IsSingleSegment) { memory = default(ReadOnlyMemory); return false; } memory = sequence.First; return true; } internal static bool TryGetString(ReadOnlySequence sequence, out string text, out int start, out int length) { return sequence.TryGetString(out text, out start, out length); } } internal static class MemoryMarshal { public static bool TryGetArray(ReadOnlyMemory memory, out ArraySegment segment) { int start; int length; object objectStartLength = memory.GetObjectStartLength(out start, out length); if (start < 0) { if (((MemoryManager)objectStartLength).TryGetArray(out var segment2)) { segment = new ArraySegment(segment2.Array, segment2.Offset + (start & 0x7FFFFFFF), length); return true; } } else if (objectStartLength is T[] array) { segment = new ArraySegment(array, start, length & 0x7FFFFFFF); return true; } if ((length & 0x7FFFFFFF) == 0) { segment = new ArraySegment(System.SpanHelpers.PerTypeValues.EmptyArray); return true; } segment = default(ArraySegment); return false; } public static bool TryGetMemoryManager(ReadOnlyMemory memory, out TManager manager) where TManager : MemoryManager { int start; int length; TManager val = (manager = memory.GetObjectStartLength(out start, out length) as TManager); return manager != null; } public static bool TryGetMemoryManager(ReadOnlyMemory memory, out TManager manager, out int start, out int length) where TManager : MemoryManager { TManager val = (manager = memory.GetObjectStartLength(out start, out length) as TManager); start &= int.MaxValue; if (manager == null) { start = 0; length = 0; return false; } return true; } public static IEnumerable ToEnumerable(ReadOnlyMemory memory) { for (int i = 0; i < memory.Length; i++) { yield return memory.Span[i]; } } public static bool TryGetString(ReadOnlyMemory memory, out string text, out int start, out int length) { if (memory.GetObjectStartLength(out var start2, out var length2) is string text2) { text = text2; start = start2; length = length2; return true; } text = null; start = 0; length = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T Read(ReadOnlySpan source) where T : struct { if (System.SpanHelpers.IsReferenceOrContainsReferences()) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } if (Unsafe.SizeOf() > source.Length) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.length); } return Unsafe.ReadUnaligned(ref GetReference(source)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryRead(ReadOnlySpan source, out T value) where T : struct { if (System.SpanHelpers.IsReferenceOrContainsReferences()) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } if (Unsafe.SizeOf() > (uint)source.Length) { value = default(T); return false; } value = Unsafe.ReadUnaligned(ref GetReference(source)); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Write(Span destination, ref T value) where T : struct { if (System.SpanHelpers.IsReferenceOrContainsReferences()) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } if ((uint)Unsafe.SizeOf() > (uint)destination.Length) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.length); } Unsafe.WriteUnaligned(ref GetReference(destination), value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWrite(Span destination, ref T value) where T : struct { if (System.SpanHelpers.IsReferenceOrContainsReferences()) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } if (Unsafe.SizeOf() > (uint)destination.Length) { return false; } Unsafe.WriteUnaligned(ref GetReference(destination), value); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Memory CreateFromPinnedArray(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(); } return default(Memory); } if (default(T) == null && array.GetType() != typeof(T[])) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(); } return new Memory((object)array, start, length | int.MinValue); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsBytes(Span span) where T : struct { if (System.SpanHelpers.IsReferenceOrContainsReferences()) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } int length = checked(span.Length * Unsafe.SizeOf()); return new Span(Unsafe.As>(span.Pinnable), span.ByteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan AsBytes(ReadOnlySpan span) where T : struct { if (System.SpanHelpers.IsReferenceOrContainsReferences()) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } int length = checked(span.Length * Unsafe.SizeOf()); return new ReadOnlySpan(Unsafe.As>(span.Pinnable), span.ByteOffset, length); } public static Memory AsMemory(ReadOnlyMemory memory) { return Unsafe.As, Memory>(ref memory); } public unsafe static ref T GetReference(Span span) { if (span.Pinnable == null) { return ref Unsafe.AsRef(span.ByteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref span.Pinnable.Data, span.ByteOffset); } public unsafe static ref T GetReference(ReadOnlySpan span) { if (span.Pinnable == null) { return ref Unsafe.AsRef(span.ByteOffset.ToPointer()); } return ref Unsafe.AddByteOffset(ref span.Pinnable.Data, span.ByteOffset); } public static Span Cast(Span span) where TFrom : struct where TTo : struct { if (System.SpanHelpers.IsReferenceOrContainsReferences()) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(TFrom)); } if (System.SpanHelpers.IsReferenceOrContainsReferences()) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(TTo)); } checked { int length = (int)unchecked(checked(unchecked((long)span.Length) * unchecked((long)Unsafe.SizeOf())) / Unsafe.SizeOf()); return new Span(Unsafe.As>(span.Pinnable), span.ByteOffset, length); } } public static ReadOnlySpan Cast(ReadOnlySpan span) where TFrom : struct where TTo : struct { if (System.SpanHelpers.IsReferenceOrContainsReferences()) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(TFrom)); } if (System.SpanHelpers.IsReferenceOrContainsReferences()) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(TTo)); } checked { int length = (int)unchecked(checked(unchecked((long)span.Length) * unchecked((long)Unsafe.SizeOf())) / Unsafe.SizeOf()); return new ReadOnlySpan(Unsafe.As>(span.Pinnable), span.ByteOffset, length); } } } } namespace System.Buffers { internal sealed class ArrayMemoryPool : MemoryPool { private sealed class ArrayMemoryPoolBuffer : IMemoryOwner, IDisposable { private T[] _array; public Memory Memory { get { T[] array = _array; if (array == null) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowObjectDisposedException_ArrayMemoryPoolBuffer(); } return new Memory(array); } } public ArrayMemoryPoolBuffer(int size) { _array = ArrayPool.Shared.Rent(size); } public void Dispose() { T[] array = _array; if (array != null) { _array = null; ArrayPool.Shared.Return(array); } } } private const int s_maxBufferSize = int.MaxValue; public sealed override int MaxBufferSize => int.MaxValue; public sealed override IMemoryOwner Rent(int minimumBufferSize = -1) { if (minimumBufferSize == -1) { minimumBufferSize = 1 + 4095 / Unsafe.SizeOf(); } else if ((uint)minimumBufferSize > 2147483647u) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.minimumBufferSize); } return new ArrayMemoryPoolBuffer(minimumBufferSize); } protected sealed override void Dispose(bool disposing) { } } internal static class BuffersExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static SequencePosition? PositionOf(this in ReadOnlySequence source, T value) where T : IEquatable { if (source.IsSingleSegment) { int num = source.First.Span.IndexOf(value); if (num != -1) { return source.GetPosition(num); } return null; } return PositionOfMultiSegment(in source, value); } private static SequencePosition? PositionOfMultiSegment(in ReadOnlySequence source, T value) where T : IEquatable { SequencePosition position = source.Start; SequencePosition origin = position; ReadOnlyMemory memory; while (source.TryGet(ref position, out memory)) { int num = memory.Span.IndexOf(value); if (num != -1) { return source.GetPosition(num, origin); } if (position.GetObject() == null) { break; } origin = position; } return null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo(this in ReadOnlySequence source, Span destination) { if (source.Length > destination.Length) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.destination); } if (source.IsSingleSegment) { source.First.Span.CopyTo(destination); } else { CopyToMultiSegment(in source, destination); } } private static void CopyToMultiSegment(in ReadOnlySequence sequence, Span destination) { SequencePosition position = sequence.Start; ReadOnlyMemory memory; while (sequence.TryGet(ref position, out memory)) { ReadOnlySpan span = memory.Span; span.CopyTo(destination); if (position.GetObject() != null) { destination = destination.Slice(span.Length); continue; } break; } } public static T[] ToArray(this in ReadOnlySequence sequence) { T[] array = new T[sequence.Length]; CopyTo(in sequence, array); return array; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Write(this IBufferWriter writer, ReadOnlySpan value) { Span span = writer.GetSpan(); if (value.Length <= span.Length) { value.CopyTo(span); writer.Advance(value.Length); } else { WriteMultiSegment(writer, in value, span); } } private static void WriteMultiSegment(IBufferWriter writer, in ReadOnlySpan source, Span destination) { ReadOnlySpan readOnlySpan = source; while (true) { int num = Math.Min(destination.Length, readOnlySpan.Length); readOnlySpan.Slice(0, num).CopyTo(destination); writer.Advance(num); readOnlySpan = readOnlySpan.Slice(num); if (readOnlySpan.Length > 0) { destination = writer.GetSpan(readOnlySpan.Length); continue; } break; } } } internal interface IBufferWriter { void Advance(int count); Memory GetMemory(int sizeHint = 0); Span GetSpan(int sizeHint = 0); } internal abstract class MemoryPool : IDisposable { private static readonly MemoryPool s_shared = new System.Buffers.ArrayMemoryPool(); public static MemoryPool Shared => s_shared; public abstract int MaxBufferSize { get; } public abstract IMemoryOwner Rent(int minBufferSize = -1); public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected abstract void Dispose(bool disposing); } internal enum OperationStatus { Done, DestinationTooSmall, NeedMoreData, InvalidData } [DebuggerTypeProxy(typeof(System.Buffers.ReadOnlySequenceDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] internal readonly struct ReadOnlySequence { public struct Enumerator { private readonly ReadOnlySequence _sequence; private SequencePosition _next; private ReadOnlyMemory _currentMemory; public ReadOnlyMemory Current => _currentMemory; public Enumerator(in ReadOnlySequence sequence) { _currentMemory = default(ReadOnlyMemory); _next = sequence.Start; _sequence = sequence; } public bool MoveNext() { if (_next.GetObject() == null) { return false; } return _sequence.TryGet(ref _next, out _currentMemory); } } private enum SequenceType { MultiSegment, Array, MemoryManager, String, Empty } private readonly SequencePosition _sequenceStart; private readonly SequencePosition _sequenceEnd; public static readonly ReadOnlySequence Empty = new ReadOnlySequence(System.SpanHelpers.PerTypeValues.EmptyArray); public long Length => GetLength(); public bool IsEmpty => Length == 0; public bool IsSingleSegment { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _sequenceStart.GetObject() == _sequenceEnd.GetObject(); } } public ReadOnlyMemory First => GetFirstBuffer(); public SequencePosition Start => _sequenceStart; public SequencePosition End => _sequenceEnd; [MethodImpl(MethodImplOptions.AggressiveInlining)] private ReadOnlySequence(object startSegment, int startIndexAndFlags, object endSegment, int endIndexAndFlags) { _sequenceStart = new SequencePosition(startSegment, startIndexAndFlags); _sequenceEnd = new SequencePosition(endSegment, endIndexAndFlags); } public ReadOnlySequence(ReadOnlySequenceSegment startSegment, int startIndex, ReadOnlySequenceSegment endSegment, int endIndex) { if (startSegment == null || endSegment == null || (startSegment != endSegment && startSegment.RunningIndex > endSegment.RunningIndex) || (uint)startSegment.Memory.Length < (uint)startIndex || (uint)endSegment.Memory.Length < (uint)endIndex || (startSegment == endSegment && endIndex < startIndex)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentValidationException(startSegment, startIndex, endSegment); } _sequenceStart = new SequencePosition(startSegment, System.Buffers.ReadOnlySequence.SegmentToSequenceStart(startIndex)); _sequenceEnd = new SequencePosition(endSegment, System.Buffers.ReadOnlySequence.SegmentToSequenceEnd(endIndex)); } public ReadOnlySequence(T[] array) { if (array == null) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentNullException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.array); } _sequenceStart = new SequencePosition(array, System.Buffers.ReadOnlySequence.ArrayToSequenceStart(0)); _sequenceEnd = new SequencePosition(array, System.Buffers.ReadOnlySequence.ArrayToSequenceEnd(array.Length)); } public ReadOnlySequence(T[] array, int start, int length) { if (array == null || (uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentValidationException(array, start); } _sequenceStart = new SequencePosition(array, System.Buffers.ReadOnlySequence.ArrayToSequenceStart(start)); _sequenceEnd = new SequencePosition(array, System.Buffers.ReadOnlySequence.ArrayToSequenceEnd(start + length)); } public ReadOnlySequence(ReadOnlyMemory memory) { ArraySegment segment; if (MemoryMarshal.TryGetMemoryManager>(memory, out var manager, out var start, out var length)) { _sequenceStart = new SequencePosition(manager, System.Buffers.ReadOnlySequence.MemoryManagerToSequenceStart(start)); _sequenceEnd = new SequencePosition(manager, System.Buffers.ReadOnlySequence.MemoryManagerToSequenceEnd(length)); } else if (MemoryMarshal.TryGetArray(memory, out segment)) { T[] array = segment.Array; int offset = segment.Offset; _sequenceStart = new SequencePosition(array, System.Buffers.ReadOnlySequence.ArrayToSequenceStart(offset)); _sequenceEnd = new SequencePosition(array, System.Buffers.ReadOnlySequence.ArrayToSequenceEnd(offset + segment.Count)); } else if (typeof(T) == typeof(char)) { if (!MemoryMarshal.TryGetString((ReadOnlyMemory)(object)memory, out var text, out var start2, out length)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowInvalidOperationException(); } _sequenceStart = new SequencePosition(text, System.Buffers.ReadOnlySequence.StringToSequenceStart(start2)); _sequenceEnd = new SequencePosition(text, System.Buffers.ReadOnlySequence.StringToSequenceEnd(start2 + length)); } else { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowInvalidOperationException(); _sequenceStart = default(SequencePosition); _sequenceEnd = default(SequencePosition); } } public ReadOnlySequence Slice(long start, long length) { if (start < 0 || length < 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowStartOrEndArgumentValidationException(start); } int index = GetIndex(in _sequenceStart); int index2 = GetIndex(in _sequenceEnd); object @object = _sequenceStart.GetObject(); object object2 = _sequenceEnd.GetObject(); SequencePosition start2; SequencePosition end; if (@object != object2) { ReadOnlySequenceSegment readOnlySequenceSegment = (ReadOnlySequenceSegment)@object; int num = readOnlySequenceSegment.Memory.Length - index; if (num > start) { index += (int)start; start2 = new SequencePosition(@object, index); end = GetEndPosition(readOnlySequenceSegment, @object, index, object2, index2, length); } else { if (num < 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } start2 = SeekMultiSegment(readOnlySequenceSegment.Next, object2, index2, start - num, <364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); int index3 = GetIndex(in start2); object object3 = start2.GetObject(); if (object3 != object2) { end = GetEndPosition((ReadOnlySequenceSegment)object3, object3, index3, object2, index2, length); } else { if (index2 - index3 < length) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowStartOrEndArgumentValidationException(0L); } end = new SequencePosition(object3, index3 + (int)length); } } } else { if (index2 - index < start) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowStartOrEndArgumentValidationException(-1L); } index += (int)start; start2 = new SequencePosition(@object, index); if (index2 - index < length) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowStartOrEndArgumentValidationException(0L); } end = new SequencePosition(@object, index + (int)length); } return SliceImpl(in start2, in end); } public ReadOnlySequence Slice(long start, SequencePosition end) { if (start < 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowStartOrEndArgumentValidationException(start); } uint index = (uint)GetIndex(in end); object @object = end.GetObject(); uint index2 = (uint)GetIndex(in _sequenceStart); object object2 = _sequenceStart.GetObject(); uint index3 = (uint)GetIndex(in _sequenceEnd); object object3 = _sequenceEnd.GetObject(); if (object2 == object3) { if (!InRange(index, index2, index3)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } if (index - index2 < start) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowStartOrEndArgumentValidationException(-1L); } } else { ReadOnlySequenceSegment readOnlySequenceSegment = (ReadOnlySequenceSegment)object2; ulong num = (ulong)(readOnlySequenceSegment.RunningIndex + index2); ulong num2 = (ulong)(((ReadOnlySequenceSegment)@object).RunningIndex + index); if (!InRange(num2, num, (ulong)(((ReadOnlySequenceSegment)object3).RunningIndex + index3))) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } if ((ulong)((long)num + start) > num2) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); } int num3 = readOnlySequenceSegment.Memory.Length - (int)index2; if (num3 <= start) { if (num3 < 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } SequencePosition start2 = SeekMultiSegment(readOnlySequenceSegment.Next, @object, (int)index, start - num3, <364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); return SliceImpl(in start2, in end); } } SequencePosition start3 = new SequencePosition(object2, (int)index2 + (int)start); return SliceImpl(in start3, in end); } public ReadOnlySequence Slice(SequencePosition start, long length) { uint index = (uint)GetIndex(in start); object @object = start.GetObject(); uint index2 = (uint)GetIndex(in _sequenceStart); object object2 = _sequenceStart.GetObject(); uint index3 = (uint)GetIndex(in _sequenceEnd); object object3 = _sequenceEnd.GetObject(); if (object2 == object3) { if (!InRange(index, index2, index3)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } if (length < 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowStartOrEndArgumentValidationException(0L); } if (index3 - index < length) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowStartOrEndArgumentValidationException(0L); } } else { ReadOnlySequenceSegment readOnlySequenceSegment = (ReadOnlySequenceSegment)@object; ulong num = (ulong)(readOnlySequenceSegment.RunningIndex + index); ulong start2 = (ulong)(((ReadOnlySequenceSegment)object2).RunningIndex + index2); ulong num2 = (ulong)(((ReadOnlySequenceSegment)object3).RunningIndex + index3); if (!InRange(num, start2, num2)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } if (length < 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowStartOrEndArgumentValidationException(0L); } if ((ulong)((long)num + length) > num2) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.length); } int num3 = readOnlySequenceSegment.Memory.Length - (int)index; if (num3 < length) { if (num3 < 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } SequencePosition end = SeekMultiSegment(readOnlySequenceSegment.Next, object3, (int)index3, length - num3, <364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.length); return SliceImpl(in start, in end); } } SequencePosition end2 = new SequencePosition(@object, (int)index + (int)length); return SliceImpl(in start, in end2); } public ReadOnlySequence Slice(int start, int length) { return Slice((long)start, (long)length); } public ReadOnlySequence Slice(int start, SequencePosition end) { return Slice((long)start, end); } public ReadOnlySequence Slice(SequencePosition start, int length) { return Slice(start, (long)length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySequence Slice(SequencePosition start, SequencePosition end) { BoundsCheck((uint)GetIndex(in start), start.GetObject(), (uint)GetIndex(in end), end.GetObject()); return SliceImpl(in start, in end); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySequence Slice(SequencePosition start) { BoundsCheck(in start); return SliceImpl(in start, in _sequenceEnd); } public ReadOnlySequence Slice(long start) { if (start < 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowStartOrEndArgumentValidationException(start); } if (start == 0L) { return this; } SequencePosition start2 = Seek(in _sequenceStart, in _sequenceEnd, start, <364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.start); return SliceImpl(in start2, in _sequenceEnd); } public override string ToString() { if (typeof(T) == typeof(char)) { ReadOnlySequence source = this; ReadOnlySequence sequence = Unsafe.As, ReadOnlySequence>(ref source); if (SequenceMarshal.TryGetString(sequence, out var text, out var start, out var length)) { return text.Substring(start, length); } if (Length < int.MaxValue) { return new string(BuffersExtensions.ToArray(in sequence)); } } return $"System.Buffers.ReadOnlySequence<{typeof(T).Name}>[{Length}]"; } public Enumerator GetEnumerator() { return new Enumerator(in this); } public SequencePosition GetPosition(long offset) { return GetPosition(offset, _sequenceStart); } public SequencePosition GetPosition(long offset, SequencePosition origin) { if (offset < 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException_OffsetOutOfRange(); } return Seek(in origin, in _sequenceEnd, offset, <364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.offset); } public bool TryGet(ref SequencePosition position, out ReadOnlyMemory memory, bool advance = true) { SequencePosition next; bool result = TryGetBuffer(in position, out memory, out next); if (advance) { position = next; } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool TryGetBuffer(in SequencePosition position, out ReadOnlyMemory memory, out SequencePosition next) { object @object = position.GetObject(); next = default(SequencePosition); if (@object == null) { memory = default(ReadOnlyMemory); return false; } SequenceType sequenceType = GetSequenceType(); object object2 = _sequenceEnd.GetObject(); int index = GetIndex(in position); int index2 = GetIndex(in _sequenceEnd); if (sequenceType == SequenceType.MultiSegment) { ReadOnlySequenceSegment readOnlySequenceSegment = (ReadOnlySequenceSegment)@object; if (readOnlySequenceSegment != object2) { ReadOnlySequenceSegment next2 = readOnlySequenceSegment.Next; if (next2 == null) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); } next = new SequencePosition(next2, 0); memory = readOnlySequenceSegment.Memory.Slice(index); } else { memory = readOnlySequenceSegment.Memory.Slice(index, index2 - index); } } else { if (@object != object2) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); } if (sequenceType == SequenceType.Array) { memory = new ReadOnlyMemory((T[])@object, index, index2 - index); } else if (typeof(T) == typeof(char) && sequenceType == SequenceType.String) { memory = (ReadOnlyMemory)(object)MemoryExtensions.AsMemory((string)@object, index, index2 - index); } else { memory = ((MemoryManager)@object).Memory.Slice(index, index2 - index); } } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ReadOnlyMemory GetFirstBuffer() { object @object = _sequenceStart.GetObject(); if (@object == null) { return default(ReadOnlyMemory); } int integer = _sequenceStart.GetInteger(); int integer2 = _sequenceEnd.GetInteger(); bool flag = @object != _sequenceEnd.GetObject(); if (integer >= 0) { if (integer2 >= 0) { ReadOnlyMemory memory = ((ReadOnlySequenceSegment)@object).Memory; if (flag) { return memory.Slice(integer); } return memory.Slice(integer, integer2 - integer); } if (flag) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); } return new ReadOnlyMemory((T[])@object, integer, (integer2 & 0x7FFFFFFF) - integer); } if (flag) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); } if (typeof(T) == typeof(char) && integer2 < 0) { return (ReadOnlyMemory)(object)MemoryExtensions.AsMemory((string)@object, integer & 0x7FFFFFFF, integer2 - integer); } integer &= 0x7FFFFFFF; return ((MemoryManager)@object).Memory.Slice(integer, integer2 - integer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private SequencePosition Seek(in SequencePosition start, in SequencePosition end, long offset, <364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument argument) { int index = GetIndex(in start); int index2 = GetIndex(in end); object @object = start.GetObject(); object object2 = end.GetObject(); if (@object != object2) { ReadOnlySequenceSegment readOnlySequenceSegment = (ReadOnlySequenceSegment)@object; int num = readOnlySequenceSegment.Memory.Length - index; if (num <= offset) { if (num < 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } return SeekMultiSegment(readOnlySequenceSegment.Next, object2, index2, offset - num, argument); } } else if (index2 - index < offset) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(argument); } return new SequencePosition(@object, index + (int)offset); } [MethodImpl(MethodImplOptions.NoInlining)] private static SequencePosition SeekMultiSegment(ReadOnlySequenceSegment currentSegment, object endObject, int endIndex, long offset, <364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument argument) { while (true) { if (currentSegment != null && currentSegment != endObject) { int length = currentSegment.Memory.Length; if (length > offset) { break; } offset -= length; currentSegment = currentSegment.Next; continue; } if (currentSegment == null || endIndex < offset) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(argument); } break; } return new SequencePosition(currentSegment, (int)offset); } private void BoundsCheck(in SequencePosition position) { uint index = (uint)GetIndex(in position); uint index2 = (uint)GetIndex(in _sequenceStart); uint index3 = (uint)GetIndex(in _sequenceEnd); object @object = _sequenceStart.GetObject(); object object2 = _sequenceEnd.GetObject(); if (@object == object2) { if (!InRange(index, index2, index3)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } return; } ulong start = (ulong)(((ReadOnlySequenceSegment)@object).RunningIndex + index2); if (!InRange((ulong)(((ReadOnlySequenceSegment)position.GetObject()).RunningIndex + index), start, (ulong)(((ReadOnlySequenceSegment)object2).RunningIndex + index3))) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } } private void BoundsCheck(uint sliceStartIndex, object sliceStartObject, uint sliceEndIndex, object sliceEndObject) { uint index = (uint)GetIndex(in _sequenceStart); uint index2 = (uint)GetIndex(in _sequenceEnd); object @object = _sequenceStart.GetObject(); object object2 = _sequenceEnd.GetObject(); if (@object == object2) { if (sliceStartObject != sliceEndObject || sliceStartObject != @object || sliceStartIndex > sliceEndIndex || sliceStartIndex < index || sliceEndIndex > index2) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } return; } ulong num = (ulong)(((ReadOnlySequenceSegment)sliceStartObject).RunningIndex + sliceStartIndex); ulong num2 = (ulong)(((ReadOnlySequenceSegment)sliceEndObject).RunningIndex + sliceEndIndex); if (num > num2) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } if (num < (ulong)(((ReadOnlySequenceSegment)@object).RunningIndex + index) || num2 > (ulong)(((ReadOnlySequenceSegment)object2).RunningIndex + index2)) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } } private static SequencePosition GetEndPosition(ReadOnlySequenceSegment startSegment, object startObject, int startIndex, object endObject, int endIndex, long length) { int num = startSegment.Memory.Length - startIndex; if (num > length) { return new SequencePosition(startObject, startIndex + (int)length); } if (num < 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } return SeekMultiSegment(startSegment.Next, endObject, endIndex, length - num, <364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private SequenceType GetSequenceType() { return (SequenceType)(-(2 * (_sequenceStart.GetInteger() >> 31) + (_sequenceEnd.GetInteger() >> 31))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int GetIndex(in SequencePosition position) { return position.GetInteger() & 0x7FFFFFFF; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ReadOnlySequence SliceImpl(in SequencePosition start, in SequencePosition end) { return new ReadOnlySequence(start.GetObject(), GetIndex(in start) | (_sequenceStart.GetInteger() & int.MinValue), end.GetObject(), GetIndex(in end) | (_sequenceEnd.GetInteger() & int.MinValue)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private long GetLength() { int index = GetIndex(in _sequenceStart); int index2 = GetIndex(in _sequenceEnd); object @object = _sequenceStart.GetObject(); object object2 = _sequenceEnd.GetObject(); if (@object != object2) { ReadOnlySequenceSegment readOnlySequenceSegment = (ReadOnlySequenceSegment)@object; ReadOnlySequenceSegment readOnlySequenceSegment2 = (ReadOnlySequenceSegment)object2; return readOnlySequenceSegment2.RunningIndex + index2 - (readOnlySequenceSegment.RunningIndex + index); } return index2 - index; } internal bool TryGetReadOnlySequenceSegment(out ReadOnlySequenceSegment startSegment, out int startIndex, out ReadOnlySequenceSegment endSegment, out int endIndex) { object @object = _sequenceStart.GetObject(); if (@object == null || GetSequenceType() != 0) { startSegment = null; startIndex = 0; endSegment = null; endIndex = 0; return false; } startSegment = (ReadOnlySequenceSegment)@object; startIndex = GetIndex(in _sequenceStart); endSegment = (ReadOnlySequenceSegment)_sequenceEnd.GetObject(); endIndex = GetIndex(in _sequenceEnd); return true; } internal bool TryGetArray(out ArraySegment segment) { if (GetSequenceType() != SequenceType.Array) { segment = default(ArraySegment); return false; } int index = GetIndex(in _sequenceStart); segment = new ArraySegment((T[])_sequenceStart.GetObject(), index, GetIndex(in _sequenceEnd) - index); return true; } internal bool TryGetString(out string text, out int start, out int length) { if (typeof(T) != typeof(char) || GetSequenceType() != SequenceType.String) { start = 0; length = 0; text = null; return false; } start = GetIndex(in _sequenceStart); length = GetIndex(in _sequenceEnd) - start; text = (string)_sequenceStart.GetObject(); return true; } private static bool InRange(uint value, uint start, uint end) { return value - start <= end - start; } private static bool InRange(ulong value, ulong start, ulong end) { return value - start <= end - start; } } internal static class ReadOnlySequence { public const int FlagBitMask = int.MinValue; public const int IndexBitMask = int.MaxValue; public const int SegmentStartMask = 0; public const int SegmentEndMask = 0; public const int ArrayStartMask = 0; public const int ArrayEndMask = int.MinValue; public const int MemoryManagerStartMask = int.MinValue; public const int MemoryManagerEndMask = 0; public const int StringStartMask = int.MinValue; public const int StringEndMask = int.MinValue; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int SegmentToSequenceStart(int startIndex) { return startIndex | 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int SegmentToSequenceEnd(int endIndex) { return endIndex | 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int ArrayToSequenceStart(int startIndex) { return startIndex | 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int ArrayToSequenceEnd(int endIndex) { return endIndex | int.MinValue; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int MemoryManagerToSequenceStart(int startIndex) { return startIndex | int.MinValue; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int MemoryManagerToSequenceEnd(int endIndex) { return endIndex | 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int StringToSequenceStart(int startIndex) { return startIndex | int.MinValue; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int StringToSequenceEnd(int endIndex) { return endIndex | int.MinValue; } } internal sealed class ReadOnlySequenceDebugView { [DebuggerDisplay("Count: {Segments.Length}", Name = "Segments")] public struct ReadOnlySequenceDebugViewSegments { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public ReadOnlyMemory[] Segments { get; set; } } private readonly T[] _array; private readonly ReadOnlySequenceDebugViewSegments _segments; public ReadOnlySequenceDebugViewSegments BufferSegments => _segments; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => _array; public ReadOnlySequenceDebugView(ReadOnlySequence sequence) { _array = BuffersExtensions.ToArray(in sequence); int num = 0; ReadOnlySequence.Enumerator enumerator = sequence.GetEnumerator(); while (enumerator.MoveNext()) { ReadOnlyMemory current = enumerator.Current; num++; } ReadOnlyMemory[] array = new ReadOnlyMemory[num]; int num2 = 0; ReadOnlySequence.Enumerator enumerator2 = sequence.GetEnumerator(); while (enumerator2.MoveNext()) { ReadOnlyMemory current2 = enumerator2.Current; array[num2] = current2; num2++; } _segments = new ReadOnlySequenceDebugViewSegments { Segments = array }; } } internal abstract class ReadOnlySequenceSegment { public ReadOnlyMemory Memory { get; protected set; } public ReadOnlySequenceSegment Next { get; protected set; } public long RunningIndex { get; protected set; } } internal readonly struct StandardFormat : IEquatable { public const byte NoPrecision = byte.MaxValue; public const byte MaxPrecision = 99; private readonly byte _format; private readonly byte _precision; public char Symbol => (char)_format; public byte Precision => _precision; public bool HasPrecision => _precision != byte.MaxValue; public bool IsDefault { get { if (_format == 0) { return _precision == 0; } return false; } } public StandardFormat(char symbol, byte precision = byte.MaxValue) { if (precision != byte.MaxValue && precision > 99) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException_PrecisionTooLarge(); } if (symbol != (byte)symbol) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException_SymbolDoesNotFit(); } _format = (byte)symbol; _precision = precision; } public static implicit operator StandardFormat(char symbol) { return new StandardFormat(symbol); } public static StandardFormat Parse(ReadOnlySpan format) { if (format.Length == 0) { return default(StandardFormat); } char symbol = format[0]; byte precision; if (format.Length == 1) { precision = byte.MaxValue; } else { uint num = 0u; for (int i = 1; i < format.Length; i++) { uint num2 = (uint)(format[i] - 48); if (num2 > 9) { throw new FormatException(<364de6aa-3638-4f0c-b478-eff7d6f86309>SR.Format(<364de6aa-3638-4f0c-b478-eff7d6f86309>SR.Argument_CannotParsePrecision, (byte)99)); } num = num * 10 + num2; if (num > 99) { throw new FormatException(<364de6aa-3638-4f0c-b478-eff7d6f86309>SR.Format(<364de6aa-3638-4f0c-b478-eff7d6f86309>SR.Argument_PrecisionTooLarge, (byte)99)); } } precision = (byte)num; } return new StandardFormat(symbol, precision); } public static StandardFormat Parse(string format) { if (format != null) { return Parse(MemoryExtensions.AsSpan(format)); } return default(StandardFormat); } public override bool Equals(object obj) { if (obj is StandardFormat other) { return Equals(other); } return false; } public override int GetHashCode() { byte format = _format; int hashCode = format.GetHashCode(); format = _precision; return hashCode ^ format.GetHashCode(); } public bool Equals(StandardFormat other) { if (_format == other._format) { return _precision == other._precision; } return false; } public unsafe override string ToString() { char* ptr = stackalloc char[4]; int length = 0; char symbol = Symbol; if (symbol != 0) { ptr[length++] = symbol; byte b = Precision; if (b != byte.MaxValue) { if (b >= 100) { ptr[length++] = (char)(48 + b / 100 % 10); b %= 100; } if (b >= 10) { ptr[length++] = (char)(48 + b / 10 % 10); b %= 10; } ptr[length++] = (char)(48 + b); } } return new string(ptr, 0, length); } public static bool operator ==(StandardFormat left, StandardFormat right) { return left.Equals(right); } public static bool operator !=(StandardFormat left, StandardFormat right) { return !left.Equals(right); } } internal interface IPinnable { MemoryHandle Pin(int elementIndex); void Unpin(); } internal interface IMemoryOwner : IDisposable { Memory Memory { get; } } internal struct MemoryHandle : IDisposable { private unsafe void* _pointer; private GCHandle _handle; private IPinnable _pinnable; [CLSCompliant(false)] public unsafe void* Pointer => _pointer; [CLSCompliant(false)] public unsafe MemoryHandle(void* pointer, GCHandle handle = default(GCHandle), IPinnable pinnable = null) { _pointer = pointer; _handle = handle; _pinnable = pinnable; } public unsafe void Dispose() { if (_handle.IsAllocated) { _handle.Free(); } if (_pinnable != null) { _pinnable.Unpin(); _pinnable = null; } _pointer = null; } } internal abstract class MemoryManager : IMemoryOwner, IDisposable, IPinnable { public virtual Memory Memory => new Memory(this, GetSpan().Length); public abstract Span GetSpan(); public abstract MemoryHandle Pin(int elementIndex = 0); public abstract void Unpin(); [MethodImpl(MethodImplOptions.AggressiveInlining)] protected Memory CreateMemory(int length) { return new Memory(this, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected Memory CreateMemory(int start, int length) { return new Memory(this, start, length); } protected internal virtual bool TryGetArray(out ArraySegment segment) { segment = default(ArraySegment); return false; } void IDisposable.Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected abstract void Dispose(bool disposing); } } namespace System.Buffers.Text { internal static class Base64 { private static readonly sbyte[] s_decodingMap = new sbyte[256] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; private static readonly byte[] s_encodingMap = new byte[64] { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47 }; private const byte EncodingPad = 61; private const int MaximumEncodeLength = 1610612733; public static OperationStatus DecodeFromUtf8(ReadOnlySpan utf8, Span bytes, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { ref byte reference = ref MemoryMarshal.GetReference(utf8); ref byte reference2 = ref MemoryMarshal.GetReference(bytes); int num = utf8.Length & -4; int length = bytes.Length; int num2 = 0; int num3 = 0; if (utf8.Length != 0) { ref sbyte reference3 = ref s_decodingMap[0]; int num4 = (isFinalBlock ? 4 : 0); int num5 = 0; num5 = ((length < GetMaxDecodedFromUtf8Length(num)) ? (length / 3 * 4) : (num - num4)); while (true) { if (num2 < num5) { int num6 = Decode(ref Unsafe.Add(ref reference, num2), ref reference3); if (num6 >= 0) { WriteThreeLowOrderBytes(ref Unsafe.Add(ref reference2, num3), num6); num3 += 3; num2 += 4; continue; } } else { if (num5 != num - num4) { goto IL_0205; } if (num2 == num) { if (!isFinalBlock) { bytesConsumed = num2; bytesWritten = num3; return OperationStatus.NeedMoreData; } } else { int elementOffset = Unsafe.Add(ref reference, num - 4); int elementOffset2 = Unsafe.Add(ref reference, num - 3); int num7 = Unsafe.Add(ref reference, num - 2); int num8 = Unsafe.Add(ref reference, num - 1); elementOffset = Unsafe.Add(ref reference3, elementOffset); elementOffset2 = Unsafe.Add(ref reference3, elementOffset2); elementOffset <<= 18; elementOffset2 <<= 12; elementOffset |= elementOffset2; if (num8 != 61) { num7 = Unsafe.Add(ref reference3, num7); num8 = Unsafe.Add(ref reference3, num8); num7 <<= 6; elementOffset |= num8; elementOffset |= num7; if (elementOffset >= 0) { if (num3 <= length - 3) { WriteThreeLowOrderBytes(ref Unsafe.Add(ref reference2, num3), elementOffset); num3 += 3; goto IL_01eb; } goto IL_0205; } } else if (num7 != 61) { num7 = Unsafe.Add(ref reference3, num7); num7 <<= 6; elementOffset |= num7; if (elementOffset >= 0) { if (num3 <= length - 2) { Unsafe.Add(ref reference2, num3) = (byte)(elementOffset >> 16); Unsafe.Add(ref reference2, num3 + 1) = (byte)(elementOffset >> 8); num3 += 2; goto IL_01eb; } goto IL_0205; } } else if (elementOffset >= 0) { if (num3 <= length - 1) { Unsafe.Add(ref reference2, num3) = (byte)(elementOffset >> 16); num3++; goto IL_01eb; } goto IL_0205; } } } goto IL_022b; IL_01eb: num2 += 4; if (num == utf8.Length) { break; } goto IL_022b; IL_022b: bytesConsumed = num2; bytesWritten = num3; return OperationStatus.InvalidData; IL_0205: if (!(num != utf8.Length && isFinalBlock)) { bytesConsumed = num2; bytesWritten = num3; return OperationStatus.DestinationTooSmall; } goto IL_022b; } } bytesConsumed = num2; bytesWritten = num3; return OperationStatus.Done; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetMaxDecodedFromUtf8Length(int length) { if (length < 0) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.length); } return (length >> 2) * 3; } public static OperationStatus DecodeFromUtf8InPlace(Span buffer, out int bytesWritten) { int length = buffer.Length; int num = 0; int num2 = 0; if (length == (length >> 2) * 4) { if (length == 0) { goto IL_016d; } ref byte reference = ref MemoryMarshal.GetReference(buffer); ref sbyte reference2 = ref s_decodingMap[0]; while (num < length - 4) { int num3 = Decode(ref Unsafe.Add(ref reference, num), ref reference2); if (num3 >= 0) { WriteThreeLowOrderBytes(ref Unsafe.Add(ref reference, num2), num3); num2 += 3; num += 4; continue; } goto IL_0172; } int elementOffset = Unsafe.Add(ref reference, length - 4); int elementOffset2 = Unsafe.Add(ref reference, length - 3); int num4 = Unsafe.Add(ref reference, length - 2); int num5 = Unsafe.Add(ref reference, length - 1); elementOffset = Unsafe.Add(ref reference2, elementOffset); elementOffset2 = Unsafe.Add(ref reference2, elementOffset2); elementOffset <<= 18; elementOffset2 <<= 12; elementOffset |= elementOffset2; if (num5 != 61) { num4 = Unsafe.Add(ref reference2, num4); num5 = Unsafe.Add(ref reference2, num5); num4 <<= 6; elementOffset |= num5; elementOffset |= num4; if (elementOffset >= 0) { WriteThreeLowOrderBytes(ref Unsafe.Add(ref reference, num2), elementOffset); num2 += 3; goto IL_016d; } } else if (num4 != 61) { num4 = Unsafe.Add(ref reference2, num4); num4 <<= 6; elementOffset |= num4; if (elementOffset >= 0) { Unsafe.Add(ref reference, num2) = (byte)(elementOffset >> 16); Unsafe.Add(ref reference, num2 + 1) = (byte)(elementOffset >> 8); num2 += 2; goto IL_016d; } } else if (elementOffset >= 0) { Unsafe.Add(ref reference, num2) = (byte)(elementOffset >> 16); num2++; goto IL_016d; } } goto IL_0172; IL_016d: bytesWritten = num2; return OperationStatus.Done; IL_0172: bytesWritten = num2; return OperationStatus.InvalidData; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int Decode(ref byte encodedBytes, ref sbyte decodingMap) { int elementOffset = encodedBytes; int elementOffset2 = Unsafe.Add(ref encodedBytes, 1); int elementOffset3 = Unsafe.Add(ref encodedBytes, 2); int elementOffset4 = Unsafe.Add(ref encodedBytes, 3); elementOffset = Unsafe.Add(ref decodingMap, elementOffset); elementOffset2 = Unsafe.Add(ref decodingMap, elementOffset2); elementOffset3 = Unsafe.Add(ref decodingMap, elementOffset3); elementOffset4 = Unsafe.Add(ref decodingMap, elementOffset4); elementOffset <<= 18; elementOffset2 <<= 12; elementOffset3 <<= 6; elementOffset |= elementOffset4; elementOffset2 |= elementOffset3; return elementOffset | elementOffset2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteThreeLowOrderBytes(ref byte destination, int value) { destination = (byte)(value >> 16); Unsafe.Add(ref destination, 1) = (byte)(value >> 8); Unsafe.Add(ref destination, 2) = (byte)value; } public static OperationStatus EncodeToUtf8(ReadOnlySpan bytes, Span utf8, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { ref byte reference = ref MemoryMarshal.GetReference(bytes); ref byte reference2 = ref MemoryMarshal.GetReference(utf8); int length = bytes.Length; int length2 = utf8.Length; int num = 0; num = ((length > 1610612733 || length2 < GetMaxEncodedToUtf8Length(length)) ? ((length2 >> 2) * 3 - 2) : (length - 2)); int i = 0; int num2 = 0; int num3 = 0; ref byte encodingMap = ref s_encodingMap[0]; for (; i < num; i += 3) { num3 = Encode(ref Unsafe.Add(ref reference, i), ref encodingMap); Unsafe.WriteUnaligned(ref Unsafe.Add(ref reference2, num2), num3); num2 += 4; } if (num == length - 2) { if (isFinalBlock) { if (i == length - 1) { num3 = EncodeAndPadTwo(ref Unsafe.Add(ref reference, i), ref encodingMap); Unsafe.WriteUnaligned(ref Unsafe.Add(ref reference2, num2), num3); num2 += 4; i++; } else if (i == length - 2) { num3 = EncodeAndPadOne(ref Unsafe.Add(ref reference, i), ref encodingMap); Unsafe.WriteUnaligned(ref Unsafe.Add(ref reference2, num2), num3); num2 += 4; i += 2; } bytesConsumed = i; bytesWritten = num2; return OperationStatus.Done; } bytesConsumed = i; bytesWritten = num2; return OperationStatus.NeedMoreData; } bytesConsumed = i; bytesWritten = num2; return OperationStatus.DestinationTooSmall; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetMaxEncodedToUtf8Length(int length) { if ((uint)length > 1610612733u) { <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.ThrowArgumentOutOfRangeException(<364de6aa-3638-4f0c-b478-eff7d6f86309>ExceptionArgument.length); } return (length + 2) / 3 * 4; } public static OperationStatus EncodeToUtf8InPlace(Span buffer, int dataLength, out int bytesWritten) { int maxEncodedToUtf8Length = GetMaxEncodedToUtf8Length(dataLength); if (buffer.Length >= maxEncodedToUtf8Length) { int num = dataLength - dataLength / 3 * 3; int num2 = maxEncodedToUtf8Length - 4; int num3 = dataLength - num; int num4 = 0; ref byte encodingMap = ref s_encodingMap[0]; ref byte reference = ref MemoryMarshal.GetReference(buffer); switch (num) { case 1: num4 = EncodeAndPadTwo(ref Unsafe.Add(ref reference, num3), ref encodingMap); Unsafe.WriteUnaligned(ref Unsafe.Add(ref reference, num2), num4); num2 -= 4; break; default: num4 = EncodeAndPadOne(ref Unsafe.Add(ref reference, num3), ref encodingMap); Unsafe.WriteUnaligned(ref Unsafe.Add(ref reference, num2), num4); num2 -= 4; break; case 0: break; } for (num3 -= 3; num3 >= 0; num3 -= 3) { num4 = Encode(ref Unsafe.Add(ref reference, num3), ref encodingMap); Unsafe.WriteUnaligned(ref Unsafe.Add(ref reference, num2), num4); num2 -= 4; } bytesWritten = maxEncodedToUtf8Length; return OperationStatus.Done; } bytesWritten = 0; return OperationStatus.DestinationTooSmall; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int Encode(ref byte threeBytes, ref byte encodingMap) { int num = (threeBytes << 16) | (Unsafe.Add(ref threeBytes, 1) << 8) | Unsafe.Add(ref threeBytes, 2); int num2 = Unsafe.Add(ref encodingMap, num >> 18); int num3 = Unsafe.Add(ref encodingMap, (num >> 12) & 0x3F); int num4 = Unsafe.Add(ref encodingMap, (num >> 6) & 0x3F); int num5 = Unsafe.Add(ref encodingMap, num & 0x3F); return num2 | (num3 << 8) | (num4 << 16) | (num5 << 24); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int EncodeAndPadOne(ref byte twoBytes, ref byte encodingMap) { int num = (twoBytes << 16) | (Unsafe.Add(ref twoBytes, 1) << 8); int num2 = Unsafe.Add(ref encodingMap, num >> 18); int num3 = Unsafe.Add(ref encodingMap, (num >> 12) & 0x3F); int num4 = Unsafe.Add(ref encodingMap, (num >> 6) & 0x3F); return num2 | (num3 << 8) | (num4 << 16) | 0x3D000000; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int EncodeAndPadTwo(ref byte oneByte, ref byte encodingMap) { int num = oneByte << 8; int num2 = Unsafe.Add(ref encodingMap, num >> 10); int num3 = Unsafe.Add(ref encodingMap, (num >> 4) & 0x3F); return num2 | (num3 << 8) | 0x3D0000 | 0x3D000000; } } internal static class Utf8Constants { public const byte Colon = 58; public const byte Comma = 44; public const byte Minus = 45; public const byte Period = 46; public const byte Plus = 43; public const byte Slash = 47; public const byte Space = 32; public const byte Hyphen = 45; public const byte Separator = 44; public const int GroupSize = 3; public static readonly TimeSpan s_nullUtcOffset = TimeSpan.MinValue; public const int DateTimeMaxUtcOffsetHours = 14; public const int DateTimeNumFractionDigits = 7; public const int MaxDateTimeFraction = 9999999; public const ulong BillionMaxUIntValue = 4294967295000000000uL; public const uint Billion = 1000000000u; } internal static class FormattingHelpers { public enum HexCasing : uint { Uppercase = 0u, Lowercase = 8224u } internal const string HexTableLower = "0123456789abcdef"; internal const string HexTableUpper = "0123456789ABCDEF"; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char GetSymbolOrDefault(in StandardFormat format, char defaultSymbol) { char c = format.Symbol; if (c == '\0' && format.Precision == 0) { c = defaultSymbol; } return c; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void FillWithAsciiZeros(Span buffer) { for (int i = 0; i < buffer.Length; i++) { buffer[i] = 48; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteHexByte(byte value, Span buffer, int startingIndex = 0, HexCasing casing = HexCasing.Uppercase) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (byte)num2; buffer[startingIndex] = (byte)(num2 >> 8); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteDigits(ulong value, Span buffer) { for (int num = buffer.Length - 1; num >= 1; num--) { ulong num2 = 48 + value; value /= 10; buffer[num] = (byte)(num2 - value * 10); } buffer[0] = (byte)(48 + value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteDigitsWithGroupSeparator(ulong value, Span buffer) { int num = 0; for (int num2 = buffer.Length - 1; num2 >= 1; num2--) { ulong num3 = 48 + value; value /= 10; buffer[num2] = (byte)(num3 - value * 10); if (num == 2) { buffer[--num2] = 44; num = 0; } else { num++; } } buffer[0] = (byte)(48 + value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteDigits(uint value, Span buffer) { for (int num = buffer.Length - 1; num >= 1; num--) { uint num2 = 48 + value; value /= 10; buffer[num] = (byte)(num2 - value * 10); } buffer[0] = (byte)(48 + value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteFourDecimalDigits(uint value, Span buffer, int startingIndex = 0) { uint num = 48 + value; value /= 10; buffer[startingIndex + 3] = (byte)(num - value * 10); num = 48 + value; value /= 10; buffer[startingIndex + 2] = (byte)(num - value * 10); num = 48 + value; value /= 10; buffer[startingIndex + 1] = (byte)(num - value * 10); buffer[startingIndex] = (byte)(48 + value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteTwoDecimalDigits(uint value, Span buffer, int startingIndex = 0) { uint num = 48 + value; value /= 10; buffer[startingIndex + 1] = (byte)(num - value * 10); buffer[startingIndex] = (byte)(48 + value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong DivMod(ulong numerator, ulong denominator, out ulong modulo) { ulong num = numerator / denominator; modulo = numerator - num * denominator; return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint DivMod(uint numerator, uint denominator, out uint modulo) { uint num = numerator / denominator; modulo = numerator - num * denominator; return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int CountDecimalTrailingZeros(uint value, out uint valueWithoutTrailingZeros) { int num = 0; if (value != 0) { while (true) { uint modulo; uint num2 = DivMod(value, 10u, out modulo); if (modulo != 0) { break; } value = num2; num++; } } valueWithoutTrailingZeros = value; return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int CountDigits(ulong value) { int num = 1; uint num2; if (value >= 10000000) { if (value >= 100000000000000L) { num2 = (uint)(value / 100000000000000L); num += 14; } else { num2 = (uint)(value / 10000000); num += 7; } } else { num2 = (uint)value; } if (num2 >= 10) { num = ((num2 < 100) ? (num + 1) : ((num2 < 1000) ? (num + 2) : ((num2 < 10000) ? (num + 3) : ((num2 < 100000) ? (num + 4) : ((num2 >= 1000000) ? (num + 6) : (num + 5)))))); } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int CountDigits(uint value) { int num = 1; if (value >= 100000) { value /= 100000; num += 5; } if (value >= 10) { num = ((value < 100) ? (num + 1) : ((value < 1000) ? (num + 2) : ((value >= 10000) ? (num + 4) : (num + 3)))); } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int CountHexDigits(ulong value) { int num = 1; if (value > uint.MaxValue) { num += 8; value >>= 32; } if (value > 65535) { num += 4; value >>= 16; } if (value > 255) { num += 2; value >>= 8; } if (value > 15) { num++; } return num; } } internal static class Utf8Formatter { [StructLayout(LayoutKind.Explicit)] private struct DecomposedGuid { [FieldOffset(0)] public Guid Guid; [FieldOffset(0)] public byte Byte00; [FieldOffset(1)] public byte Byte01; [FieldOffset(2)] public byte Byte02; [FieldOffset(3)] public byte Byte03; [FieldOffset(4)] public byte Byte04; [FieldOffset(5)] public byte Byte05; [FieldOffset(6)] public byte Byte06; [FieldOffset(7)] public byte Byte07; [FieldOffset(8)] public byte Byte08; [FieldOffset(9)] public byte Byte09; [FieldOffset(10)] public byte Byte10; [FieldOffset(11)] public byte Byte11; [FieldOffset(12)] public byte Byte12; [FieldOffset(13)] public byte Byte13; [FieldOffset(14)] public byte Byte14; [FieldOffset(15)] public byte Byte15; } private const byte TimeMarker = 84; private const byte UtcMarker = 90; private const byte GMT1 = 71; private const byte GMT2 = 77; private const byte GMT3 = 84; private const byte GMT1Lowercase = 103; private const byte GMT2Lowercase = 109; private const byte GMT3Lowercase = 116; private static readonly uint[] DayAbbreviations = new uint[7] { 7238995u, 7237453u, 6649172u, 6579543u, 7694420u, 6910534u, 7627091u }; private static readonly uint[] DayAbbreviationsLowercase = new uint[7] { 7239027u, 7237485u, 6649204u, 6579575u, 7694452u, 6910566u, 7627123u }; private static readonly uint[] MonthAbbreviations = new uint[12] { 7233866u, 6448454u, 7496013u, 7499841u, 7954765u, 7238986u, 7107914u, 6780225u, 7365971u, 7627599u, 7761742u, 6513988u }; private static readonly uint[] MonthAbbreviationsLowercase = new uint[12] { 7233898u, 6448486u, 7496045u, 7499873u, 7954797u, 7239018u, 7107946u, 6780257u, 7366003u, 7627631u, 7761774u, 6514020u }; private const byte OpenBrace = 123; private const byte CloseBrace = 125; private const byte OpenParen = 40; private const byte CloseParen = 41; private const byte Dash = 45; public static bool TryFormat(bool value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { char symbolOrDefault = System.Buffers.Text.FormattingHelpers.GetSymbolOrDefault(in format, 'G'); if (value) { if (symbolOrDefault == 'G') { if (BinaryPrimitives.TryWriteUInt32BigEndian(destination, 1416787301u)) { goto IL_0033; } } else { if (symbolOrDefault != 'l') { goto IL_0083; } if (BinaryPrimitives.TryWriteUInt32BigEndian(destination, 1953658213u)) { goto IL_0033; } } } else if (symbolOrDefault == 'G') { if (4u < (uint)destination.Length) { BinaryPrimitives.WriteUInt32BigEndian(destination, 1180789875u); goto IL_006e; } } else { if (symbolOrDefault != 'l') { goto IL_0083; } if (4u < (uint)destination.Length) { BinaryPrimitives.WriteUInt32BigEndian(destination, 1717660787u); goto IL_006e; } } bytesWritten = 0; return false; IL_0033: bytesWritten = 4; return true; IL_0083: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryFormatThrowFormatException(out bytesWritten); IL_006e: destination[4] = 101; bytesWritten = 5; return true; } public static bool TryFormat(DateTimeOffset value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { TimeSpan offset = System.Buffers.Text.Utf8Constants.s_nullUtcOffset; char c = format.Symbol; if (format.IsDefault) { c = 'G'; offset = value.Offset; } return c switch { 'R' => TryFormatDateTimeR(value.UtcDateTime, destination, out bytesWritten), 'l' => TryFormatDateTimeL(value.UtcDateTime, destination, out bytesWritten), 'O' => TryFormatDateTimeO(value.DateTime, value.Offset, destination, out bytesWritten), 'G' => TryFormatDateTimeG(value.DateTime, offset, destination, out bytesWritten), _ => <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryFormatThrowFormatException(out bytesWritten), }; } public static bool TryFormat(DateTime value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return System.Buffers.Text.FormattingHelpers.GetSymbolOrDefault(in format, 'G') switch { 'R' => TryFormatDateTimeR(value, destination, out bytesWritten), 'l' => TryFormatDateTimeL(value, destination, out bytesWritten), 'O' => TryFormatDateTimeO(value, System.Buffers.Text.Utf8Constants.s_nullUtcOffset, destination, out bytesWritten), 'G' => TryFormatDateTimeG(value, System.Buffers.Text.Utf8Constants.s_nullUtcOffset, destination, out bytesWritten), _ => <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryFormatThrowFormatException(out bytesWritten), }; } private static bool TryFormatDateTimeG(DateTime value, TimeSpan offset, Span destination, out int bytesWritten) { int num = 19; if (offset != System.Buffers.Text.Utf8Constants.s_nullUtcOffset) { num += 7; } if (destination.Length < num) { bytesWritten = 0; return false; } bytesWritten = num; byte b = destination[18]; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Month, destination); destination[2] = 47; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Day, destination, 3); destination[5] = 47; System.Buffers.Text.FormattingHelpers.WriteFourDecimalDigits((uint)value.Year, destination, 6); destination[10] = 32; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Hour, destination, 11); destination[13] = 58; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Minute, destination, 14); destination[16] = 58; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Second, destination, 17); if (offset != System.Buffers.Text.Utf8Constants.s_nullUtcOffset) { byte b2; if (offset < default(TimeSpan)) { b2 = 45; offset = TimeSpan.FromTicks(-offset.Ticks); } else { b2 = 43; } System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)offset.Minutes, destination, 24); destination[23] = 58; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)offset.Hours, destination, 21); destination[20] = b2; destination[19] = 32; } return true; } private static bool TryFormatDateTimeO(DateTime value, TimeSpan offset, Span destination, out int bytesWritten) { int num = 27; DateTimeKind dateTimeKind = DateTimeKind.Local; if (offset == System.Buffers.Text.Utf8Constants.s_nullUtcOffset) { dateTimeKind = value.Kind; switch (dateTimeKind) { case DateTimeKind.Local: offset = TimeZoneInfo.Local.GetUtcOffset(value); num += 6; break; case DateTimeKind.Utc: num++; break; } } else { num += 6; } if (destination.Length < num) { bytesWritten = 0; return false; } bytesWritten = num; byte b = destination[26]; System.Buffers.Text.FormattingHelpers.WriteFourDecimalDigits((uint)value.Year, destination); destination[4] = 45; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Month, destination, 5); destination[7] = 45; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Day, destination, 8); destination[10] = 84; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Hour, destination, 11); destination[13] = 58; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Minute, destination, 14); destination[16] = 58; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Second, destination, 17); destination[19] = 46; System.Buffers.Text.FormattingHelpers.WriteDigits((uint)((ulong)value.Ticks % 10000000uL), destination.Slice(20, 7)); switch (dateTimeKind) { case DateTimeKind.Local: { byte b2; if (offset < default(TimeSpan)) { b2 = 45; offset = TimeSpan.FromTicks(-offset.Ticks); } else { b2 = 43; } System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)offset.Minutes, destination, 31); destination[30] = 58; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)offset.Hours, destination, 28); destination[27] = b2; break; } case DateTimeKind.Utc: destination[27] = 90; break; } return true; } private static bool TryFormatDateTimeR(DateTime value, Span destination, out int bytesWritten) { if (28u >= (uint)destination.Length) { bytesWritten = 0; return false; } uint num = DayAbbreviations[(int)value.DayOfWeek]; destination[0] = (byte)num; num >>= 8; destination[1] = (byte)num; num >>= 8; destination[2] = (byte)num; destination[3] = 44; destination[4] = 32; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Day, destination, 5); destination[7] = 32; uint num2 = MonthAbbreviations[value.Month - 1]; destination[8] = (byte)num2; num2 >>= 8; destination[9] = (byte)num2; num2 >>= 8; destination[10] = (byte)num2; destination[11] = 32; System.Buffers.Text.FormattingHelpers.WriteFourDecimalDigits((uint)value.Year, destination, 12); destination[16] = 32; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Hour, destination, 17); destination[19] = 58; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Minute, destination, 20); destination[22] = 58; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Second, destination, 23); destination[25] = 32; destination[26] = 71; destination[27] = 77; destination[28] = 84; bytesWritten = 29; return true; } private static bool TryFormatDateTimeL(DateTime value, Span destination, out int bytesWritten) { if (28u >= (uint)destination.Length) { bytesWritten = 0; return false; } uint num = DayAbbreviationsLowercase[(int)value.DayOfWeek]; destination[0] = (byte)num; num >>= 8; destination[1] = (byte)num; num >>= 8; destination[2] = (byte)num; destination[3] = 44; destination[4] = 32; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Day, destination, 5); destination[7] = 32; uint num2 = MonthAbbreviationsLowercase[value.Month - 1]; destination[8] = (byte)num2; num2 >>= 8; destination[9] = (byte)num2; num2 >>= 8; destination[10] = (byte)num2; destination[11] = 32; System.Buffers.Text.FormattingHelpers.WriteFourDecimalDigits((uint)value.Year, destination, 12); destination[16] = 32; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Hour, destination, 17); destination[19] = 58; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Minute, destination, 20); destination[22] = 58; System.Buffers.Text.FormattingHelpers.WriteTwoDecimalDigits((uint)value.Second, destination, 23); destination[25] = 32; destination[26] = 103; destination[27] = 109; destination[28] = 116; bytesWritten = 29; return true; } public static bool TryFormat(decimal value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { if (format.IsDefault) { format = 'G'; } switch (format.Symbol) { case 'G': case 'g': { if (format.Precision != byte.MaxValue) { throw new NotSupportedException(<364de6aa-3638-4f0c-b478-eff7d6f86309>SR.Argument_GWithPrecisionNotSupported); } NumberBuffer number3 = default(NumberBuffer); System.Number.DecimalToNumber(value, ref number3); if (number3.Digits[0] == 0) { number3.IsNegative = false; } return TryFormatDecimalG(ref number3, destination, out bytesWritten); } case 'F': case 'f': { NumberBuffer number2 = default(NumberBuffer); System.Number.DecimalToNumber(value, ref number2); byte b2 = (byte)((format.Precision == byte.MaxValue) ? 2 : format.Precision); System.Number.RoundNumber(ref number2, number2.Scale + b2); return TryFormatDecimalF(ref number2, destination, out bytesWritten, b2); } case 'E': case 'e': { NumberBuffer number = default(NumberBuffer); System.Number.DecimalToNumber(value, ref number); byte b = (byte)((format.Precision == byte.MaxValue) ? 6 : format.Precision); System.Number.RoundNumber(ref number, b + 1); return TryFormatDecimalE(ref number, destination, out bytesWritten, b, (byte)format.Symbol); } default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryFormatThrowFormatException(out bytesWritten); } } private static bool TryFormatDecimalE(ref NumberBuffer number, Span destination, out int bytesWritten, byte precision, byte exponentSymbol) { int scale = number.Scale; ReadOnlySpan readOnlySpan = number.Digits; int num = (number.IsNegative ? 1 : 0) + 1 + ((precision != 0) ? (precision + 1) : 0) + 2 + 3; if (destination.Length < num) { bytesWritten = 0; return false; } int num2 = 0; int num3 = 0; if (number.IsNegative) { destination[num2++] = 45; } byte b = readOnlySpan[num3]; int num4; if (b == 0) { destination[num2++] = 48; num4 = 0; } else { destination[num2++] = b; num3++; num4 = scale - 1; } if (precision > 0) { destination[num2++] = 46; for (int i = 0; i < precision; i++) { byte b2 = readOnlySpan[num3]; if (b2 == 0) { while (i++ < precision) { destination[num2++] = 48; } break; } destination[num2++] = b2; num3++; } } destination[num2++] = exponentSymbol; if (num4 >= 0) { destination[num2++] = 43; } else { destination[num2++] = 45; num4 = -num4; } destination[num2++] = 48; destination[num2++] = (byte)(num4 / 10 + 48); destination[num2++] = (byte)(num4 % 10 + 48); bytesWritten = num; return true; } private static bool TryFormatDecimalF(ref NumberBuffer number, Span destination, out int bytesWritten, byte precision) { int scale = number.Scale; ReadOnlySpan readOnlySpan = number.Digits; int num = (number.IsNegative ? 1 : 0) + ((scale <= 0) ? 1 : scale) + ((precision != 0) ? (precision + 1) : 0); if (destination.Length < num) { bytesWritten = 0; return false; } int i = 0; int num2 = 0; if (number.IsNegative) { destination[num2++] = 45; } if (scale <= 0) { destination[num2++] = 48; } else { for (; i < scale; i++) { byte b = readOnlySpan[i]; if (b == 0) { int num3 = scale - i; for (int j = 0; j < num3; j++) { destination[num2++] = 48; } break; } destination[num2++] = b; } } if (precision > 0) { destination[num2++] = 46; int k = 0; if (scale < 0) { int num4 = Math.Min(precision, -scale); for (int l = 0; l < num4; l++) { destination[num2++] = 48; } k += num4; } for (; k < precision; k++) { byte b2 = readOnlySpan[i]; if (b2 == 0) { while (k++ < precision) { destination[num2++] = 48; } break; } destination[num2++] = b2; i++; } } bytesWritten = num; return true; } private static bool TryFormatDecimalG(ref NumberBuffer number, Span destination, out int bytesWritten) { int scale = number.Scale; ReadOnlySpan readOnlySpan = number.Digits; int numDigits = number.NumDigits; bool flag = scale < numDigits; int num; if (flag) { num = numDigits + 1; if (scale <= 0) { num += 1 + -scale; } } else { num = ((scale <= 0) ? 1 : scale); } if (number.IsNegative) { num++; } if (destination.Length < num) { bytesWritten = 0; return false; } int i = 0; int num2 = 0; if (number.IsNegative) { destination[num2++] = 45; } if (scale <= 0) { destination[num2++] = 48; } else { for (; i < scale; i++) { byte b = readOnlySpan[i]; if (b == 0) { int num3 = scale - i; for (int j = 0; j < num3; j++) { destination[num2++] = 48; } break; } destination[num2++] = b; } } if (flag) { destination[num2++] = 46; if (scale < 0) { int num4 = -scale; for (int k = 0; k < num4; k++) { destination[num2++] = 48; } } byte b2; while ((b2 = readOnlySpan[i++]) != 0) { destination[num2++] = b2; } } bytesWritten = num; return true; } public static bool TryFormat(double value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatFloatingPoint(value, destination, out bytesWritten, format); } public static bool TryFormat(float value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatFloatingPoint(value, destination, out bytesWritten, format); } private static bool TryFormatFloatingPoint(T value, Span destination, out int bytesWritten, StandardFormat format) where T : IFormattable { if (format.IsDefault) { format = 'G'; } switch (format.Symbol) { case 'G': case 'g': if (format.Precision != byte.MaxValue) { throw new NotSupportedException(<364de6aa-3638-4f0c-b478-eff7d6f86309>SR.Argument_GWithPrecisionNotSupported); } break; default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryFormatThrowFormatException(out bytesWritten); case 'E': case 'F': case 'e': case 'f': break; } string text = format.ToString(); string text2 = value.ToString(text, CultureInfo.InvariantCulture); int length = text2.Length; if (length > destination.Length) { bytesWritten = 0; return false; } for (int i = 0; i < length; i++) { destination[i] = (byte)text2[i]; } bytesWritten = length; return true; } public static bool TryFormat(Guid value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { int num; switch (System.Buffers.Text.FormattingHelpers.GetSymbolOrDefault(in format, 'D')) { case 'D': num = -2147483612; break; case 'B': num = -2139260122; break; case 'P': num = -2144786394; break; case 'N': num = 32; break; default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryFormatThrowFormatException(out bytesWritten); } if ((byte)num > destination.Length) { bytesWritten = 0; return false; } bytesWritten = (byte)num; num >>= 8; if ((byte)num != 0) { destination[0] = (byte)num; destination = destination.Slice(1); } num >>= 8; DecomposedGuid decomposedGuid = default(DecomposedGuid); decomposedGuid.Guid = value; byte b = destination[8]; System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte03, destination, 0, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte02, destination, 2, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte01, destination, 4, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte00, destination, 6, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); if (num < 0) { destination[8] = 45; destination = destination.Slice(9); } else { destination = destination.Slice(8); } byte b2 = destination[4]; System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte05, destination, 0, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte04, destination, 2, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); if (num < 0) { destination[4] = 45; destination = destination.Slice(5); } else { destination = destination.Slice(4); } byte b3 = destination[4]; System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte07, destination, 0, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte06, destination, 2, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); if (num < 0) { destination[4] = 45; destination = destination.Slice(5); } else { destination = destination.Slice(4); } byte b4 = destination[4]; System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte08, destination, 0, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte09, destination, 2, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); if (num < 0) { destination[4] = 45; destination = destination.Slice(5); } else { destination = destination.Slice(4); } byte b5 = destination[11]; System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte10, destination, 0, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte11, destination, 2, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte12, destination, 4, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte13, destination, 6, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte14, destination, 8, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); System.Buffers.Text.FormattingHelpers.WriteHexByte(decomposedGuid.Byte15, destination, 10, System.Buffers.Text.FormattingHelpers.HexCasing.Lowercase); if ((byte)num != 0) { destination[12] = (byte)num; } return true; } public static bool TryFormat(byte value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatUInt64(value, destination, out bytesWritten, format); } [CLSCompliant(false)] public static bool TryFormat(sbyte value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatInt64(value, 255uL, destination, out bytesWritten, format); } [CLSCompliant(false)] public static bool TryFormat(ushort value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatUInt64(value, destination, out bytesWritten, format); } public static bool TryFormat(short value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatInt64(value, 65535uL, destination, out bytesWritten, format); } [CLSCompliant(false)] public static bool TryFormat(uint value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatUInt64(value, destination, out bytesWritten, format); } public static bool TryFormat(int value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatInt64(value, 4294967295uL, destination, out bytesWritten, format); } [CLSCompliant(false)] public static bool TryFormat(ulong value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatUInt64(value, destination, out bytesWritten, format); } public static bool TryFormat(long value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatInt64(value, ulong.MaxValue, destination, out bytesWritten, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatInt64(long value, ulong mask, Span destination, out int bytesWritten, StandardFormat format) { if (format.IsDefault) { return TryFormatInt64Default(value, destination, out bytesWritten); } switch (format.Symbol) { case 'G': case 'g': if (format.HasPrecision) { throw new NotSupportedException(<364de6aa-3638-4f0c-b478-eff7d6f86309>SR.Argument_GWithPrecisionNotSupported); } return TryFormatInt64D(value, format.Precision, destination, out bytesWritten); case 'D': case 'd': return TryFormatInt64D(value, format.Precision, destination, out bytesWritten); case 'N': case 'n': return TryFormatInt64N(value, format.Precision, destination, out bytesWritten); case 'x': return TryFormatUInt64X((ulong)value & mask, format.Precision, useLower: true, destination, out bytesWritten); case 'X': return TryFormatUInt64X((ulong)value & mask, format.Precision, useLower: false, destination, out bytesWritten); default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryFormatThrowFormatException(out bytesWritten); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatInt64D(long value, byte precision, Span destination, out int bytesWritten) { bool insertNegationSign = false; if (value < 0) { insertNegationSign = true; value = -value; } return TryFormatUInt64D((ulong)value, precision, destination, insertNegationSign, out bytesWritten); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatInt64Default(long value, Span destination, out int bytesWritten) { if ((ulong)value < 10uL) { return TryFormatUInt32SingleDigit((uint)value, destination, out bytesWritten); } if (IntPtr.Size == 8) { return TryFormatInt64MultipleDigits(value, destination, out bytesWritten); } if (value <= int.MaxValue && value >= int.MinValue) { return TryFormatInt32MultipleDigits((int)value, destination, out bytesWritten); } if (value <= 4294967295000000000L && value >= -4294967295000000000L) { if (value >= 0) { return TryFormatUInt64LessThanBillionMaxUInt((ulong)value, destination, out bytesWritten); } return TryFormatInt64MoreThanNegativeBillionMaxUInt(-value, destination, out bytesWritten); } if (value >= 0) { return TryFormatUInt64MoreThanBillionMaxUInt((ulong)value, destination, out bytesWritten); } return TryFormatInt64LessThanNegativeBillionMaxUInt(-value, destination, out bytesWritten); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatInt32Default(int value, Span destination, out int bytesWritten) { if ((uint)value < 10u) { return TryFormatUInt32SingleDigit((uint)value, destination, out bytesWritten); } return TryFormatInt32MultipleDigits(value, destination, out bytesWritten); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatInt32MultipleDigits(int value, Span destination, out int bytesWritten) { if (value < 0) { value = -value; int num = System.Buffers.Text.FormattingHelpers.CountDigits((uint)value); if (num >= destination.Length) { bytesWritten = 0; return false; } destination[0] = 45; bytesWritten = num + 1; System.Buffers.Text.FormattingHelpers.WriteDigits((uint)value, destination.Slice(1, num)); return true; } return TryFormatUInt32MultipleDigits((uint)value, destination, out bytesWritten); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatInt64MultipleDigits(long value, Span destination, out int bytesWritten) { if (value < 0) { value = -value; int num = System.Buffers.Text.FormattingHelpers.CountDigits((ulong)value); if (num >= destination.Length) { bytesWritten = 0; return false; } destination[0] = 45; bytesWritten = num + 1; System.Buffers.Text.FormattingHelpers.WriteDigits((ulong)value, destination.Slice(1, num)); return true; } return TryFormatUInt64MultipleDigits((ulong)value, destination, out bytesWritten); } private static bool TryFormatInt64MoreThanNegativeBillionMaxUInt(long value, Span destination, out int bytesWritten) { uint num = (uint)(value / 1000000000); uint value2 = (uint)(value - num * 1000000000); int num2 = System.Buffers.Text.FormattingHelpers.CountDigits(num); int num3 = num2 + 9; if (num3 >= destination.Length) { bytesWritten = 0; return false; } destination[0] = 45; bytesWritten = num3 + 1; System.Buffers.Text.FormattingHelpers.WriteDigits(num, destination.Slice(1, num2)); System.Buffers.Text.FormattingHelpers.WriteDigits(value2, destination.Slice(num2 + 1, 9)); return true; } private static bool TryFormatInt64LessThanNegativeBillionMaxUInt(long value, Span destination, out int bytesWritten) { ulong num = (ulong)value / 1000000000uL; uint value2 = (uint)((ulong)value - num * 1000000000); uint num2 = (uint)(num / 1000000000); uint value3 = (uint)(num - num2 * 1000000000); int num3 = System.Buffers.Text.FormattingHelpers.CountDigits(num2); int num4 = num3 + 18; if (num4 >= destination.Length) { bytesWritten = 0; return false; } destination[0] = 45; bytesWritten = num4 + 1; System.Buffers.Text.FormattingHelpers.WriteDigits(num2, destination.Slice(1, num3)); System.Buffers.Text.FormattingHelpers.WriteDigits(value3, destination.Slice(num3 + 1, 9)); System.Buffers.Text.FormattingHelpers.WriteDigits(value2, destination.Slice(num3 + 1 + 9, 9)); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatInt64N(long value, byte precision, Span destination, out int bytesWritten) { bool insertNegationSign = false; if (value < 0) { insertNegationSign = true; value = -value; } return TryFormatUInt64N((ulong)value, precision, destination, insertNegationSign, out bytesWritten); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatUInt64(ulong value, Span destination, out int bytesWritten, StandardFormat format) { if (format.IsDefault) { return TryFormatUInt64Default(value, destination, out bytesWritten); } switch (format.Symbol) { case 'G': case 'g': if (format.HasPrecision) { throw new NotSupportedException(<364de6aa-3638-4f0c-b478-eff7d6f86309>SR.Argument_GWithPrecisionNotSupported); } return TryFormatUInt64D(value, format.Precision, destination, insertNegationSign: false, out bytesWritten); case 'D': case 'd': return TryFormatUInt64D(value, format.Precision, destination, insertNegationSign: false, out bytesWritten); case 'N': case 'n': return TryFormatUInt64N(value, format.Precision, destination, insertNegationSign: false, out bytesWritten); case 'x': return TryFormatUInt64X(value, format.Precision, useLower: true, destination, out bytesWritten); case 'X': return TryFormatUInt64X(value, format.Precision, useLower: false, destination, out bytesWritten); default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryFormatThrowFormatException(out bytesWritten); } } private static bool TryFormatUInt64D(ulong value, byte precision, Span destination, bool insertNegationSign, out int bytesWritten) { int num = System.Buffers.Text.FormattingHelpers.CountDigits(value); int num2 = ((precision != byte.MaxValue) ? precision : 0) - num; if (num2 < 0) { num2 = 0; } int num3 = num + num2; if (insertNegationSign) { num3++; } if (num3 > destination.Length) { bytesWritten = 0; return false; } bytesWritten = num3; if (insertNegationSign) { destination[0] = 45; destination = destination.Slice(1); } if (num2 > 0) { System.Buffers.Text.FormattingHelpers.FillWithAsciiZeros(destination.Slice(0, num2)); } System.Buffers.Text.FormattingHelpers.WriteDigits(value, destination.Slice(num2, num)); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatUInt64Default(ulong value, Span destination, out int bytesWritten) { if (value < 10) { return TryFormatUInt32SingleDigit((uint)value, destination, out bytesWritten); } if (IntPtr.Size == 8) { return TryFormatUInt64MultipleDigits(value, destination, out bytesWritten); } if (value <= uint.MaxValue) { return TryFormatUInt32MultipleDigits((uint)value, destination, out bytesWritten); } if (value <= 4294967295000000000L) { return TryFormatUInt64LessThanBillionMaxUInt(value, destination, out bytesWritten); } return TryFormatUInt64MoreThanBillionMaxUInt(value, destination, out bytesWritten); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatUInt32Default(uint value, Span destination, out int bytesWritten) { if (value < 10) { return TryFormatUInt32SingleDigit(value, destination, out bytesWritten); } return TryFormatUInt32MultipleDigits(value, destination, out bytesWritten); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatUInt32SingleDigit(uint value, Span destination, out int bytesWritten) { if (destination.Length == 0) { bytesWritten = 0; return false; } destination[0] = (byte)(48 + value); bytesWritten = 1; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatUInt32MultipleDigits(uint value, Span destination, out int bytesWritten) { int num = System.Buffers.Text.FormattingHelpers.CountDigits(value); if (num > destination.Length) { bytesWritten = 0; return false; } bytesWritten = num; System.Buffers.Text.FormattingHelpers.WriteDigits(value, destination.Slice(0, num)); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatUInt64SingleDigit(ulong value, Span destination, out int bytesWritten) { if (destination.Length == 0) { bytesWritten = 0; return false; } destination[0] = (byte)(48 + value); bytesWritten = 1; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatUInt64MultipleDigits(ulong value, Span destination, out int bytesWritten) { int num = System.Buffers.Text.FormattingHelpers.CountDigits(value); if (num > destination.Length) { bytesWritten = 0; return false; } bytesWritten = num; System.Buffers.Text.FormattingHelpers.WriteDigits(value, destination.Slice(0, num)); return true; } private static bool TryFormatUInt64LessThanBillionMaxUInt(ulong value, Span destination, out int bytesWritten) { uint num = (uint)(value / 1000000000); uint value2 = (uint)(value - num * 1000000000); int num2 = System.Buffers.Text.FormattingHelpers.CountDigits(num); int num3 = num2 + 9; if (num3 > destination.Length) { bytesWritten = 0; return false; } bytesWritten = num3; System.Buffers.Text.FormattingHelpers.WriteDigits(num, destination.Slice(0, num2)); System.Buffers.Text.FormattingHelpers.WriteDigits(value2, destination.Slice(num2, 9)); return true; } private static bool TryFormatUInt64MoreThanBillionMaxUInt(ulong value, Span destination, out int bytesWritten) { ulong num = value / 1000000000; uint value2 = (uint)(value - num * 1000000000); uint num2 = (uint)(num / 1000000000); uint value3 = (uint)(num - num2 * 1000000000); int num3 = System.Buffers.Text.FormattingHelpers.CountDigits(num2); int num4 = num3 + 18; if (num4 > destination.Length) { bytesWritten = 0; return false; } bytesWritten = num4; System.Buffers.Text.FormattingHelpers.WriteDigits(num2, destination.Slice(0, num3)); System.Buffers.Text.FormattingHelpers.WriteDigits(value3, destination.Slice(num3, 9)); System.Buffers.Text.FormattingHelpers.WriteDigits(value2, destination.Slice(num3 + 9, 9)); return true; } private static bool TryFormatUInt64N(ulong value, byte precision, Span destination, bool insertNegationSign, out int bytesWritten) { int num = System.Buffers.Text.FormattingHelpers.CountDigits(value); int num2 = (num - 1) / 3; int num3 = ((precision == byte.MaxValue) ? 2 : precision); int num4 = num + num2; if (num3 > 0) { num4 += num3 + 1; } if (insertNegationSign) { num4++; } if (num4 > destination.Length) { bytesWritten = 0; return false; } bytesWritten = num4; if (insertNegationSign) { destination[0] = 45; destination = destination.Slice(1); } System.Buffers.Text.FormattingHelpers.WriteDigitsWithGroupSeparator(value, destination.Slice(0, num + num2)); if (num3 > 0) { destination[num + num2] = 46; System.Buffers.Text.FormattingHelpers.FillWithAsciiZeros(destination.Slice(num + num2 + 1, num3)); } return true; } private static bool TryFormatUInt64X(ulong value, byte precision, bool useLower, Span destination, out int bytesWritten) { int num = System.Buffers.Text.FormattingHelpers.CountHexDigits(value); int num2 = ((precision == byte.MaxValue) ? num : Math.Max(precision, num)); if (destination.Length < num2) { bytesWritten = 0; return false; } bytesWritten = num2; string text = (useLower ? "0123456789abcdef" : "0123456789ABCDEF"); while ((uint)(--num2) < (uint)destination.Length) { destination[num2] = (byte)text[(int)value & 0xF]; value >>= 4; } return true; } public static bool TryFormat(TimeSpan value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { char c = System.Buffers.Text.FormattingHelpers.GetSymbolOrDefault(in format, 'c'); switch (c) { case 'T': case 't': c = 'c'; break; default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryFormatThrowFormatException(out bytesWritten); case 'G': case 'c': case 'g': break; } int num = 8; long ticks = value.Ticks; uint valueWithoutTrailingZeros; ulong num2; if (ticks < 0) { ticks = -ticks; if (ticks < 0) { valueWithoutTrailingZeros = 4775808u; num2 = 922337203685uL; goto IL_0082; } } num2 = System.Buffers.Text.FormattingHelpers.DivMod((ulong)Math.Abs(value.Ticks), 10000000uL, out var modulo); valueWithoutTrailingZeros = (uint)modulo; goto IL_0082; IL_0082: int num3 = 0; switch (c) { case 'c': if (valueWithoutTrailingZeros != 0) { num3 = 7; } break; case 'G': num3 = 7; break; default: if (valueWithoutTrailingZeros != 0) { num3 = 7 - System.Buffers.Text.FormattingHelpers.CountDecimalTrailingZeros(valueWithoutTrailingZeros, out valueWithoutTrailingZeros); } break; } if (num3 != 0) { num += num3 + 1; } ulong num4 = 0uL; ulong modulo2 = 0uL; if (num2 != 0) { num4 = System.Buffers.Text.FormattingHelpers.DivMod(num2, 60uL, out modulo2); } ulong num5 = 0uL; ulong modulo3 = 0uL; if (num4 != 0) { num5 = System.Buffers.Text.FormattingHelpers.DivMod(num4, 60uL, out modulo3); } uint num6 = 0u; uint modulo4 = 0u; if (num5 != 0) { num6 = System.Buffers.Text.FormattingHelpers.DivMod((uint)num5, 24u, out modulo4); } int num7 = 2; if (modulo4 < 10 && c == 'g') { num7--; num--; } int num8 = 0; if (num6 == 0) { if (c == 'G') { num += 2; num8 = 1; } } else { num8 = System.Buffers.Text.FormattingHelpers.CountDigits(num6); num += num8 + 1; } if (value.Ticks < 0) { num++; } if (destination.Length < num) { bytesWritten = 0; return false; } bytesWritten = num; int num9 = 0; if (value.Ticks < 0) { destination[num9++] = 45; } if (num8 > 0) { System.Buffers.Text.FormattingHelpers.WriteDigits(num6, destination.Slice(num9, num8)); num9 += num8; destination[num9++] = (byte)((c == 'c') ? 46 : 58); } System.Buffers.Text.FormattingHelpers.WriteDigits(modulo4, destination.Slice(num9, num7)); num9 += num7; destination[num9++] = 58; System.Buffers.Text.FormattingHelpers.WriteDigits((uint)modulo3, destination.Slice(num9, 2)); num9 += 2; destination[num9++] = 58; System.Buffers.Text.FormattingHelpers.WriteDigits((uint)modulo2, destination.Slice(num9, 2)); num9 += 2; if (num3 > 0) { destination[num9++] = 46; System.Buffers.Text.FormattingHelpers.WriteDigits(valueWithoutTrailingZeros, destination.Slice(num9, num3)); num9 += num3; } return true; } } internal static class ParserHelpers { public const int ByteOverflowLength = 3; public const int ByteOverflowLengthHex = 2; public const int UInt16OverflowLength = 5; public const int UInt16OverflowLengthHex = 4; public const int UInt32OverflowLength = 10; public const int UInt32OverflowLengthHex = 8; public const int UInt64OverflowLength = 20; public const int UInt64OverflowLengthHex = 16; public const int SByteOverflowLength = 3; public const int SByteOverflowLengthHex = 2; public const int Int16OverflowLength = 5; public const int Int16OverflowLengthHex = 4; public const int Int32OverflowLength = 10; public const int Int32OverflowLengthHex = 8; public const int Int64OverflowLength = 19; public const int Int64OverflowLengthHex = 16; public static readonly byte[] s_hexLookup = new byte[256] { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsDigit(int i) { return (uint)(i - 48) <= 9u; } } internal static class Utf8Parser { [Flags] private enum ParseNumberOptions { AllowExponent = 1 } private enum ComponentParseResult : byte { NoMoreData, Colon, Period, ParseFailure } private struct TimeSpanSplitter { public uint V1; public uint V2; public uint V3; public uint V4; public uint V5; public bool IsNegative; public uint Separators; public bool TrySplitTimeSpan(ReadOnlySpan source, bool periodUsedToSeparateDay, out int bytesConsumed) { int i = 0; byte b = 0; for (; i != source.Length; i++) { b = source[i]; if (b != 32 && b != 9) { break; } } if (i == source.Length) { bytesConsumed = 0; return false; } if (b == 45) { IsNegative = true; i++; if (i == source.Length) { bytesConsumed = 0; return false; } } if (!TryParseUInt32D(source.Slice(i), out V1, out var bytesConsumed2)) { bytesConsumed = 0; return false; } i += bytesConsumed2; ComponentParseResult componentParseResult = ParseComponent(source, periodUsedToSeparateDay, ref i, out V2); switch (componentParseResult) { case ComponentParseResult.ParseFailure: bytesConsumed = 0; return false; case ComponentParseResult.NoMoreData: bytesConsumed = i; return true; default: Separators |= (uint)componentParseResult << 24; componentParseResult = ParseComponent(source, neverParseAsFraction: false, ref i, out V3); switch (componentParseResult) { case ComponentParseResult.ParseFailure: bytesConsumed = 0; return false; case ComponentParseResult.NoMoreData: bytesConsumed = i; return true; default: Separators |= (uint)componentParseResult << 16; componentParseResult = ParseComponent(source, neverParseAsFraction: false, ref i, out V4); switch (componentParseResult) { case ComponentParseResult.ParseFailure: bytesConsumed = 0; return false; case ComponentParseResult.NoMoreData: bytesConsumed = i; return true; default: Separators |= (uint)componentParseResult << 8; componentParseResult = ParseComponent(source, neverParseAsFraction: false, ref i, out V5); switch (componentParseResult) { case ComponentParseResult.ParseFailure: bytesConsumed = 0; return false; case ComponentParseResult.NoMoreData: bytesConsumed = i; return true; default: Separators |= (uint)componentParseResult; if (i != source.Length && (source[i] == 46 || source[i] == 58)) { bytesConsumed = 0; return false; } bytesConsumed = i; return true; } } } } } private static ComponentParseResult ParseComponent(ReadOnlySpan source, bool neverParseAsFraction, ref int srcIndex, out uint value) { if (srcIndex == source.Length) { value = 0u; return ComponentParseResult.NoMoreData; } byte b = source[srcIndex]; if (b == 58 || (b == 46 && neverParseAsFraction)) { srcIndex++; if (!TryParseUInt32D(source.Slice(srcIndex), out value, out var bytesConsumed)) { value = 0u; return ComponentParseResult.ParseFailure; } srcIndex += bytesConsumed; if (b != 58) { return ComponentParseResult.Period; } return ComponentParseResult.Colon; } if (b == 46) { srcIndex++; if (!TryParseTimeSpanFraction(source.Slice(srcIndex), out value, out var bytesConsumed2)) { value = 0u; return ComponentParseResult.ParseFailure; } srcIndex += bytesConsumed2; return ComponentParseResult.Period; } value = 0u; return ComponentParseResult.NoMoreData; } } private const uint FlipCase = 32u; private const uint NoFlipCase = 0u; private static readonly int[] s_daysToMonth365 = new int[13] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; private static readonly int[] s_daysToMonth366 = new int[13] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; public static bool TryParse(ReadOnlySpan source, out bool value, out int bytesConsumed, char standardFormat = '\0') { if (standardFormat != 0 && standardFormat != 'G' && standardFormat != 'l') { return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); } if (source.Length >= 4) { if ((source[0] == 84 || source[0] == 116) && (source[1] == 82 || source[1] == 114) && (source[2] == 85 || source[2] == 117) && (source[3] == 69 || source[3] == 101)) { bytesConsumed = 4; value = true; return true; } if (source.Length >= 5 && (source[0] == 70 || source[0] == 102) && (source[1] == 65 || source[1] == 97) && (source[2] == 76 || source[2] == 108) && (source[3] == 83 || source[3] == 115) && (source[4] == 69 || source[4] == 101)) { bytesConsumed = 5; value = false; return true; } } bytesConsumed = 0; value = false; return false; } public static bool TryParse(ReadOnlySpan source, out DateTime value, out int bytesConsumed, char standardFormat = '\0') { switch (standardFormat) { case 'R': { if (!TryParseDateTimeOffsetR(source, 0u, out var dateTimeOffset, out bytesConsumed)) { value = default(DateTime); return false; } value = dateTimeOffset.DateTime; return true; } case 'l': { if (!TryParseDateTimeOffsetR(source, 32u, out var dateTimeOffset2, out bytesConsumed)) { value = default(DateTime); return false; } value = dateTimeOffset2.DateTime; return true; } case 'O': { if (!TryParseDateTimeOffsetO(source, out var value2, out bytesConsumed, out var kind)) { value = default(DateTime); bytesConsumed = 0; return false; } switch (kind) { case DateTimeKind.Local: value = value2.LocalDateTime; break; case DateTimeKind.Utc: value = value2.UtcDateTime; break; default: value = value2.DateTime; break; } return true; } case '\0': case 'G': { DateTimeOffset valueAsOffset; return TryParseDateTimeG(source, out value, out valueAsOffset, out bytesConsumed); } default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); } } public static bool TryParse(ReadOnlySpan source, out DateTimeOffset value, out int bytesConsumed, char standardFormat = '\0') { DateTimeKind kind; DateTime value2; return standardFormat switch { 'R' => TryParseDateTimeOffsetR(source, 0u, out value, out bytesConsumed), 'l' => TryParseDateTimeOffsetR(source, 32u, out value, out bytesConsumed), 'O' => TryParseDateTimeOffsetO(source, out value, out bytesConsumed, out kind), '\0' => TryParseDateTimeOffsetDefault(source, out value, out bytesConsumed), 'G' => TryParseDateTimeG(source, out value2, out value, out bytesConsumed), _ => <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed), }; } private static bool TryParseDateTimeOffsetDefault(ReadOnlySpan source, out DateTimeOffset value, out int bytesConsumed) { if (source.Length < 26) { bytesConsumed = 0; value = default(DateTimeOffset); return false; } if (!TryParseDateTimeG(source, out var value2, out var _, out var _)) { bytesConsumed = 0; value = default(DateTimeOffset); return false; } if (source[19] != 32) { bytesConsumed = 0; value = default(DateTimeOffset); return false; } byte b = source[20]; if (b != 43 && b != 45) { bytesConsumed = 0; value = default(DateTimeOffset); return false; } uint num = (uint)(source[21] - 48); uint num2 = (uint)(source[22] - 48); if (num > 9 || num2 > 9) { bytesConsumed = 0; value = default(DateTimeOffset); return false; } int num3 = (int)(num * 10 + num2); if (source[23] != 58) { bytesConsumed = 0; value = default(DateTimeOffset); return false; } uint num4 = (uint)(source[24] - 48); uint num5 = (uint)(source[25] - 48); if (num4 > 9 || num5 > 9) { bytesConsumed = 0; value = default(DateTimeOffset); return false; } int num6 = (int)(num4 * 10 + num5); TimeSpan timeSpan = new TimeSpan(num3, num6, 0); if (b == 45) { timeSpan = -timeSpan; } if (!TryCreateDateTimeOffset(value2, b == 45, num3, num6, out value)) { bytesConsumed = 0; value = default(DateTimeOffset); return false; } bytesConsumed = 26; return true; } private static bool TryParseDateTimeG(ReadOnlySpan source, out DateTime value, out DateTimeOffset valueAsOffset, out int bytesConsumed) { if (source.Length < 19) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } uint num = (uint)(source[0] - 48); uint num2 = (uint)(source[1] - 48); if (num > 9 || num2 > 9) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } int month = (int)(num * 10 + num2); if (source[2] != 47) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } uint num3 = (uint)(source[3] - 48); uint num4 = (uint)(source[4] - 48); if (num3 > 9 || num4 > 9) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } int day = (int)(num3 * 10 + num4); if (source[5] != 47) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } uint num5 = (uint)(source[6] - 48); uint num6 = (uint)(source[7] - 48); uint num7 = (uint)(source[8] - 48); uint num8 = (uint)(source[9] - 48); if (num5 > 9 || num6 > 9 || num7 > 9 || num8 > 9) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } int year = (int)(num5 * 1000 + num6 * 100 + num7 * 10 + num8); if (source[10] != 32) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } uint num9 = (uint)(source[11] - 48); uint num10 = (uint)(source[12] - 48); if (num9 > 9 || num10 > 9) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } int hour = (int)(num9 * 10 + num10); if (source[13] != 58) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } uint num11 = (uint)(source[14] - 48); uint num12 = (uint)(source[15] - 48); if (num11 > 9 || num12 > 9) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } int minute = (int)(num11 * 10 + num12); if (source[16] != 58) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } uint num13 = (uint)(source[17] - 48); uint num14 = (uint)(source[18] - 48); if (num13 > 9 || num14 > 9) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } int second = (int)(num13 * 10 + num14); if (!TryCreateDateTimeOffsetInterpretingDataAsLocalTime(year, month, day, hour, minute, second, 0, out valueAsOffset)) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } bytesConsumed = 19; value = valueAsOffset.DateTime; return true; } private static bool TryCreateDateTimeOffset(DateTime dateTime, bool offsetNegative, int offsetHours, int offsetMinutes, out DateTimeOffset value) { if ((uint)offsetHours > 14u) { value = default(DateTimeOffset); return false; } if ((uint)offsetMinutes > 59u) { value = default(DateTimeOffset); return false; } if (offsetHours == 14 && offsetMinutes != 0) { value = default(DateTimeOffset); return false; } long num = ((long)offsetHours * 3600L + (long)offsetMinutes * 60L) * 10000000; if (offsetNegative) { num = -num; } try { value = new DateTimeOffset(dateTime.Ticks, new TimeSpan(num)); } catch (ArgumentOutOfRangeException) { value = default(DateTimeOffset); return false; } return true; } private static bool TryCreateDateTimeOffset(int year, int month, int day, int hour, int minute, int second, int fraction, bool offsetNegative, int offsetHours, int offsetMinutes, out DateTimeOffset value) { if (!TryCreateDateTime(year, month, day, hour, minute, second, fraction, DateTimeKind.Unspecified, out var value2)) { value = default(DateTimeOffset); return false; } if (!TryCreateDateTimeOffset(value2, offsetNegative, offsetHours, offsetMinutes, out value)) { value = default(DateTimeOffset); return false; } return true; } private static bool TryCreateDateTimeOffsetInterpretingDataAsLocalTime(int year, int month, int day, int hour, int minute, int second, int fraction, out DateTimeOffset value) { if (!TryCreateDateTime(year, month, day, hour, minute, second, fraction, DateTimeKind.Local, out var value2)) { value = default(DateTimeOffset); return false; } try { value = new DateTimeOffset(value2); } catch (ArgumentOutOfRangeException) { value = default(DateTimeOffset); return false; } return true; } private static bool TryCreateDateTime(int year, int month, int day, int hour, int minute, int second, int fraction, DateTimeKind kind, out DateTime value) { if (year == 0) { value = default(DateTime); return false; } if ((uint)(month - 1) >= 12u) { value = default(DateTime); return false; } uint num = (uint)(day - 1); if (num >= 28 && num >= DateTime.DaysInMonth(year, month)) { value = default(DateTime); return false; } if ((uint)hour > 23u) { value = default(DateTime); return false; } if ((uint)minute > 59u) { value = default(DateTime); return false; } if ((uint)second > 59u) { value = default(DateTime); return false; } int[] array = (DateTime.IsLeapYear(year) ? s_daysToMonth366 : s_daysToMonth365); int num2 = year - 1; int num3 = num2 * 365 + num2 / 4 - num2 / 100 + num2 / 400 + array[month - 1] + day - 1; long num4 = num3 * 864000000000L; int num5 = hour * 3600 + minute * 60 + second; num4 += (long)num5 * 10000000L; num4 += fraction; value = new DateTime(num4, kind); return true; } private static bool TryParseDateTimeOffsetO(ReadOnlySpan source, out DateTimeOffset value, out int bytesConsumed, out DateTimeKind kind) { if (source.Length < 27) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num = (uint)(source[0] - 48); uint num2 = (uint)(source[1] - 48); uint num3 = (uint)(source[2] - 48); uint num4 = (uint)(source[3] - 48); if (num > 9 || num2 > 9 || num3 > 9 || num4 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int year = (int)(num * 1000 + num2 * 100 + num3 * 10 + num4); if (source[4] != 45) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num5 = (uint)(source[5] - 48); uint num6 = (uint)(source[6] - 48); if (num5 > 9 || num6 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int month = (int)(num5 * 10 + num6); if (source[7] != 45) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num7 = (uint)(source[8] - 48); uint num8 = (uint)(source[9] - 48); if (num7 > 9 || num8 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int day = (int)(num7 * 10 + num8); if (source[10] != 84) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num9 = (uint)(source[11] - 48); uint num10 = (uint)(source[12] - 48); if (num9 > 9 || num10 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int hour = (int)(num9 * 10 + num10); if (source[13] != 58) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num11 = (uint)(source[14] - 48); uint num12 = (uint)(source[15] - 48); if (num11 > 9 || num12 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int minute = (int)(num11 * 10 + num12); if (source[16] != 58) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num13 = (uint)(source[17] - 48); uint num14 = (uint)(source[18] - 48); if (num13 > 9 || num14 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int second = (int)(num13 * 10 + num14); if (source[19] != 46) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num15 = (uint)(source[20] - 48); uint num16 = (uint)(source[21] - 48); uint num17 = (uint)(source[22] - 48); uint num18 = (uint)(source[23] - 48); uint num19 = (uint)(source[24] - 48); uint num20 = (uint)(source[25] - 48); uint num21 = (uint)(source[26] - 48); if (num15 > 9 || num16 > 9 || num17 > 9 || num18 > 9 || num19 > 9 || num20 > 9 || num21 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int fraction = (int)(num15 * 1000000 + num16 * 100000 + num17 * 10000 + num18 * 1000 + num19 * 100 + num20 * 10 + num21); byte b = (byte)((source.Length > 27) ? source[27] : 0); if (b != 90 && b != 43 && b != 45) { if (!TryCreateDateTimeOffsetInterpretingDataAsLocalTime(year, month, day, hour, minute, second, fraction, out value)) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } bytesConsumed = 27; kind = DateTimeKind.Unspecified; return true; } if (b == 90) { if (!TryCreateDateTimeOffset(year, month, day, hour, minute, second, fraction, offsetNegative: false, 0, 0, out value)) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } bytesConsumed = 28; kind = DateTimeKind.Utc; return true; } if (source.Length < 33) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num22 = (uint)(source[28] - 48); uint num23 = (uint)(source[29] - 48); if (num22 > 9 || num23 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int offsetHours = (int)(num22 * 10 + num23); if (source[30] != 58) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num24 = (uint)(source[31] - 48); uint num25 = (uint)(source[32] - 48); if (num24 > 9 || num25 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int offsetMinutes = (int)(num24 * 10 + num25); if (!TryCreateDateTimeOffset(year, month, day, hour, minute, second, fraction, b == 45, offsetHours, offsetMinutes, out value)) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } bytesConsumed = 33; kind = DateTimeKind.Local; return true; } private static bool TryParseDateTimeOffsetR(ReadOnlySpan source, uint caseFlipXorMask, out DateTimeOffset dateTimeOffset, out int bytesConsumed) { if (source.Length < 29) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } uint num = source[0] ^ caseFlipXorMask; uint num2 = source[1]; uint num3 = source[2]; uint num4 = source[3]; DayOfWeek dayOfWeek; switch ((num << 24) | (num2 << 16) | (num3 << 8) | num4) { case 1400204844u: dayOfWeek = DayOfWeek.Sunday; break; case 1299148332u: dayOfWeek = DayOfWeek.Monday; break; case 1416979756u: dayOfWeek = DayOfWeek.Tuesday; break; case 1466262572u: dayOfWeek = DayOfWeek.Wednesday; break; case 1416131884u: dayOfWeek = DayOfWeek.Thursday; break; case 1181903148u: dayOfWeek = DayOfWeek.Friday; break; case 1398895660u: dayOfWeek = DayOfWeek.Saturday; break; default: bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } if (source[4] != 32) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } uint num5 = (uint)(source[5] - 48); uint num6 = (uint)(source[6] - 48); if (num5 > 9 || num6 > 9) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } int day = (int)(num5 * 10 + num6); if (source[7] != 32) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } uint num7 = source[8] ^ caseFlipXorMask; uint num8 = source[9]; uint num9 = source[10]; uint num10 = source[11]; int month; switch ((num7 << 24) | (num8 << 16) | (num9 << 8) | num10) { case 1247899168u: month = 1; break; case 1181049376u: month = 2; break; case 1298231840u: month = 3; break; case 1097888288u: month = 4; break; case 1298233632u: month = 5; break; case 1249209888u: month = 6; break; case 1249209376u: month = 7; break; case 1098213152u: month = 8; break; case 1399156768u: month = 9; break; case 1331917856u: month = 10; break; case 1315927584u: month = 11; break; case 1147495200u: month = 12; break; default: bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } uint num11 = (uint)(source[12] - 48); uint num12 = (uint)(source[13] - 48); uint num13 = (uint)(source[14] - 48); uint num14 = (uint)(source[15] - 48); if (num11 > 9 || num12 > 9 || num13 > 9 || num14 > 9) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } int year = (int)(num11 * 1000 + num12 * 100 + num13 * 10 + num14); if (source[16] != 32) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } uint num15 = (uint)(source[17] - 48); uint num16 = (uint)(source[18] - 48); if (num15 > 9 || num16 > 9) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } int hour = (int)(num15 * 10 + num16); if (source[19] != 58) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } uint num17 = (uint)(source[20] - 48); uint num18 = (uint)(source[21] - 48); if (num17 > 9 || num18 > 9) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } int minute = (int)(num17 * 10 + num18); if (source[22] != 58) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } uint num19 = (uint)(source[23] - 48); uint num20 = (uint)(source[24] - 48); if (num19 > 9 || num20 > 9) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } int second = (int)(num19 * 10 + num20); uint num21 = source[25]; uint num22 = source[26] ^ caseFlipXorMask; uint num23 = source[27] ^ caseFlipXorMask; uint num24 = source[28] ^ caseFlipXorMask; uint num25 = (num21 << 24) | (num22 << 16) | (num23 << 8) | num24; if (num25 != 541543764) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } if (!TryCreateDateTimeOffset(year, month, day, hour, minute, second, 0, offsetNegative: false, 0, 0, out dateTimeOffset)) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } if (dayOfWeek != dateTimeOffset.DayOfWeek) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } bytesConsumed = 29; return true; } public static bool TryParse(ReadOnlySpan source, out decimal value, out int bytesConsumed, char standardFormat = '\0') { ParseNumberOptions options; switch (standardFormat) { case '\0': case 'E': case 'G': case 'e': case 'g': options = ParseNumberOptions.AllowExponent; break; case 'F': case 'f': options = (ParseNumberOptions)0; break; default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); } NumberBuffer number = default(NumberBuffer); if (!TryParseNumber(source, ref number, out bytesConsumed, options, out var textUsedExponentNotation)) { value = default(decimal); return false; } if (!textUsedExponentNotation && (standardFormat == 'E' || standardFormat == 'e')) { value = default(decimal); bytesConsumed = 0; return false; } if (number.Digits[0] == 0 && number.Scale == 0) { number.IsNegative = false; } value = default(decimal); if (!System.Number.NumberBufferToDecimal(ref number, ref value)) { value = default(decimal); bytesConsumed = 0; return false; } return true; } public static bool TryParse(ReadOnlySpan source, out float value, out int bytesConsumed, char standardFormat = '\0') { if (TryParseNormalAsFloatingPoint(source, out var value2, out bytesConsumed, standardFormat)) { value = (float)value2; if (float.IsInfinity(value)) { value = 0f; bytesConsumed = 0; return false; } return true; } return TryParseAsSpecialFloatingPoint(source, float.PositiveInfinity, float.NegativeInfinity, float.NaN, out value, out bytesConsumed); } public static bool TryParse(ReadOnlySpan source, out double value, out int bytesConsumed, char standardFormat = '\0') { if (TryParseNormalAsFloatingPoint(source, out value, out bytesConsumed, standardFormat)) { return true; } return TryParseAsSpecialFloatingPoint(source, double.PositiveInfinity, double.NegativeInfinity, double.NaN, out value, out bytesConsumed); } private static bool TryParseNormalAsFloatingPoint(ReadOnlySpan source, out double value, out int bytesConsumed, char standardFormat) { ParseNumberOptions options; switch (standardFormat) { case '\0': case 'E': case 'G': case 'e': case 'g': options = ParseNumberOptions.AllowExponent; break; case 'F': case 'f': options = (ParseNumberOptions)0; break; default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); } NumberBuffer number = default(NumberBuffer); if (!TryParseNumber(source, ref number, out bytesConsumed, options, out var textUsedExponentNotation)) { value = 0.0; return false; } if (!textUsedExponentNotation && (standardFormat == 'E' || standardFormat == 'e')) { value = 0.0; bytesConsumed = 0; return false; } if (number.Digits[0] == 0) { number.IsNegative = false; } if (!System.Number.NumberBufferToDouble(ref number, out value)) { value = 0.0; bytesConsumed = 0; return false; } return true; } private static bool TryParseAsSpecialFloatingPoint(ReadOnlySpan source, T positiveInfinity, T negativeInfinity, T nan, out T value, out int bytesConsumed) { if (source.Length >= 8 && source[0] == 73 && source[1] == 110 && source[2] == 102 && source[3] == 105 && source[4] == 110 && source[5] == 105 && source[6] == 116 && source[7] == 121) { value = positiveInfinity; bytesConsumed = 8; return true; } if (source.Length >= 9 && source[0] == 45 && source[1] == 73 && source[2] == 110 && source[3] == 102 && source[4] == 105 && source[5] == 110 && source[6] == 105 && source[7] == 116 && source[8] == 121) { value = negativeInfinity; bytesConsumed = 9; return true; } if (source.Length >= 3 && source[0] == 78 && source[1] == 97 && source[2] == 78) { value = nan; bytesConsumed = 3; return true; } value = default(T); bytesConsumed = 0; return false; } public static bool TryParse(ReadOnlySpan source, out Guid value, out int bytesConsumed, char standardFormat = '\0') { switch (standardFormat) { case '\0': case 'D': return TryParseGuidCore(source, ends: false, ' ', ' ', out value, out bytesConsumed); case 'B': return TryParseGuidCore(source, ends: true, '{', '}', out value, out bytesConsumed); case 'P': return TryParseGuidCore(source, ends: true, '(', ')', out value, out bytesConsumed); case 'N': return TryParseGuidN(source, out value, out bytesConsumed); default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); } } private static bool TryParseGuidN(ReadOnlySpan text, out Guid value, out int bytesConsumed) { if (text.Length < 32) { value = default(Guid); bytesConsumed = 0; return false; } if (!TryParseUInt32X(text.Slice(0, 8), out var value2, out var bytesConsumed2) || bytesConsumed2 != 8) { value = default(Guid); bytesConsumed = 0; return false; } if (!TryParseUInt16X(text.Slice(8, 4), out var value3, out bytesConsumed2) || bytesConsumed2 != 4) { value = default(Guid); bytesConsumed = 0; return false; } if (!TryParseUInt16X(text.Slice(12, 4), out var value4, out bytesConsumed2) || bytesConsumed2 != 4) { value = default(Guid); bytesConsumed = 0; return false; } if (!TryParseUInt16X(text.Slice(16, 4), out var value5, out bytesConsumed2) || bytesConsumed2 != 4) { value = default(Guid); bytesConsumed = 0; return false; } if (!TryParseUInt64X(text.Slice(20), out var value6, out bytesConsumed2) || bytesConsumed2 != 12) { value = default(Guid); bytesConsumed = 0; return false; } bytesConsumed = 32; value = new Guid((int)value2, (short)value3, (short)value4, (byte)(value5 >> 8), (byte)value5, (byte)(value6 >> 40), (byte)(value6 >> 32), (byte)(value6 >> 24), (byte)(value6 >> 16), (byte)(value6 >> 8), (byte)value6); return true; } private static bool TryParseGuidCore(ReadOnlySpan source, bool ends, char begin, char end, out Guid value, out int bytesConsumed) { int num = 36 + (ends ? 2 : 0); if (source.Length < num) { value = default(Guid); bytesConsumed = 0; return false; } if (ends) { if (source[0] != begin) { value = default(Guid); bytesConsumed = 0; return false; } source = source.Slice(1); } if (!TryParseUInt32X(source, out var value2, out var bytesConsumed2)) { value = default(Guid); bytesConsumed = 0; return false; } if (bytesConsumed2 != 8) { value = default(Guid); bytesConsumed = 0; return false; } if (source[bytesConsumed2] != 45) { value = default(Guid); bytesConsumed = 0; return false; } source = source.Slice(9); if (!TryParseUInt16X(source, out var value3, out bytesConsumed2)) { value = default(Guid); bytesConsumed = 0; return false; } if (bytesConsumed2 != 4) { value = default(Guid); bytesConsumed = 0; return false; } if (source[bytesConsumed2] != 45) { value = default(Guid); bytesConsumed = 0; return false; } source = source.Slice(5); if (!TryParseUInt16X(source, out var value4, out bytesConsumed2)) { value = default(Guid); bytesConsumed = 0; return false; } if (bytesConsumed2 != 4) { value = default(Guid); bytesConsumed = 0; return false; } if (source[bytesConsumed2] != 45) { value = default(Guid); bytesConsumed = 0; return false; } source = source.Slice(5); if (!TryParseUInt16X(source, out var value5, out bytesConsumed2)) { value = default(Guid); bytesConsumed = 0; return false; } if (bytesConsumed2 != 4) { value = default(Guid); bytesConsumed = 0; return false; } if (source[bytesConsumed2] != 45) { value = default(Guid); bytesConsumed = 0; return false; } source = source.Slice(5); if (!TryParseUInt64X(source, out var value6, out bytesConsumed2)) { value = default(Guid); bytesConsumed = 0; return false; } if (bytesConsumed2 != 12) { value = default(Guid); bytesConsumed = 0; return false; } if (ends && source[bytesConsumed2] != end) { value = default(Guid); bytesConsumed = 0; return false; } bytesConsumed = num; value = new Guid((int)value2, (short)value3, (short)value4, (byte)(value5 >> 8), (byte)value5, (byte)(value6 >> 40), (byte)(value6 >> 32), (byte)(value6 >> 24), (byte)(value6 >> 16), (byte)(value6 >> 8), (byte)value6); return true; } [CLSCompliant(false)] public static bool TryParse(ReadOnlySpan source, out sbyte value, out int bytesConsumed, char standardFormat = '\0') { switch (standardFormat) { case '\0': case 'D': case 'G': case 'd': case 'g': return TryParseSByteD(source, out value, out bytesConsumed); case 'N': case 'n': return TryParseSByteN(source, out value, out bytesConsumed); case 'X': case 'x': value = 0; return TryParseByteX(source, out Unsafe.As(ref value), out bytesConsumed); default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); } } public static bool TryParse(ReadOnlySpan source, out short value, out int bytesConsumed, char standardFormat = '\0') { switch (standardFormat) { case '\0': case 'D': case 'G': case 'd': case 'g': return TryParseInt16D(source, out value, out bytesConsumed); case 'N': case 'n': return TryParseInt16N(source, out value, out bytesConsumed); case 'X': case 'x': value = 0; return TryParseUInt16X(source, out Unsafe.As(ref value), out bytesConsumed); default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); } } public static bool TryParse(ReadOnlySpan source, out int value, out int bytesConsumed, char standardFormat = '\0') { switch (standardFormat) { case '\0': case 'D': case 'G': case 'd': case 'g': return TryParseInt32D(source, out value, out bytesConsumed); case 'N': case 'n': return TryParseInt32N(source, out value, out bytesConsumed); case 'X': case 'x': value = 0; return TryParseUInt32X(source, out Unsafe.As(ref value), out bytesConsumed); default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); } } public static bool TryParse(ReadOnlySpan source, out long value, out int bytesConsumed, char standardFormat = '\0') { switch (standardFormat) { case '\0': case 'D': case 'G': case 'd': case 'g': return TryParseInt64D(source, out value, out bytesConsumed); case 'N': case 'n': return TryParseInt64N(source, out value, out bytesConsumed); case 'X': case 'x': value = 0L; return TryParseUInt64X(source, out Unsafe.As(ref value), out bytesConsumed); default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); } } private static bool TryParseSByteD(ReadOnlySpan source, out sbyte value, out int bytesConsumed) { int num; int num2; int num4; int num3; if (source.Length >= 1) { num = 1; num2 = 0; num3 = source[num2]; if (num3 == 45) { num = -1; num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_0123; } num3 = source[num2]; } else if (num3 == 43) { num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_0123; } num3 = source[num2]; } num4 = 0; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { if (num3 != 48) { goto IL_009c; } while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 48) { continue; } goto IL_0091; } goto IL_012b; } } goto IL_0123; IL_0123: bytesConsumed = 0; value = 0; return false; IL_0091: if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { goto IL_009c; } goto IL_012b; IL_012b: bytesConsumed = num2; value = (sbyte)(num4 * num); return true; IL_009c: num4 = num3 - 48; num2++; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num2++; num4 = num4 * 10 + num3 - 48; if ((uint)num4 > 127L + (long)((-1 * num + 1) / 2) || ((uint)num2 < (uint)source.Length && System.Buffers.Text.ParserHelpers.IsDigit(source[num2]))) { goto IL_0123; } } } } } goto IL_012b; } private static bool TryParseInt16D(ReadOnlySpan source, out short value, out int bytesConsumed) { int num; int num2; int num4; int num3; if (source.Length >= 1) { num = 1; num2 = 0; num3 = source[num2]; if (num3 == 45) { num = -1; num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_0186; } num3 = source[num2]; } else if (num3 == 43) { num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_0186; } num3 = source[num2]; } num4 = 0; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { if (num3 != 48) { goto IL_009c; } while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 48) { continue; } goto IL_0091; } goto IL_018e; } } goto IL_0186; IL_0186: bytesConsumed = 0; value = 0; return false; IL_0091: if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { goto IL_009c; } goto IL_018e; IL_018e: bytesConsumed = num2; value = (short)(num4 * num); return true; IL_009c: num4 = num3 - 48; num2++; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num2++; num4 = num4 * 10 + num3 - 48; if ((uint)num4 > 32767L + (long)((-1 * num + 1) / 2) || ((uint)num2 < (uint)source.Length && System.Buffers.Text.ParserHelpers.IsDigit(source[num2]))) { goto IL_0186; } } } } } } } } } goto IL_018e; } private static bool TryParseInt32D(ReadOnlySpan source, out int value, out int bytesConsumed) { int num; int num2; int num4; int num3; if (source.Length >= 1) { num = 1; num2 = 0; num3 = source[num2]; if (num3 == 45) { num = -1; num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_0281; } num3 = source[num2]; } else if (num3 == 43) { num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_0281; } num3 = source[num2]; } num4 = 0; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { if (num3 != 48) { goto IL_009c; } while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 48) { continue; } goto IL_0091; } goto IL_0289; } } goto IL_0281; IL_0281: bytesConsumed = 0; value = 0; return false; IL_0091: if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { goto IL_009c; } goto IL_0289; IL_0289: bytesConsumed = num2; value = num4 * num; return true; IL_009c: num4 = num3 - 48; num2++; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num2++; if (num4 <= 214748364) { num4 = num4 * 10 + num3 - 48; if ((uint)num4 <= 2147483647L + (long)((-1 * num + 1) / 2) && ((uint)num2 >= (uint)source.Length || !System.Buffers.Text.ParserHelpers.IsDigit(source[num2]))) { goto IL_0289; } } goto IL_0281; } } } } } } } } } } } } } } } } } } goto IL_0289; } private static bool TryParseInt64D(ReadOnlySpan source, out long value, out int bytesConsumed) { if (source.Length < 1) { bytesConsumed = 0; value = 0L; return false; } int num = 0; int num2 = 1; if (source[0] == 45) { num = 1; num2 = -1; if (source.Length <= num) { bytesConsumed = 0; value = 0L; return false; } } else if (source[0] == 43) { num = 1; if (source.Length <= num) { bytesConsumed = 0; value = 0L; return false; } } int num3 = 19 + num; long num4 = source[num] - 48; if (num4 < 0 || num4 > 9) { bytesConsumed = 0; value = 0L; return false; } ulong num5 = (ulong)num4; if (source.Length < num3) { for (int i = num + 1; i < source.Length; i++) { long num6 = source[i] - 48; if (num6 < 0 || num6 > 9) { bytesConsumed = i; value = (long)num5 * (long)num2; return true; } num5 = num5 * 10 + (ulong)num6; } } else { for (int j = num + 1; j < num3 - 1; j++) { long num7 = source[j] - 48; if (num7 < 0 || num7 > 9) { bytesConsumed = j; value = (long)num5 * (long)num2; return true; } num5 = num5 * 10 + (ulong)num7; } for (int k = num3 - 1; k < source.Length; k++) { long num8 = source[k] - 48; if (num8 < 0 || num8 > 9) { bytesConsumed = k; value = (long)num5 * (long)num2; return true; } bool flag = num2 > 0; bool flag2 = num8 > 8 || (flag && num8 > 7); if (num5 > 922337203685477580L || (num5 == 922337203685477580L && flag2)) { bytesConsumed = 0; value = 0L; return false; } num5 = num5 * 10 + (ulong)num8; } } bytesConsumed = source.Length; value = (long)num5 * (long)num2; return true; } private static bool TryParseSByteN(ReadOnlySpan source, out sbyte value, out int bytesConsumed) { int num; int num2; int num4; int num3; if (source.Length >= 1) { num = 1; num2 = 0; num3 = source[num2]; if (num3 == 45) { num = -1; num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_00f9; } num3 = source[num2]; } else if (num3 == 43) { num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_00f9; } num3 = source[num2]; } if (num3 != 46) { if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num4 = num3 - 48; while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 44) { continue; } if (num3 == 46) { goto IL_00d4; } if (!System.Buffers.Text.ParserHelpers.IsDigit(num3)) { break; } num4 = num4 * 10 + num3 - 48; if (num4 <= 127 + (-1 * num + 1) / 2) { continue; } goto IL_00f9; } goto IL_0101; } } else { num4 = 0; num2++; if ((uint)num2 < (uint)source.Length && source[num2] == 48) { goto IL_00d4; } } } goto IL_00f9; IL_00f9: bytesConsumed = 0; value = 0; return false; IL_0101: bytesConsumed = num2; value = (sbyte)(num4 * num); return true; IL_00d4: while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 48) { continue; } goto IL_00f1; } goto IL_0101; IL_00f1: if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { goto IL_00f9; } goto IL_0101; } private static bool TryParseInt16N(ReadOnlySpan source, out short value, out int bytesConsumed) { int num; int num2; int num4; int num3; if (source.Length >= 1) { num = 1; num2 = 0; num3 = source[num2]; if (num3 == 45) { num = -1; num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_00ff; } num3 = source[num2]; } else if (num3 == 43) { num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_00ff; } num3 = source[num2]; } if (num3 != 46) { if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num4 = num3 - 48; while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 44) { continue; } if (num3 == 46) { goto IL_00da; } if (!System.Buffers.Text.ParserHelpers.IsDigit(num3)) { break; } num4 = num4 * 10 + num3 - 48; if (num4 <= 32767 + (-1 * num + 1) / 2) { continue; } goto IL_00ff; } goto IL_0107; } } else { num4 = 0; num2++; if ((uint)num2 < (uint)source.Length && source[num2] == 48) { goto IL_00da; } } } goto IL_00ff; IL_00ff: bytesConsumed = 0; value = 0; return false; IL_0107: bytesConsumed = num2; value = (short)(num4 * num); return true; IL_00da: while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 48) { continue; } goto IL_00f7; } goto IL_0107; IL_00f7: if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { goto IL_00ff; } goto IL_0107; } private static bool TryParseInt32N(ReadOnlySpan source, out int value, out int bytesConsumed) { int num; int num2; int num4; int num3; if (source.Length >= 1) { num = 1; num2 = 0; num3 = source[num2]; if (num3 == 45) { num = -1; num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_010a; } num3 = source[num2]; } else if (num3 == 43) { num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_010a; } num3 = source[num2]; } if (num3 != 46) { if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num4 = num3 - 48; while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 44) { continue; } if (num3 == 46) { goto IL_00e5; } if (!System.Buffers.Text.ParserHelpers.IsDigit(num3)) { break; } if ((uint)num4 <= 214748364u) { num4 = num4 * 10 + num3 - 48; if ((uint)num4 <= 2147483647L + (long)((-1 * num + 1) / 2)) { continue; } } goto IL_010a; } goto IL_0112; } } else { num4 = 0; num2++; if ((uint)num2 < (uint)source.Length && source[num2] == 48) { goto IL_00e5; } } } goto IL_010a; IL_010a: bytesConsumed = 0; value = 0; return false; IL_0112: bytesConsumed = num2; value = num4 * num; return true; IL_00e5: while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 48) { continue; } goto IL_0102; } goto IL_0112; IL_0102: if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { goto IL_010a; } goto IL_0112; } private static bool TryParseInt64N(ReadOnlySpan source, out long value, out int bytesConsumed) { int num; int num2; long num4; int num3; if (source.Length >= 1) { num = 1; num2 = 0; num3 = source[num2]; if (num3 == 45) { num = -1; num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_0115; } num3 = source[num2]; } else if (num3 == 43) { num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_0115; } num3 = source[num2]; } if (num3 != 46) { if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { num4 = num3 - 48; while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 44) { continue; } if (num3 == 46) { goto IL_00f0; } if (!System.Buffers.Text.ParserHelpers.IsDigit(num3)) { break; } if ((ulong)num4 <= 922337203685477580uL) { num4 = num4 * 10 + num3 - 48; if ((ulong)num4 <= (ulong)(long.MaxValue + (-1 * num + 1) / 2)) { continue; } } goto IL_0115; } goto IL_011e; } } else { num4 = 0L; num2++; if ((uint)num2 < (uint)source.Length && source[num2] == 48) { goto IL_00f0; } } } goto IL_0115; IL_0115: bytesConsumed = 0; value = 0L; return false; IL_011e: bytesConsumed = num2; value = num4 * num; return true; IL_00f0: while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 48) { continue; } goto IL_010d; } goto IL_011e; IL_010d: if (System.Buffers.Text.ParserHelpers.IsDigit(num3)) { goto IL_0115; } goto IL_011e; } public static bool TryParse(ReadOnlySpan source, out byte value, out int bytesConsumed, char standardFormat = '\0') { switch (standardFormat) { case '\0': case 'D': case 'G': case 'd': case 'g': return TryParseByteD(source, out value, out bytesConsumed); case 'N': case 'n': return TryParseByteN(source, out value, out bytesConsumed); case 'X': case 'x': return TryParseByteX(source, out value, out bytesConsumed); default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); } } [CLSCompliant(false)] public static bool TryParse(ReadOnlySpan source, out ushort value, out int bytesConsumed, char standardFormat = '\0') { switch (standardFormat) { case '\0': case 'D': case 'G': case 'd': case 'g': return TryParseUInt16D(source, out value, out bytesConsumed); case 'N': case 'n': return TryParseUInt16N(source, out value, out bytesConsumed); case 'X': case 'x': return TryParseUInt16X(source, out value, out bytesConsumed); default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); } } [CLSCompliant(false)] public static bool TryParse(ReadOnlySpan source, out uint value, out int bytesConsumed, char standardFormat = '\0') { switch (standardFormat) { case '\0': case 'D': case 'G': case 'd': case 'g': return TryParseUInt32D(source, out value, out bytesConsumed); case 'N': case 'n': return TryParseUInt32N(source, out value, out bytesConsumed); case 'X': case 'x': return TryParseUInt32X(source, out value, out bytesConsumed); default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); } } [CLSCompliant(false)] public static bool TryParse(ReadOnlySpan source, out ulong value, out int bytesConsumed, char standardFormat = '\0') { switch (standardFormat) { case '\0': case 'D': case 'G': case 'd': case 'g': return TryParseUInt64D(source, out value, out bytesConsumed); case 'N': case 'n': return TryParseUInt64N(source, out value, out bytesConsumed); case 'X': case 'x': return TryParseUInt64X(source, out value, out bytesConsumed); default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); } } private static bool TryParseByteD(ReadOnlySpan source, out byte value, out int bytesConsumed) { int num; int num3; int num2; if (source.Length >= 1) { num = 0; num2 = source[num]; num3 = 0; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { if (num2 != 48) { goto IL_0056; } while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 48) { continue; } goto IL_004b; } goto IL_00dd; } } goto IL_00d5; IL_004b: if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { goto IL_0056; } goto IL_00dd; IL_0056: num3 = num2 - 48; num++; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num++; num3 = num3 * 10 + num2 - 48; if ((uint)num3 > 255u || ((uint)num < (uint)source.Length && System.Buffers.Text.ParserHelpers.IsDigit(source[num]))) { goto IL_00d5; } } } } } goto IL_00dd; IL_00dd: bytesConsumed = num; value = (byte)num3; return true; IL_00d5: bytesConsumed = 0; value = 0; return false; } private static bool TryParseUInt16D(ReadOnlySpan source, out ushort value, out int bytesConsumed) { int num; int num3; int num2; if (source.Length >= 1) { num = 0; num2 = source[num]; num3 = 0; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { if (num2 != 48) { goto IL_0056; } while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 48) { continue; } goto IL_004b; } goto IL_013d; } } goto IL_0135; IL_004b: if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { goto IL_0056; } goto IL_013d; IL_0056: num3 = num2 - 48; num++; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num++; num3 = num3 * 10 + num2 - 48; if ((uint)num3 > 65535u || ((uint)num < (uint)source.Length && System.Buffers.Text.ParserHelpers.IsDigit(source[num]))) { goto IL_0135; } } } } } } } } } goto IL_013d; IL_013d: bytesConsumed = num; value = (ushort)num3; return true; IL_0135: bytesConsumed = 0; value = 0; return false; } private static bool TryParseUInt32D(ReadOnlySpan source, out uint value, out int bytesConsumed) { int num; int num3; int num2; if (source.Length >= 1) { num = 0; num2 = source[num]; num3 = 0; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { if (num2 != 48) { goto IL_0056; } while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 48) { continue; } goto IL_004b; } goto IL_023d; } } goto IL_0235; IL_004b: if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { goto IL_0056; } goto IL_023d; IL_0056: num3 = num2 - 48; num++; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num++; if ((uint)num3 <= 429496729u && (num3 != 429496729 || num2 <= 53)) { num3 = num3 * 10 + num2 - 48; if ((uint)num >= (uint)source.Length || !System.Buffers.Text.ParserHelpers.IsDigit(source[num])) { goto IL_023d; } } goto IL_0235; } } } } } } } } } } } } } } } } } } goto IL_023d; IL_023d: bytesConsumed = num; value = (uint)num3; return true; IL_0235: bytesConsumed = 0; value = 0u; return false; } private static bool TryParseUInt64D(ReadOnlySpan source, out ulong value, out int bytesConsumed) { if (source.Length < 1) { bytesConsumed = 0; value = 0uL; return false; } ulong num = (uint)(source[0] - 48); if (num > 9) { bytesConsumed = 0; value = 0uL; return false; } ulong num2 = num; if (source.Length < 19) { for (int i = 1; i < source.Length; i++) { ulong num3 = (uint)(source[i] - 48); if (num3 > 9) { bytesConsumed = i; value = num2; return true; } num2 = num2 * 10 + num3; } } else { for (int j = 1; j < 18; j++) { ulong num4 = (uint)(source[j] - 48); if (num4 > 9) { bytesConsumed = j; value = num2; return true; } num2 = num2 * 10 + num4; } for (int k = 18; k < source.Length; k++) { ulong num5 = (uint)(source[k] - 48); if (num5 > 9) { bytesConsumed = k; value = num2; return true; } if (num2 > 1844674407370955161L || (num2 == 1844674407370955161L && num5 > 5)) { bytesConsumed = 0; value = 0uL; return false; } num2 = num2 * 10 + num5; } } bytesConsumed = source.Length; value = num2; return true; } private static bool TryParseByteN(ReadOnlySpan source, out byte value, out int bytesConsumed) { int num; int num3; int num2; if (source.Length >= 1) { num = 0; num2 = source[num]; if (num2 == 43) { num++; if ((uint)num >= (uint)source.Length) { goto IL_00ce; } num2 = source[num]; } if (num2 != 46) { if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num3 = num2 - 48; while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 44) { continue; } if (num2 == 46) { goto IL_00a9; } if (!System.Buffers.Text.ParserHelpers.IsDigit(num2)) { break; } num3 = num3 * 10 + num2 - 48; if (num3 <= 255) { continue; } goto IL_00ce; } goto IL_00d6; } } else { num3 = 0; num++; if ((uint)num < (uint)source.Length && source[num] == 48) { goto IL_00a9; } } } goto IL_00ce; IL_00c6: if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { goto IL_00ce; } goto IL_00d6; IL_00ce: bytesConsumed = 0; value = 0; return false; IL_00d6: bytesConsumed = num; value = (byte)num3; return true; IL_00a9: while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 48) { continue; } goto IL_00c6; } goto IL_00d6; } private static bool TryParseUInt16N(ReadOnlySpan source, out ushort value, out int bytesConsumed) { int num; int num3; int num2; if (source.Length >= 1) { num = 0; num2 = source[num]; if (num2 == 43) { num++; if ((uint)num >= (uint)source.Length) { goto IL_00ce; } num2 = source[num]; } if (num2 != 46) { if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num3 = num2 - 48; while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 44) { continue; } if (num2 == 46) { goto IL_00a9; } if (!System.Buffers.Text.ParserHelpers.IsDigit(num2)) { break; } num3 = num3 * 10 + num2 - 48; if (num3 <= 65535) { continue; } goto IL_00ce; } goto IL_00d6; } } else { num3 = 0; num++; if ((uint)num < (uint)source.Length && source[num] == 48) { goto IL_00a9; } } } goto IL_00ce; IL_00c6: if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { goto IL_00ce; } goto IL_00d6; IL_00ce: bytesConsumed = 0; value = 0; return false; IL_00d6: bytesConsumed = num; value = (ushort)num3; return true; IL_00a9: while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 48) { continue; } goto IL_00c6; } goto IL_00d6; } private static bool TryParseUInt32N(ReadOnlySpan source, out uint value, out int bytesConsumed) { int num; int num3; int num2; if (source.Length >= 1) { num = 0; num2 = source[num]; if (num2 == 43) { num++; if ((uint)num >= (uint)source.Length) { goto IL_00de; } num2 = source[num]; } if (num2 != 46) { if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num3 = num2 - 48; while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 44) { continue; } if (num2 == 46) { goto IL_00b9; } if (!System.Buffers.Text.ParserHelpers.IsDigit(num2)) { break; } if ((uint)num3 <= 429496729u && (num3 != 429496729 || num2 <= 53)) { num3 = num3 * 10 + num2 - 48; continue; } goto IL_00de; } goto IL_00e6; } } else { num3 = 0; num++; if ((uint)num < (uint)source.Length && source[num] == 48) { goto IL_00b9; } } } goto IL_00de; IL_00d6: if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { goto IL_00de; } goto IL_00e6; IL_00de: bytesConsumed = 0; value = 0u; return false; IL_00e6: bytesConsumed = num; value = (uint)num3; return true; IL_00b9: while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 48) { continue; } goto IL_00d6; } goto IL_00e6; } private static bool TryParseUInt64N(ReadOnlySpan source, out ulong value, out int bytesConsumed) { int num; long num3; int num2; if (source.Length >= 1) { num = 0; num2 = source[num]; if (num2 == 43) { num++; if ((uint)num >= (uint)source.Length) { goto IL_00eb; } num2 = source[num]; } if (num2 != 46) { if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { num3 = num2 - 48; while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 44) { continue; } if (num2 == 46) { goto IL_00c6; } if (!System.Buffers.Text.ParserHelpers.IsDigit(num2)) { break; } if ((ulong)num3 <= 1844674407370955161uL && (num3 != 1844674407370955161L || num2 <= 53)) { num3 = num3 * 10 + num2 - 48; continue; } goto IL_00eb; } goto IL_00f4; } } else { num3 = 0L; num++; if ((uint)num < (uint)source.Length && source[num] == 48) { goto IL_00c6; } } } goto IL_00eb; IL_00e3: if (System.Buffers.Text.ParserHelpers.IsDigit(num2)) { goto IL_00eb; } goto IL_00f4; IL_00eb: bytesConsumed = 0; value = 0uL; return false; IL_00f4: bytesConsumed = num; value = (ulong)num3; return true; IL_00c6: while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 48) { continue; } goto IL_00e3; } goto IL_00f4; } private static bool TryParseByteX(ReadOnlySpan source, out byte value, out int bytesConsumed) { if (source.Length < 1) { bytesConsumed = 0; value = 0; return false; } byte[] s_hexLookup = System.Buffers.Text.ParserHelpers.s_hexLookup; byte b = source[0]; byte b2 = s_hexLookup[b]; if (b2 == byte.MaxValue) { bytesConsumed = 0; value = 0; return false; } uint num = b2; if (source.Length <= 2) { for (int i = 1; i < source.Length; i++) { b = source[i]; b2 = s_hexLookup[b]; if (b2 == byte.MaxValue) { bytesConsumed = i; value = (byte)num; return true; } num = (num << 4) + b2; } } else { for (int j = 1; j < 2; j++) { b = source[j]; b2 = s_hexLookup[b]; if (b2 == byte.MaxValue) { bytesConsumed = j; value = (byte)num; return true; } num = (num << 4) + b2; } for (int k = 2; k < source.Length; k++) { b = source[k]; b2 = s_hexLookup[b]; if (b2 == byte.MaxValue) { bytesConsumed = k; value = (byte)num; return true; } if (num > 15) { bytesConsumed = 0; value = 0; return false; } num = (num << 4) + b2; } } bytesConsumed = source.Length; value = (byte)num; return true; } private static bool TryParseUInt16X(ReadOnlySpan source, out ushort value, out int bytesConsumed) { if (source.Length < 1) { bytesConsumed = 0; value = 0; return false; } byte[] s_hexLookup = System.Buffers.Text.ParserHelpers.s_hexLookup; byte b = source[0]; byte b2 = s_hexLookup[b]; if (b2 == byte.MaxValue) { bytesConsumed = 0; value = 0; return false; } uint num = b2; if (source.Length <= 4) { for (int i = 1; i < source.Length; i++) { b = source[i]; b2 = s_hexLookup[b]; if (b2 == byte.MaxValue) { bytesConsumed = i; value = (ushort)num; return true; } num = (num << 4) + b2; } } else { for (int j = 1; j < 4; j++) { b = source[j]; b2 = s_hexLookup[b]; if (b2 == byte.MaxValue) { bytesConsumed = j; value = (ushort)num; return true; } num = (num << 4) + b2; } for (int k = 4; k < source.Length; k++) { b = source[k]; b2 = s_hexLookup[b]; if (b2 == byte.MaxValue) { bytesConsumed = k; value = (ushort)num; return true; } if (num > 4095) { bytesConsumed = 0; value = 0; return false; } num = (num << 4) + b2; } } bytesConsumed = source.Length; value = (ushort)num; return true; } private static bool TryParseUInt32X(ReadOnlySpan source, out uint value, out int bytesConsumed) { if (source.Length < 1) { bytesConsumed = 0; value = 0u; return false; } byte[] s_hexLookup = System.Buffers.Text.ParserHelpers.s_hexLookup; byte b = source[0]; byte b2 = s_hexLookup[b]; if (b2 == byte.MaxValue) { bytesConsumed = 0; value = 0u; return false; } uint num = b2; if (source.Length <= 8) { for (int i = 1; i < source.Length; i++) { b = source[i]; b2 = s_hexLookup[b]; if (b2 == byte.MaxValue) { bytesConsumed = i; value = num; return true; } num = (num << 4) + b2; } } else { for (int j = 1; j < 8; j++) { b = source[j]; b2 = s_hexLookup[b]; if (b2 == byte.MaxValue) { bytesConsumed = j; value = num; return true; } num = (num << 4) + b2; } for (int k = 8; k < source.Length; k++) { b = source[k]; b2 = s_hexLookup[b]; if (b2 == byte.MaxValue) { bytesConsumed = k; value = num; return true; } if (num > 268435455) { bytesConsumed = 0; value = 0u; return false; } num = (num << 4) + b2; } } bytesConsumed = source.Length; value = num; return true; } private static bool TryParseUInt64X(ReadOnlySpan source, out ulong value, out int bytesConsumed) { if (source.Length < 1) { bytesConsumed = 0; value = 0uL; return false; } byte[] s_hexLookup = System.Buffers.Text.ParserHelpers.s_hexLookup; byte b = source[0]; byte b2 = s_hexLookup[b]; if (b2 == byte.MaxValue) { bytesConsumed = 0; value = 0uL; return false; } ulong num = b2; if (source.Length <= 16) { for (int i = 1; i < source.Length; i++) { b = source[i]; b2 = s_hexLookup[b]; if (b2 == byte.MaxValue) { bytesConsumed = i; value = num; return true; } num = (num << 4) + b2; } } else { for (int j = 1; j < 16; j++) { b = source[j]; b2 = s_hexLookup[b]; if (b2 == byte.MaxValue) { bytesConsumed = j; value = num; return true; } num = (num << 4) + b2; } for (int k = 16; k < source.Length; k++) { b = source[k]; b2 = s_hexLookup[b]; if (b2 == byte.MaxValue) { bytesConsumed = k; value = num; return true; } if (num > 1152921504606846975L) { bytesConsumed = 0; value = 0uL; return false; } num = (num << 4) + b2; } } bytesConsumed = source.Length; value = num; return true; } private static bool TryParseNumber(ReadOnlySpan source, ref NumberBuffer number, out int bytesConsumed, ParseNumberOptions options, out bool textUsedExponentNotation) { textUsedExponentNotation = false; if (source.Length == 0) { bytesConsumed = 0; return false; } Span digits = number.Digits; int i = 0; int num = 0; byte b = source[i]; if (b != 43) { if (b != 45) { goto IL_0055; } number.IsNegative = true; } i++; if (i == source.Length) { bytesConsumed = 0; return false; } b = source[i]; goto IL_0055; IL_0055: int num2 = i; for (; i != source.Length; i++) { b = source[i]; if (b != 48) { break; } } if (i == source.Length) { digits[0] = 0; number.Scale = 0; bytesConsumed = i; return true; } int num3 = i; for (; i != source.Length; i++) { b = source[i]; if ((uint)(b - 48) > 9u) { break; } } int num4 = i - num2; int num5 = i - num3; int num6 = Math.Min(num5, 50); source.Slice(num3, num6).CopyTo(digits); num = num6; number.Scale = num5; if (i == source.Length) { bytesConsumed = i; return true; } int num7 = 0; if (b == 46) { i++; int num8 = i; for (; i != source.Length; i++) { b = source[i]; if ((uint)(b - 48) > 9u) { break; } } num7 = i - num8; int j = num8; if (num == 0) { for (; j < i && source[j] == 48; j++) { number.Scale--; } } int num9 = Math.Min(i - j, 51 - num - 1); source.Slice(j, num9).CopyTo(digits.Slice(num)); num += num9; if (i == source.Length) { if (num4 == 0 && num7 == 0) { bytesConsumed = 0; return false; } bytesConsumed = i; return true; } } if (num4 == 0 && num7 == 0) { bytesConsumed = 0; return false; } if ((b & -33) != 69) { bytesConsumed = i; return true; } textUsedExponentNotation = true; i++; if ((options & ParseNumberOptions.AllowExponent) == 0) { bytesConsumed = 0; return false; } if (i == source.Length) { bytesConsumed = 0; return false; } bool flag = false; b = source[i]; if (b != 43) { if (b != 45) { goto IL_0229; } flag = true; } i++; if (i == source.Length) { bytesConsumed = 0; return false; } b = source[i]; goto IL_0229; IL_0229: if (!TryParseUInt32D(source.Slice(i), out var value, out var bytesConsumed2)) { bytesConsumed = 0; return false; } i += bytesConsumed2; if (flag) { if (number.Scale < int.MinValue + value) { number.Scale = int.MinValue; } else { number.Scale -= (int)value; } } else { if (number.Scale > 2147483647L - (long)value) { bytesConsumed = 0; return false; } number.Scale += (int)value; } bytesConsumed = i; return true; } private static bool TryParseTimeSpanBigG(ReadOnlySpan source, out TimeSpan value, out int bytesConsumed) { int i = 0; byte b = 0; for (; i != source.Length; i++) { b = source[i]; if (b != 32 && b != 9) { break; } } if (i == source.Length) { value = default(TimeSpan); bytesConsumed = 0; return false; } bool isNegative = false; if (b == 45) { isNegative = true; i++; if (i == source.Length) { value = default(TimeSpan); bytesConsumed = 0; return false; } } if (!TryParseUInt32D(source.Slice(i), out var value2, out var bytesConsumed2)) { value = default(TimeSpan); bytesConsumed = 0; return false; } i += bytesConsumed2; if (i == source.Length || source[i++] != 58) { value = default(TimeSpan); bytesConsumed = 0; return false; } if (!TryParseUInt32D(source.Slice(i), out var value3, out bytesConsumed2)) { value = default(TimeSpan); bytesConsumed = 0; return false; } i += bytesConsumed2; if (i == source.Length || source[i++] != 58) { value = default(TimeSpan); bytesConsumed = 0; return false; } if (!TryParseUInt32D(source.Slice(i), out var value4, out bytesConsumed2)) { value = default(TimeSpan); bytesConsumed = 0; return false; } i += bytesConsumed2; if (i == source.Length || source[i++] != 58) { value = default(TimeSpan); bytesConsumed = 0; return false; } if (!TryParseUInt32D(source.Slice(i), out var value5, out bytesConsumed2)) { value = default(TimeSpan); bytesConsumed = 0; return false; } i += bytesConsumed2; if (i == source.Length || source[i++] != 46) { value = default(TimeSpan); bytesConsumed = 0; return false; } if (!TryParseTimeSpanFraction(source.Slice(i), out var value6, out bytesConsumed2)) { value = default(TimeSpan); bytesConsumed = 0; return false; } i += bytesConsumed2; if (!TryCreateTimeSpan(isNegative, value2, value3, value4, value5, value6, out value)) { value = default(TimeSpan); bytesConsumed = 0; return false; } if (i != source.Length && (source[i] == 46 || source[i] == 58)) { value = default(TimeSpan); bytesConsumed = 0; return false; } bytesConsumed = i; return true; } private static bool TryParseTimeSpanC(ReadOnlySpan source, out TimeSpan value, out int bytesConsumed) { TimeSpanSplitter timeSpanSplitter = default(TimeSpanSplitter); if (!timeSpanSplitter.TrySplitTimeSpan(source, periodUsedToSeparateDay: true, out bytesConsumed)) { value = default(TimeSpan); return false; } bool isNegative = timeSpanSplitter.IsNegative; bool flag; switch (timeSpanSplitter.Separators) { case 0u: flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, 0u, 0u, 0u, 0u, out value); break; case 16777216u: flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, 0u, 0u, out value); break; case 33619968u: flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, 0u, 0u, out value); break; case 16842752u: flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, 0u, out value); break; case 33620224u: flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, 0u, out value); break; case 16843264u: flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, out value); break; case 33620226u: flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, timeSpanSplitter.V5, out value); break; default: value = default(TimeSpan); flag = false; break; } if (!flag) { bytesConsumed = 0; return false; } return true; } public static bool TryParse(ReadOnlySpan source, out TimeSpan value, out int bytesConsumed, char standardFormat = '\0') { switch (standardFormat) { case '\0': case 'T': case 'c': case 't': return TryParseTimeSpanC(source, out value, out bytesConsumed); case 'G': return TryParseTimeSpanBigG(source, out value, out bytesConsumed); case 'g': return TryParseTimeSpanLittleG(source, out value, out bytesConsumed); default: return <364de6aa-3638-4f0c-b478-eff7d6f86309>ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed); } } private static bool TryParseTimeSpanFraction(ReadOnlySpan source, out uint value, out int bytesConsumed) { int num = 0; if (num == source.Length) { value = 0u; bytesConsumed = 0; return false; } uint num2 = (uint)(source[num] - 48); if (num2 > 9) { value = 0u; bytesConsumed = 0; return false; } num++; uint num3 = num2; int num4 = 1; while (num != source.Length) { num2 = (uint)(source[num] - 48); if (num2 > 9) { break; } num++; num4++; if (num4 > 7) { value = 0u; bytesConsumed = 0; return false; } num3 = 10 * num3 + num2; } switch (num4) { case 6: num3 *= 10; break; case 5: num3 *= 100; break; case 4: num3 *= 1000; break; case 3: num3 *= 10000; break; case 2: num3 *= 100000; break; default: num3 *= 1000000; break; case 7: break; } value = num3; bytesConsumed = num; return true; } private static bool TryCreateTimeSpan(bool isNegative, uint days, uint hours, uint minutes, uint seconds, uint fraction, out TimeSpan timeSpan) { if (hours > 23 || minutes > 59 || seconds > 59) { timeSpan = default(TimeSpan); return false; } long num = ((long)days * 3600L * 24 + (long)hours * 3600L + (long)minutes * 60L + seconds) * 1000; long ticks; if (isNegative) { num = -num; if (num < -922337203685477L) { timeSpan = default(TimeSpan); return false; } long num2 = num * 10000; if (num2 < long.MinValue + fraction) { timeSpan = default(TimeSpan); return false; } ticks = num2 - fraction; } else { if (num > 922337203685477L) { timeSpan = default(TimeSpan); return false; } long num3 = num * 10000; if (num3 > long.MaxValue - (long)fraction) { timeSpan = default(TimeSpan); return false; } ticks = num3 + fraction; } timeSpan = new TimeSpan(ticks); return true; } private static bool TryParseTimeSpanLittleG(ReadOnlySpan source, out TimeSpan value, out int bytesConsumed) { TimeSpanSplitter timeSpanSplitter = default(TimeSpanSplitter); if (!timeSpanSplitter.TrySplitTimeSpan(source, periodUsedToSeparateDay: false, out bytesConsumed)) { value = default(TimeSpan); return false; } bool isNegative = timeSpanSplitter.IsNegative; bool flag; switch (timeSpanSplitter.Separators) { case 0u: flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, 0u, 0u, 0u, 0u, out value); break; case 16777216u: flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, 0u, 0u, out value); break; case 16842752u: flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, 0u, out value); break; case 16843008u: flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, 0u, out value); break; case 16843264u: flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, out value); break; case 16843010u: flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, timeSpanSplitter.V5, out value); break; default: value = default(TimeSpan); flag = false; break; } if (!flag) { bytesConsumed = 0; return false; } return true; } } } namespace System.Buffers.Binary { internal static class BinaryPrimitives { [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static sbyte ReverseEndianness(sbyte value) { return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short ReverseEndianness(short value) { return (short)(((value & 0xFF) << 8) | ((value & 0xFF00) >> 8)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int ReverseEndianness(int value) { return (int)ReverseEndianness((uint)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long ReverseEndianness(long value) { return (long)ReverseEndianness((ulong)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte ReverseEndianness(byte value) { return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ushort ReverseEndianness(ushort value) { return (ushort)((value >> 8) + (value << 8)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint ReverseEndianness(uint value) { uint num = value & 0xFF00FFu; uint num2 = value & 0xFF00FF00u; return ((num >> 8) | (num << 24)) + ((num2 << 8) | (num2 >> 24)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong ReverseEndianness(ulong value) { return ((ulong)ReverseEndianness((uint)value) << 32) + ReverseEndianness((uint)(value >> 32)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short ReadInt16BigEndian(ReadOnlySpan source) { short num = MemoryMarshal.Read(source); if (BitConverter.IsLittleEndian) { num = ReverseEndianness(num); } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int ReadInt32BigEndian(ReadOnlySpan source) { int num = MemoryMarshal.Read(source); if (BitConverter.IsLittleEndian) { num = ReverseEndianness(num); } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long ReadInt64BigEndian(ReadOnlySpan source) { long num = MemoryMarshal.Read(source); if (BitConverter.IsLittleEndian) { num = ReverseEndianness(num); } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ushort ReadUInt16BigEndian(ReadOnlySpan source) { ushort num = MemoryMarshal.Read(source); if (BitConverter.IsLittleEndian) { num = ReverseEndianness(num); } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint ReadUInt32BigEndian(ReadOnlySpan source) { uint num = MemoryMarshal.Read(source); if (BitConverter.IsLittleEndian) { num = ReverseEndianness(num); } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong ReadUInt64BigEndian(ReadOnlySpan source) { ulong num = MemoryMarshal.Read(source); if (BitConverter.IsLittleEndian) { num = ReverseEndianness(num); } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryReadInt16BigEndian(ReadOnlySpan source, out short value) { bool result = MemoryMarshal.TryRead(source, out value); if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryReadInt32BigEndian(ReadOnlySpan source, out int value) { bool result = MemoryMarshal.TryRead(source, out value); if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryReadInt64BigEndian(ReadOnlySpan source, out long value) { bool result = MemoryMarshal.TryRead(source, out value); if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryReadUInt16BigEndian(ReadOnlySpan source, out ushort value) { bool result = MemoryMarshal.TryRead(source, out value); if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryReadUInt32BigEndian(ReadOnlySpan source, out uint value) { bool result = MemoryMarshal.TryRead(source, out value); if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryReadUInt64BigEndian(ReadOnlySpan source, out ulong value) { bool result = MemoryMarshal.TryRead(source, out value); if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short ReadInt16LittleEndian(ReadOnlySpan source) { short num = MemoryMarshal.Read(source); if (!BitConverter.IsLittleEndian) { num = ReverseEndianness(num); } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int ReadInt32LittleEndian(ReadOnlySpan source) { int num = MemoryMarshal.Read(source); if (!BitConverter.IsLittleEndian) { num = ReverseEndianness(num); } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long ReadInt64LittleEndian(ReadOnlySpan source) { long num = MemoryMarshal.Read(source); if (!BitConverter.IsLittleEndian) { num = ReverseEndianness(num); } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ushort ReadUInt16LittleEndian(ReadOnlySpan source) { ushort num = MemoryMarshal.Read(source); if (!BitConverter.IsLittleEndian) { num = ReverseEndianness(num); } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint ReadUInt32LittleEndian(ReadOnlySpan source) { uint num = MemoryMarshal.Read(source); if (!BitConverter.IsLittleEndian) { num = ReverseEndianness(num); } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong ReadUInt64LittleEndian(ReadOnlySpan source) { ulong num = MemoryMarshal.Read(source); if (!BitConverter.IsLittleEndian) { num = ReverseEndianness(num); } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryReadInt16LittleEndian(ReadOnlySpan source, out short value) { bool result = MemoryMarshal.TryRead(source, out value); if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryReadInt32LittleEndian(ReadOnlySpan source, out int value) { bool result = MemoryMarshal.TryRead(source, out value); if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryReadInt64LittleEndian(ReadOnlySpan source, out long value) { bool result = MemoryMarshal.TryRead(source, out value); if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryReadUInt16LittleEndian(ReadOnlySpan source, out ushort value) { bool result = MemoryMarshal.TryRead(source, out value); if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryReadUInt32LittleEndian(ReadOnlySpan source, out uint value) { bool result = MemoryMarshal.TryRead(source, out value); if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryReadUInt64LittleEndian(ReadOnlySpan source, out ulong value) { bool result = MemoryMarshal.TryRead(source, out value); if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteInt16BigEndian(Span destination, short value) { if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteInt32BigEndian(Span destination, int value) { if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteInt64BigEndian(Span destination, long value) { if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static void WriteUInt16BigEndian(Span destination, ushort value) { if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static void WriteUInt32BigEndian(Span destination, uint value) { if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static void WriteUInt64BigEndian(Span destination, ulong value) { if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteInt16BigEndian(Span destination, short value) { if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteInt32BigEndian(Span destination, int value) { if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteInt64BigEndian(Span destination, long value) { if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryWriteUInt16BigEndian(Span destination, ushort value) { if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryWriteUInt32BigEndian(Span destination, uint value) { if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryWriteUInt64BigEndian(Span destination, ulong value) { if (BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteInt16LittleEndian(Span destination, short value) { if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteInt32LittleEndian(Span destination, int value) { if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteInt64LittleEndian(Span destination, long value) { if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static void WriteUInt16LittleEndian(Span destination, ushort value) { if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static void WriteUInt32LittleEndian(Span destination, uint value) { if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static void WriteUInt64LittleEndian(Span destination, ulong value) { if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteInt16LittleEndian(Span destination, short value) { if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteInt32LittleEndian(Span destination, int value) { if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteInt64LittleEndian(Span destination, long value) { if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryWriteUInt16LittleEndian(Span destination, ushort value) { if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryWriteUInt32LittleEndian(Span destination, uint value) { if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryWriteUInt64LittleEndian(Span destination, ulong value) { if (!BitConverter.IsLittleEndian) { value = ReverseEndianness(value); } return MemoryMarshal.TryWrite(destination, ref value); } } } [CompilerGenerated] internal sealed class <364de6aa-3638-4f0c-b478-eff7d6f86309> { [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 15)] private struct __StaticArrayInitTypeSize=15 { } [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 28)] private struct __StaticArrayInitTypeSize=28 { } [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 42)] private struct __StaticArrayInitTypeSize=42 { } [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 48)] private struct __StaticArrayInitTypeSize=48 { } [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 52)] private struct __StaticArrayInitTypeSize=52 { } [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 64)] private struct __StaticArrayInitTypeSize=64 { } [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 240)] private struct __StaticArrayInitTypeSize=240 { } [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 256)] private struct __StaticArrayInitTypeSize=256 { } [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 336)] private struct __StaticArrayInitTypeSize=336 { } internal static readonly __StaticArrayInitTypeSize=64 0953DF544832295E4A5B19928F95C351F25DA86A/* Not supported: data(41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 59 5A 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 72 73 74 75 76 77 78 79 7A 30 31 32 33 34 35 36 37 38 39 2B 2F) */; internal static readonly __StaticArrayInitTypeSize=256 1588174EA926BCCEB6275C029A42C7E3DBA4D523/* Not supported: data(FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 3E FF FF FF 3F 34 35 36 37 38 39 3A 3B 3C 3D FF FF FF FF FF FF FF 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 16 17 18 19 FF FF FF FF FF FF 1A 1B 1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F 30 31 32 33 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF) */; internal static readonly __StaticArrayInitTypeSize=336 2B2055E39CBB1C111FB5C1C05492B3E5AAC607ED/* Not supported: data(00 00 00 04 BF C9 1B 8E 9E B5 70 2B A8 AD C5 9D D6 95 43 0E 05 8D 29 AF D4 A6 CF FF 49 1F 78 C2 FA F7 DA 87 8F 7A E7 D7 A0 14 9B C5 16 AB B3 EF 9C 32 23 99 C0 AD 0F 85 DE 8C E9 80 C9 47 BA 93 E6 A6 D3 A8 C5 B9 02 A4 A8 17 E6 7F 2B A1 16 B6 90 BF 9B 85 91 A2 28 CA 66 55 27 39 8D F7 70 E0 40 61 82 37 35 0C 2E F9 2C C9 3C E3 FF 96 52 8A 62 17 BF D6 F3 A6 91 99 8A DE F9 9D FB EB 7E AA 7E BC 9D A7 4A D1 49 BD 88 2F 6A 5C 19 FC 26 D2 F8 83 7C 24 20 DF 50 E9 73 E3 CC F2 29 2F 84 81 E2 E4 8E 55 57 C2 CA 8F 60 E1 4D C4 BE 94 95 E6 C3 94 39 45 AD 1E B1 CF 65 C1 7E B1 53 7C 12 BB B3 E9 39 A5 27 EA 7F A8 B5 19 09 6B BA 60 C5 97 AB 53 75 FD F7 02 B4 88 A0 D3 65 F0 BC 35 43 F6 C4 E4 BC 64 7C 46 D0 DD ED 82 53 7C 6E BA CA C7 B7 A0 73 DB 93 E0 F4 B3 53 00 CB 38 DB 27 17 A2 29 CC 23 54 77 83 FF 91 82 BC A4 3D A9 DE 80 83 00 4F 31 4A EC 3C E5 EC 17 E2 32 CF CD 5F 60 D5 78 19 7A 63 25 43 31 C0 A2 3B E4 5E AB 8E 1C AD B0 C5 6A 83 62 CE EC 9B 5C 49 0B BA D9 DC 71 8C 38 39 82 47 97 B8 00 FD 1A 99 8D 4D 44 7A E2 E3) */; internal static readonly __StaticArrayInitTypeSize=256 3CDA7449B0586AB873C75C04BB11D4864F5D7392/* Not supported: data(FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 00 01 02 03 04 05 06 07 08 09 FF FF FF FF FF FF FF 0A 0B 0C 0D 0E 0F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 0A 0B 0C 0D 0E 0F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF) */; internal static readonly __StaticArrayInitTypeSize=240 608454F961E288A48E34666C94032BEDEFD399E1/* Not supported: data(00 00 00 00 00 00 00 A0 00 00 00 00 00 00 00 C8 00 00 00 00 00 00 00 FA 00 00 00 00 00 00 40 9C 00 00 00 00 00 00 50 C3 00 00 00 00 00 00 24 F4 00 00 00 00 00 80 96 98 00 00 00 00 00 20 BC BE 00 00 00 00 00 28 6B EE 00 00 00 00 00 F9 02 95 00 00 00 00 40 B7 43 BA 00 00 00 00 10 A5 D4 E8 00 00 00 00 2A E7 84 91 00 00 00 80 F4 20 E6 B5 00 00 00 A0 31 A9 5F E3 CD CC CC CC CC CC CC CC 0B D7 A3 70 3D 0A D7 A3 3C DF 4F 8D 97 6E 12 83 2E 65 19 E2 58 17 B7 D1 25 84 47 1B 47 AC C5 A7 B7 69 6C AF 05 BD 37 86 BE 42 7A E5 D5 94 BF D6 FF CE 61 84 11 77 CC AB 99 A5 B4 36 41 5F 70 89 C2 D5 ED BD CE FE E6 DB 02 AB 24 CB 0B FF EB AF CF 88 50 6F 09 CC BC 8C 18 0E B4 4B 42 13 2E E1 13 D8 5C 09 35 DC 24 B4 DC AC B0 3A F7 7C 1D 90) */; internal static readonly __StaticArrayInitTypeSize=48 B8B960BE929E7BAB90AE2CAEF2468C56CD5414C1/* Not supported: data(6A 61 6E 00 66 65 62 00 6D 61 72 00 61 70 72 00 6D 61 79 00 6A 75 6E 00 6A 75 6C 00 61 75 67 00 73 65 70 00 6F 63 74 00 6E 6F 76 00 64 65 63 00) */; internal static readonly __StaticArrayInitTypeSize=28 BD20BFA840DDF83194ECD4397DA071ECD4C1C72F/* Not supported: data(53 75 6E 00 4D 6F 6E 00 54 75 65 00 57 65 64 00 54 68 75 00 46 72 69 00 53 61 74 00) */; internal static readonly __StaticArrayInitTypeSize=15 C3FB1115E83603E7E71244A6F2D43E22B790B5D1/* Not supported: data(04 07 0A 0E 11 14 18 1B 1E 22 25 28 2C 2F 32) */; internal static readonly __StaticArrayInitTypeSize=48 C4C38BC485A320D4B7D737DB85E705077FA38BEF/* Not supported: data(4A 61 6E 00 46 65 62 00 4D 61 72 00 41 70 72 00 4D 61 79 00 4A 75 6E 00 4A 75 6C 00 41 75 67 00 53 65 70 00 4F 63 74 00 4E 6F 76 00 44 65 63 00) */; internal static readonly __StaticArrayInitTypeSize=42 DB5930245CE35BDE5EDC35035275D8DD55E139CF/* Not supported: data(36 00 6B 00 A0 00 D5 00 0A 01 3F 01 75 01 AA 01 DF 01 14 02 49 02 7E 02 B3 02 E9 02 1E 03 53 03 88 03 BD 03 F2 03 28 04 5D 04) */; internal static readonly __StaticArrayInitTypeSize=52 DD3AEFEADB1CD615F3017763F1568179FEE640B0/* Not supported: data(00 00 00 00 1F 00 00 00 3C 00 00 00 5B 00 00 00 79 00 00 00 98 00 00 00 B6 00 00 00 D5 00 00 00 F4 00 00 00 12 01 00 00 31 01 00 00 4F 01 00 00 6E 01 00 00) */; internal static readonly __StaticArrayInitTypeSize=52 E92B39D8233061927D9ACDE54665E68E7535635A/* Not supported: data(00 00 00 00 1F 00 00 00 3B 00 00 00 5A 00 00 00 78 00 00 00 97 00 00 00 B5 00 00 00 D4 00 00 00 F3 00 00 00 11 01 00 00 30 01 00 00 4E 01 00 00 6D 01 00 00) */; internal static readonly __StaticArrayInitTypeSize=28 EE0B1C00D481FCA3559F2937C3DD3127C35B2FE3/* Not supported: data(73 75 6E 00 6D 6F 6E 00 74 75 65 00 77 65 64 00 74 68 75 00 66 72 69 00 73 61 74 00) */; } 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 Pow(float x, float y) { return (float)Math.Pow(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 static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); internal static Type ResourceType { get; } = typeof(FxResources.System.Numerics.Vectors.SR); 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 string Arg_InsufficientNumberOfElements => GetResourceString("Arg_InsufficientNumberOfElements", null); [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.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, Inherited = false)] internal sealed class IntrinsicAttribute : Attribute { } [AttributeUsage(AttributeTargets.All)] internal class __BlockReflectionAttribute : Attribute { } } 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; } } [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; } [System.Runtime.CompilerServices.Intrinsic] internal struct Vector : IEquatable>, IFormattable where T : struct { private struct VectorSizeHelper { internal Vector _placeholder; internal byte _byte; } private System.Numerics.Register register; private static readonly int s_count = InitializeCount(); private static readonly Vector s_zero = default(Vector); private static readonly Vector s_one = new Vector(GetOneValue()); private static readonly Vector s_allOnes = new Vector(GetAllBitsSetValue()); public static int Count { [System.Runtime.CompilerServices.Intrinsic] get { return s_count; } } public static Vector Zero { [System.Runtime.CompilerServices.Intrinsic] get { return s_zero; } } public static Vector One { [System.Runtime.CompilerServices.Intrinsic] get { return s_one; } } internal static Vector AllOnes => s_allOnes; public unsafe T this[int index] { [System.Runtime.CompilerServices.Intrinsic] get { if (index >= Count || index < 0) { throw new IndexOutOfRangeException(SR.Format(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(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(SR.Arg_TypeNotSupported); } num2 = 8; } return num / num2; } [System.Runtime.CompilerServices.Intrinsic] public unsafe Vector(T value) { this = default(Vector); 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; } } [System.Runtime.CompilerServices.Intrinsic] public Vector(T[] values) : this(values, 0) { } public unsafe Vector(T[] values, int index) { this = default(Vector); if (values == null) { throw new NullReferenceException(SR.Arg_NullArgumentNullRef); } if (index < 0 || values.Length - index < Count) { throw new IndexOutOfRangeException(SR.Format(SR.Arg_InsufficientNumberOfElements, Count, "values")); } 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); 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(SR.Arg_TypeNotSupported); } private Vector(ref System.Numerics.Register existingRegister) { register = existingRegister; } [System.Runtime.CompilerServices.Intrinsic] public void CopyTo(T[] destination) { CopyTo(destination, 0); } [System.Runtime.CompilerServices.Intrinsic] public unsafe void CopyTo(T[] destination, int startIndex) { if (destination == null) { throw new NullReferenceException(SR.Arg_NullArgumentNullRef); } if (startIndex < 0 || startIndex >= destination.Length) { throw new ArgumentOutOfRangeException("startIndex", SR.Format(SR.Arg_ArgumentOutOfRangeException, startIndex)); } if (destination.Length - startIndex < Count) { throw new ArgumentException(SR.Format(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)) { return false; } return Equals((Vector)obj); } [System.Runtime.CompilerServices.Intrinsic] public bool Equals(Vector 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(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(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(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 Vectoroperator +(Vector left, Vector right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarAdd(left[i], right[i]); } return new Vector(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarAdd(left[j], right[j]); } return new Vector(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(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(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(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(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(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(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(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(ptr10); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } Vector result = default(Vector); 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 Vectoroperator -(Vector left, Vector right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarSubtract(left[i], right[i]); } return new Vector(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarSubtract(left[j], right[j]); } return new Vector(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(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(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(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(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(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(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(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(ptr10); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } Vector result = default(Vector); 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 Vectoroperator *(Vector left, Vector right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarMultiply(left[i], right[i]); } return new Vector(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarMultiply(left[j], right[j]); } return new Vector(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(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(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(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(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(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(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(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(ptr10); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } Vector result = default(Vector); 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 Vectoroperator *(Vector value, T factor) { if (Vector.IsHardwareAccelerated) { return new Vector(factor) * value; } Vector result = default(Vector); 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 Vectoroperator *(T factor, Vector value) { if (Vector.IsHardwareAccelerated) { return new Vector(factor) * value; } Vector result = default(Vector); 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 Vectoroperator /(Vector left, Vector right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarDivide(left[i], right[i]); } return new Vector(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarDivide(left[j], right[j]); } return new Vector(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(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(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(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(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(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(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(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(ptr10); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } Vector result = default(Vector); 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 Vectoroperator -(Vector value) { return Zero - value; } [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vectoroperator &(Vector left, Vector right) { Vector result = default(Vector); 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.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; } [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vectoroperator |(Vector left, Vector right) { Vector result = default(Vector); 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.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; } [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vectoroperator ^(Vector left, Vector right) { Vector result = default(Vector); 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.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 Vectoroperator ~(Vector value) { return s_allOnes ^ value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Vector left, Vector right) { return left.Equals(right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Vector left, Vector right) { return !(left == right); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector(Vector value) { return new Vector(ref value.register); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector(Vector value) { return new Vector(ref value.register); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector(Vector value) { return new Vector(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector(Vector value) { return new Vector(ref value.register); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector(Vector value) { return new Vector(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector(Vector value) { return new Vector(ref value.register); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector(Vector value) { return new Vector(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector(Vector value) { return new Vector(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector(Vector value) { return new Vector(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector(Vector value) { return new Vector(ref value.register); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] internal unsafe static Vector Equals(Vector left, Vector right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(ScalarEquals(left[i], right[i]) ? ConstantHelper.GetByteWithAllBitsSet() : 0); } return new Vector(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(ScalarEquals(left[j], right[j]) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); } return new Vector(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(ScalarEquals(left[k], right[k]) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); } return new Vector(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(ScalarEquals(left[l], right[l]) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); } return new Vector(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (ScalarEquals(left[m], right[m]) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); } return new Vector(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (ScalarEquals(left[n], right[n]) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); } return new Vector(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ScalarEquals(left[num], right[num]) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); } return new Vector(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (ScalarEquals(left[num2], right[num2]) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); } return new Vector(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (ScalarEquals(left[num3], right[num3]) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); } return new Vector(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (ScalarEquals(left[num4], right[num4]) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); } return new Vector(ptr10); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } System.Numerics.Register existingRegister = default(System.Numerics.Register); if (typeof(T) == typeof(byte)) { existingRegister.byte_0 = (byte)((left.register.byte_0 == right.register.byte_0) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_1 = (byte)((left.register.byte_1 == right.register.byte_1) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_2 = (byte)((left.register.byte_2 == right.register.byte_2) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_3 = (byte)((left.register.byte_3 == right.register.byte_3) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_4 = (byte)((left.register.byte_4 == right.register.byte_4) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_5 = (byte)((left.register.byte_5 == right.register.byte_5) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_6 = (byte)((left.register.byte_6 == right.register.byte_6) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_7 = (byte)((left.register.byte_7 == right.register.byte_7) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_8 = (byte)((left.register.byte_8 == right.register.byte_8) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_9 = (byte)((left.register.byte_9 == right.register.byte_9) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_10 = (byte)((left.register.byte_10 == right.register.byte_10) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_11 = (byte)((left.register.byte_11 == right.register.byte_11) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_12 = (byte)((left.register.byte_12 == right.register.byte_12) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_13 = (byte)((left.register.byte_13 == right.register.byte_13) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_14 = (byte)((left.register.byte_14 == right.register.byte_14) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_15 = (byte)((left.register.byte_15 == right.register.byte_15) ? ConstantHelper.GetByteWithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(sbyte)) { existingRegister.sbyte_0 = (sbyte)((left.register.sbyte_0 == right.register.sbyte_0) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_1 = (sbyte)((left.register.sbyte_1 == right.register.sbyte_1) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_2 = (sbyte)((left.register.sbyte_2 == right.register.sbyte_2) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_3 = (sbyte)((left.register.sbyte_3 == right.register.sbyte_3) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_4 = (sbyte)((left.register.sbyte_4 == right.register.sbyte_4) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_5 = (sbyte)((left.register.sbyte_5 == right.register.sbyte_5) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_6 = (sbyte)((left.register.sbyte_6 == right.register.sbyte_6) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_7 = (sbyte)((left.register.sbyte_7 == right.register.sbyte_7) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_8 = (sbyte)((left.register.sbyte_8 == right.register.sbyte_8) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_9 = (sbyte)((left.register.sbyte_9 == right.register.sbyte_9) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_10 = (sbyte)((left.register.sbyte_10 == right.register.sbyte_10) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_11 = (sbyte)((left.register.sbyte_11 == right.register.sbyte_11) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_12 = (sbyte)((left.register.sbyte_12 == right.register.sbyte_12) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_13 = (sbyte)((left.register.sbyte_13 == right.register.sbyte_13) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_14 = (sbyte)((left.register.sbyte_14 == right.register.sbyte_14) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_15 = (sbyte)((left.register.sbyte_15 == right.register.sbyte_15) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(ushort)) { existingRegister.uint16_0 = (ushort)((left.register.uint16_0 == right.register.uint16_0) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_1 = (ushort)((left.register.uint16_1 == right.register.uint16_1) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_2 = (ushort)((left.register.uint16_2 == right.register.uint16_2) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_3 = (ushort)((left.register.uint16_3 == right.register.uint16_3) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_4 = (ushort)((left.register.uint16_4 == right.register.uint16_4) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_5 = (ushort)((left.register.uint16_5 == right.register.uint16_5) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_6 = (ushort)((left.register.uint16_6 == right.register.uint16_6) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_7 = (ushort)((left.register.uint16_7 == right.register.uint16_7) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(short)) { existingRegister.int16_0 = (short)((left.register.int16_0 == right.register.int16_0) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_1 = (short)((left.register.int16_1 == right.register.int16_1) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_2 = (short)((left.register.int16_2 == right.register.int16_2) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_3 = (short)((left.register.int16_3 == right.register.int16_3) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_4 = (short)((left.register.int16_4 == right.register.int16_4) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_5 = (short)((left.register.int16_5 == right.register.int16_5) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_6 = (short)((left.register.int16_6 == right.register.int16_6) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_7 = (short)((left.register.int16_7 == right.register.int16_7) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(uint)) { existingRegister.uint32_0 = ((left.register.uint32_0 == right.register.uint32_0) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); existingRegister.uint32_1 = ((left.register.uint32_1 == right.register.uint32_1) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); existingRegister.uint32_2 = ((left.register.uint32_2 == right.register.uint32_2) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); existingRegister.uint32_3 = ((left.register.uint32_3 == right.register.uint32_3) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); return new Vector(ref existingRegister); } if (typeof(T) == typeof(int)) { existingRegister.int32_0 = ((left.register.int32_0 == right.register.int32_0) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); existingRegister.int32_1 = ((left.register.int32_1 == right.register.int32_1) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); existingRegister.int32_2 = ((left.register.int32_2 == right.register.int32_2) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); existingRegister.int32_3 = ((left.register.int32_3 == right.register.int32_3) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(ulong)) { existingRegister.uint64_0 = ((left.register.uint64_0 == right.register.uint64_0) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); existingRegister.uint64_1 = ((left.register.uint64_1 == right.register.uint64_1) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(long)) { existingRegister.int64_0 = ((left.register.int64_0 == right.register.int64_0) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); existingRegister.int64_1 = ((left.register.int64_1 == right.register.int64_1) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(float)) { existingRegister.single_0 = ((left.register.single_0 == right.register.single_0) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); existingRegister.single_1 = ((left.register.single_1 == right.register.single_1) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); existingRegister.single_2 = ((left.register.single_2 == right.register.single_2) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); existingRegister.single_3 = ((left.register.single_3 == right.register.single_3) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); return new Vector(ref existingRegister); } if (typeof(T) == typeof(double)) { existingRegister.double_0 = ((left.register.double_0 == right.register.double_0) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); existingRegister.double_1 = ((left.register.double_1 == right.register.double_1) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); return new Vector(ref existingRegister); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] internal unsafe static Vector LessThan(Vector left, Vector right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(ScalarLessThan(left[i], right[i]) ? ConstantHelper.GetByteWithAllBitsSet() : 0); } return new Vector(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(ScalarLessThan(left[j], right[j]) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); } return new Vector(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(ScalarLessThan(left[k], right[k]) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); } return new Vector(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(ScalarLessThan(left[l], right[l]) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); } return new Vector(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (ScalarLessThan(left[m], right[m]) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); } return new Vector(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (ScalarLessThan(left[n], right[n]) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); } return new Vector(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ScalarLessThan(left[num], right[num]) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); } return new Vector(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (ScalarLessThan(left[num2], right[num2]) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); } return new Vector(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (ScalarLessThan(left[num3], right[num3]) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); } return new Vector(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (ScalarLessThan(left[num4], right[num4]) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); } return new Vector(ptr10); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } System.Numerics.Register existingRegister = default(System.Numerics.Register); if (typeof(T) == typeof(byte)) { existingRegister.byte_0 = (byte)((left.register.byte_0 < right.register.byte_0) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_1 = (byte)((left.register.byte_1 < right.register.byte_1) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_2 = (byte)((left.register.byte_2 < right.register.byte_2) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_3 = (byte)((left.register.byte_3 < right.register.byte_3) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_4 = (byte)((left.register.byte_4 < right.register.byte_4) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_5 = (byte)((left.register.byte_5 < right.register.byte_5) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_6 = (byte)((left.register.byte_6 < right.register.byte_6) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_7 = (byte)((left.register.byte_7 < right.register.byte_7) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_8 = (byte)((left.register.byte_8 < right.register.byte_8) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_9 = (byte)((left.register.byte_9 < right.register.byte_9) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_10 = (byte)((left.register.byte_10 < right.register.byte_10) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_11 = (byte)((left.register.byte_11 < right.register.byte_11) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_12 = (byte)((left.register.byte_12 < right.register.byte_12) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_13 = (byte)((left.register.byte_13 < right.register.byte_13) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_14 = (byte)((left.register.byte_14 < right.register.byte_14) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_15 = (byte)((left.register.byte_15 < right.register.byte_15) ? ConstantHelper.GetByteWithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(sbyte)) { existingRegister.sbyte_0 = (sbyte)((left.register.sbyte_0 < right.register.sbyte_0) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_1 = (sbyte)((left.register.sbyte_1 < right.register.sbyte_1) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_2 = (sbyte)((left.register.sbyte_2 < right.register.sbyte_2) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_3 = (sbyte)((left.register.sbyte_3 < right.register.sbyte_3) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_4 = (sbyte)((left.register.sbyte_4 < right.register.sbyte_4) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_5 = (sbyte)((left.register.sbyte_5 < right.register.sbyte_5) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_6 = (sbyte)((left.register.sbyte_6 < right.register.sbyte_6) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_7 = (sbyte)((left.register.sbyte_7 < right.register.sbyte_7) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_8 = (sbyte)((left.register.sbyte_8 < right.register.sbyte_8) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_9 = (sbyte)((left.register.sbyte_9 < right.register.sbyte_9) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_10 = (sbyte)((left.register.sbyte_10 < right.register.sbyte_10) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_11 = (sbyte)((left.register.sbyte_11 < right.register.sbyte_11) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_12 = (sbyte)((left.register.sbyte_12 < right.register.sbyte_12) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_13 = (sbyte)((left.register.sbyte_13 < right.register.sbyte_13) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_14 = (sbyte)((left.register.sbyte_14 < right.register.sbyte_14) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_15 = (sbyte)((left.register.sbyte_15 < right.register.sbyte_15) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(ushort)) { existingRegister.uint16_0 = (ushort)((left.register.uint16_0 < right.register.uint16_0) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_1 = (ushort)((left.register.uint16_1 < right.register.uint16_1) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_2 = (ushort)((left.register.uint16_2 < right.register.uint16_2) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_3 = (ushort)((left.register.uint16_3 < right.register.uint16_3) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_4 = (ushort)((left.register.uint16_4 < right.register.uint16_4) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_5 = (ushort)((left.register.uint16_5 < right.register.uint16_5) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_6 = (ushort)((left.register.uint16_6 < right.register.uint16_6) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_7 = (ushort)((left.register.uint16_7 < right.register.uint16_7) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(short)) { existingRegister.int16_0 = (short)((left.register.int16_0 < right.register.int16_0) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_1 = (short)((left.register.int16_1 < right.register.int16_1) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_2 = (short)((left.register.int16_2 < right.register.int16_2) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_3 = (short)((left.register.int16_3 < right.register.int16_3) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_4 = (short)((left.register.int16_4 < right.register.int16_4) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_5 = (short)((left.register.int16_5 < right.register.int16_5) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_6 = (short)((left.register.int16_6 < right.register.int16_6) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_7 = (short)((left.register.int16_7 < right.register.int16_7) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(uint)) { existingRegister.uint32_0 = ((left.register.uint32_0 < right.register.uint32_0) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); existingRegister.uint32_1 = ((left.register.uint32_1 < right.register.uint32_1) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); existingRegister.uint32_2 = ((left.register.uint32_2 < right.register.uint32_2) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); existingRegister.uint32_3 = ((left.register.uint32_3 < right.register.uint32_3) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); return new Vector(ref existingRegister); } if (typeof(T) == typeof(int)) { existingRegister.int32_0 = ((left.register.int32_0 < right.register.int32_0) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); existingRegister.int32_1 = ((left.register.int32_1 < right.register.int32_1) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); existingRegister.int32_2 = ((left.register.int32_2 < right.register.int32_2) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); existingRegister.int32_3 = ((left.register.int32_3 < right.register.int32_3) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(ulong)) { existingRegister.uint64_0 = ((left.register.uint64_0 < right.register.uint64_0) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); existingRegister.uint64_1 = ((left.register.uint64_1 < right.register.uint64_1) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(long)) { existingRegister.int64_0 = ((left.register.int64_0 < right.register.int64_0) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); existingRegister.int64_1 = ((left.register.int64_1 < right.register.int64_1) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(float)) { existingRegister.single_0 = ((left.register.single_0 < right.register.single_0) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); existingRegister.single_1 = ((left.register.single_1 < right.register.single_1) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); existingRegister.single_2 = ((left.register.single_2 < right.register.single_2) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); existingRegister.single_3 = ((left.register.single_3 < right.register.single_3) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); return new Vector(ref existingRegister); } if (typeof(T) == typeof(double)) { existingRegister.double_0 = ((left.register.double_0 < right.register.double_0) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); existingRegister.double_1 = ((left.register.double_1 < right.register.double_1) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); return new Vector(ref existingRegister); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] internal unsafe static Vector GreaterThan(Vector left, Vector right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(ScalarGreaterThan(left[i], right[i]) ? ConstantHelper.GetByteWithAllBitsSet() : 0); } return new Vector(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(ScalarGreaterThan(left[j], right[j]) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); } return new Vector(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(ScalarGreaterThan(left[k], right[k]) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); } return new Vector(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(ScalarGreaterThan(left[l], right[l]) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); } return new Vector(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (ScalarGreaterThan(left[m], right[m]) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); } return new Vector(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (ScalarGreaterThan(left[n], right[n]) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); } return new Vector(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ScalarGreaterThan(left[num], right[num]) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); } return new Vector(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (ScalarGreaterThan(left[num2], right[num2]) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); } return new Vector(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (ScalarGreaterThan(left[num3], right[num3]) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); } return new Vector(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (ScalarGreaterThan(left[num4], right[num4]) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); } return new Vector(ptr10); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } System.Numerics.Register existingRegister = default(System.Numerics.Register); if (typeof(T) == typeof(byte)) { existingRegister.byte_0 = (byte)((left.register.byte_0 > right.register.byte_0) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_1 = (byte)((left.register.byte_1 > right.register.byte_1) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_2 = (byte)((left.register.byte_2 > right.register.byte_2) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_3 = (byte)((left.register.byte_3 > right.register.byte_3) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_4 = (byte)((left.register.byte_4 > right.register.byte_4) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_5 = (byte)((left.register.byte_5 > right.register.byte_5) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_6 = (byte)((left.register.byte_6 > right.register.byte_6) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_7 = (byte)((left.register.byte_7 > right.register.byte_7) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_8 = (byte)((left.register.byte_8 > right.register.byte_8) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_9 = (byte)((left.register.byte_9 > right.register.byte_9) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_10 = (byte)((left.register.byte_10 > right.register.byte_10) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_11 = (byte)((left.register.byte_11 > right.register.byte_11) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_12 = (byte)((left.register.byte_12 > right.register.byte_12) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_13 = (byte)((left.register.byte_13 > right.register.byte_13) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_14 = (byte)((left.register.byte_14 > right.register.byte_14) ? ConstantHelper.GetByteWithAllBitsSet() : 0); existingRegister.byte_15 = (byte)((left.register.byte_15 > right.register.byte_15) ? ConstantHelper.GetByteWithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(sbyte)) { existingRegister.sbyte_0 = (sbyte)((left.register.sbyte_0 > right.register.sbyte_0) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_1 = (sbyte)((left.register.sbyte_1 > right.register.sbyte_1) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_2 = (sbyte)((left.register.sbyte_2 > right.register.sbyte_2) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_3 = (sbyte)((left.register.sbyte_3 > right.register.sbyte_3) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_4 = (sbyte)((left.register.sbyte_4 > right.register.sbyte_4) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_5 = (sbyte)((left.register.sbyte_5 > right.register.sbyte_5) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_6 = (sbyte)((left.register.sbyte_6 > right.register.sbyte_6) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_7 = (sbyte)((left.register.sbyte_7 > right.register.sbyte_7) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_8 = (sbyte)((left.register.sbyte_8 > right.register.sbyte_8) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_9 = (sbyte)((left.register.sbyte_9 > right.register.sbyte_9) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_10 = (sbyte)((left.register.sbyte_10 > right.register.sbyte_10) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_11 = (sbyte)((left.register.sbyte_11 > right.register.sbyte_11) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_12 = (sbyte)((left.register.sbyte_12 > right.register.sbyte_12) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_13 = (sbyte)((left.register.sbyte_13 > right.register.sbyte_13) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_14 = (sbyte)((left.register.sbyte_14 > right.register.sbyte_14) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); existingRegister.sbyte_15 = (sbyte)((left.register.sbyte_15 > right.register.sbyte_15) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(ushort)) { existingRegister.uint16_0 = (ushort)((left.register.uint16_0 > right.register.uint16_0) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_1 = (ushort)((left.register.uint16_1 > right.register.uint16_1) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_2 = (ushort)((left.register.uint16_2 > right.register.uint16_2) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_3 = (ushort)((left.register.uint16_3 > right.register.uint16_3) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_4 = (ushort)((left.register.uint16_4 > right.register.uint16_4) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_5 = (ushort)((left.register.uint16_5 > right.register.uint16_5) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_6 = (ushort)((left.register.uint16_6 > right.register.uint16_6) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); existingRegister.uint16_7 = (ushort)((left.register.uint16_7 > right.register.uint16_7) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(short)) { existingRegister.int16_0 = (short)((left.register.int16_0 > right.register.int16_0) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_1 = (short)((left.register.int16_1 > right.register.int16_1) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_2 = (short)((left.register.int16_2 > right.register.int16_2) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_3 = (short)((left.register.int16_3 > right.register.int16_3) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_4 = (short)((left.register.int16_4 > right.register.int16_4) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_5 = (short)((left.register.int16_5 > right.register.int16_5) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_6 = (short)((left.register.int16_6 > right.register.int16_6) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); existingRegister.int16_7 = (short)((left.register.int16_7 > right.register.int16_7) ? ConstantHelper.GetInt16WithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(uint)) { existingRegister.uint32_0 = ((left.register.uint32_0 > right.register.uint32_0) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); existingRegister.uint32_1 = ((left.register.uint32_1 > right.register.uint32_1) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); existingRegister.uint32_2 = ((left.register.uint32_2 > right.register.uint32_2) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); existingRegister.uint32_3 = ((left.register.uint32_3 > right.register.uint32_3) ? ConstantHelper.GetUInt32WithAllBitsSet() : 0u); return new Vector(ref existingRegister); } if (typeof(T) == typeof(int)) { existingRegister.int32_0 = ((left.register.int32_0 > right.register.int32_0) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); existingRegister.int32_1 = ((left.register.int32_1 > right.register.int32_1) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); existingRegister.int32_2 = ((left.register.int32_2 > right.register.int32_2) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); existingRegister.int32_3 = ((left.register.int32_3 > right.register.int32_3) ? ConstantHelper.GetInt32WithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(ulong)) { existingRegister.uint64_0 = ((left.register.uint64_0 > right.register.uint64_0) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); existingRegister.uint64_1 = ((left.register.uint64_1 > right.register.uint64_1) ? ConstantHelper.GetUInt64WithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(long)) { existingRegister.int64_0 = ((left.register.int64_0 > right.register.int64_0) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); existingRegister.int64_1 = ((left.register.int64_1 > right.register.int64_1) ? ConstantHelper.GetInt64WithAllBitsSet() : 0); return new Vector(ref existingRegister); } if (typeof(T) == typeof(float)) { existingRegister.single_0 = ((left.register.single_0 > right.register.single_0) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); existingRegister.single_1 = ((left.register.single_1 > right.register.single_1) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); existingRegister.single_2 = ((left.register.single_2 > right.register.single_2) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); existingRegister.single_3 = ((left.register.single_3 > right.register.single_3) ? ConstantHelper.GetSingleWithAllBitsSet() : 0f); return new Vector(ref existingRegister); } if (typeof(T) == typeof(double)) { existingRegister.double_0 = ((left.register.double_0 > right.register.double_0) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); existingRegister.double_1 = ((left.register.double_1 > right.register.double_1) ? ConstantHelper.GetDoubleWithAllBitsSet() : 0.0); return new Vector(ref existingRegister); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [System.Runtime.CompilerServices.Intrinsic] internal static Vector GreaterThanOrEqual(Vector left, Vector right) { return Equals(left, right) | GreaterThan(left, right); } [System.Runtime.CompilerServices.Intrinsic] internal static Vector LessThanOrEqual(Vector left, Vector right) { return Equals(left, right) | LessThan(left, right); } [System.Runtime.CompilerServices.Intrinsic] internal static Vector ConditionalSelect(Vector condition, Vector left, Vector right) { return (left & condition) | Vector.AndNot(right, condition); } [System.Runtime.CompilerServices.Intrinsic] internal unsafe static Vector Abs(Vector value) { if (typeof(T) == typeof(byte)) { return value; } if (typeof(T) == typeof(ushort)) { return value; } if (typeof(T) == typeof(uint)) { return value; } if (typeof(T) == typeof(ulong)) { return value; } if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(sbyte)) { sbyte* ptr = stackalloc sbyte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (sbyte)(object)Math.Abs((sbyte)(object)value[i]); } return new Vector(ptr); } if (typeof(T) == typeof(short)) { short* ptr2 = stackalloc short[Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (short)(object)Math.Abs((short)(object)value[j]); } return new Vector(ptr2); } if (typeof(T) == typeof(int)) { int* ptr3 = stackalloc int[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (int)(object)Math.Abs((int)(object)value[k]); } return new Vector(ptr3); } if (typeof(T) == typeof(long)) { long* ptr4 = stackalloc long[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (long)(object)Math.Abs((long)(object)value[l]); } return new Vector(ptr4); } if (typeof(T) == typeof(float)) { float* ptr5 = stackalloc float[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (float)(object)Math.Abs((float)(object)value[m]); } return new Vector(ptr5); } if (typeof(T) == typeof(double)) { double* ptr6 = stackalloc double[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (double)(object)Math.Abs((double)(object)value[n]); } return new Vector(ptr6); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } if (typeof(T) == typeof(sbyte)) { value.register.sbyte_0 = Math.Abs(value.register.sbyte_0); value.register.sbyte_1 = Math.Abs(value.register.sbyte_1); value.register.sbyte_2 = Math.Abs(value.register.sbyte_2); value.register.sbyte_3 = Math.Abs(value.register.sbyte_3); value.register.sbyte_4 = Math.Abs(value.register.sbyte_4); value.register.sbyte_5 = Math.Abs(value.register.sbyte_5); value.register.sbyte_6 = Math.Abs(value.register.sbyte_6); value.register.sbyte_7 = Math.Abs(value.register.sbyte_7); value.register.sbyte_8 = Math.Abs(value.register.sbyte_8); value.register.sbyte_9 = Math.Abs(value.register.sbyte_9); value.register.sbyte_10 = Math.Abs(value.register.sbyte_10); value.register.sbyte_11 = Math.Abs(value.register.sbyte_11); value.register.sbyte_12 = Math.Abs(value.register.sbyte_12); value.register.sbyte_13 = Math.Abs(value.register.sbyte_13); value.register.sbyte_14 = Math.Abs(value.register.sbyte_14); value.register.sbyte_15 = Math.Abs(value.register.sbyte_15); return value; } if (typeof(T) == typeof(short)) { value.register.int16_0 = Math.Abs(value.register.int16_0); value.register.int16_1 = Math.Abs(value.register.int16_1); value.register.int16_2 = Math.Abs(value.register.int16_2); value.register.int16_3 = Math.Abs(value.register.int16_3); value.register.int16_4 = Math.Abs(value.register.int16_4); value.register.int16_5 = Math.Abs(value.register.int16_5); value.register.int16_6 = Math.Abs(value.register.int16_6); value.register.int16_7 = Math.Abs(value.register.int16_7); return value; } if (typeof(T) == typeof(int)) { value.register.int32_0 = Math.Abs(value.register.int32_0); value.register.int32_1 = Math.Abs(value.register.int32_1); value.register.int32_2 = Math.Abs(value.register.int32_2); value.register.int32_3 = Math.Abs(value.register.int32_3); return value; } if (typeof(T) == typeof(long)) { value.register.int64_0 = Math.Abs(value.register.int64_0); value.register.int64_1 = Math.Abs(value.register.int64_1); return value; } if (typeof(T) == typeof(float)) { value.register.single_0 = Math.Abs(value.register.single_0); value.register.single_1 = Math.Abs(value.register.single_1); value.register.single_2 = Math.Abs(value.register.single_2); value.register.single_3 = Math.Abs(value.register.single_3); return value; } if (typeof(T) == typeof(double)) { value.register.double_0 = Math.Abs(value.register.double_0); value.register.double_1 = Math.Abs(value.register.double_1); return value; } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [System.Runtime.CompilerServices.Intrinsic] internal unsafe static Vector Min(Vector left, Vector right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (ScalarLessThan(left[i], right[i]) ? ((byte)(object)left[i]) : ((byte)(object)right[i])); } return new Vector(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (ScalarLessThan(left[j], right[j]) ? ((sbyte)(object)left[j]) : ((sbyte)(object)right[j])); } return new Vector(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ScalarLessThan(left[k], right[k]) ? ((ushort)(object)left[k]) : ((ushort)(object)right[k])); } return new Vector(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (ScalarLessThan(left[l], right[l]) ? ((short)(object)left[l]) : ((short)(object)right[l])); } return new Vector(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (ScalarLessThan(left[m], right[m]) ? ((uint)(object)left[m]) : ((uint)(object)right[m])); } return new Vector(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (ScalarLessThan(left[n], right[n]) ? ((int)(object)left[n]) : ((int)(object)right[n])); } return new Vector(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ScalarLessThan(left[num], right[num]) ? ((ulong)(object)left[num]) : ((ulong)(object)right[num])); } return new Vector(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (ScalarLessThan(left[num2], right[num2]) ? ((long)(object)left[num2]) : ((long)(object)right[num2])); } return new Vector(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (ScalarLessThan(left[num3], right[num3]) ? ((float)(object)left[num3]) : ((float)(object)right[num3])); } return new Vector(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (ScalarLessThan(left[num4], right[num4]) ? ((double)(object)left[num4]) : ((double)(object)right[num4])); } return new Vector(ptr10); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } Vector result = default(Vector); if (typeof(T) == typeof(byte)) { result.register.byte_0 = ((left.register.byte_0 < right.register.byte_0) ? left.register.byte_0 : right.register.byte_0); result.register.byte_1 = ((left.register.byte_1 < right.register.byte_1) ? left.register.byte_1 : right.register.byte_1); result.register.byte_2 = ((left.register.byte_2 < right.register.byte_2) ? left.register.byte_2 : right.register.byte_2); result.register.byte_3 = ((left.register.byte_3 < right.register.byte_3) ? left.register.byte_3 : right.register.byte_3); result.register.byte_4 = ((left.register.byte_4 < right.register.byte_4) ? left.register.byte_4 : right.register.byte_4); result.register.byte_5 = ((left.register.byte_5 < right.register.byte_5) ? left.register.byte_5 : right.register.byte_5); result.register.byte_6 = ((left.register.byte_6 < right.register.byte_6) ? left.register.byte_6 : right.register.byte_6); result.register.byte_7 = ((left.register.byte_7 < right.register.byte_7) ? left.register.byte_7 : right.register.byte_7); result.register.byte_8 = ((left.register.byte_8 < right.register.byte_8) ? left.register.byte_8 : right.register.byte_8); result.register.byte_9 = ((left.register.byte_9 < right.register.byte_9) ? left.register.byte_9 : right.register.byte_9); result.register.byte_10 = ((left.register.byte_10 < right.register.byte_10) ? left.register.byte_10 : right.register.byte_10); result.register.byte_11 = ((left.register.byte_11 < right.register.byte_11) ? left.register.byte_11 : right.register.byte_11); result.register.byte_12 = ((left.register.byte_12 < right.register.byte_12) ? left.register.byte_12 : right.register.byte_12); result.register.byte_13 = ((left.register.byte_13 < right.register.byte_13) ? left.register.byte_13 : right.register.byte_13); result.register.byte_14 = ((left.register.byte_14 < right.register.byte_14) ? left.register.byte_14 : right.register.byte_14); result.register.byte_15 = ((left.register.byte_15 < right.register.byte_15) ? left.register.byte_15 : right.register.byte_15); return result; } if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = ((left.register.sbyte_0 < right.register.sbyte_0) ? left.register.sbyte_0 : right.register.sbyte_0); result.register.sbyte_1 = ((left.register.sbyte_1 < right.register.sbyte_1) ? left.register.sbyte_1 : right.register.sbyte_1); result.register.sbyte_2 = ((left.register.sbyte_2 < right.register.sbyte_2) ? left.register.sbyte_2 : right.register.sbyte_2); result.register.sbyte_3 = ((left.register.sbyte_3 < right.register.sbyte_3) ? left.register.sbyte_3 : right.register.sbyte_3); result.register.sbyte_4 = ((left.register.sbyte_4 < right.register.sbyte_4) ? left.register.sbyte_4 : right.register.sbyte_4); result.register.sbyte_5 = ((left.register.sbyte_5 < right.register.sbyte_5) ? left.register.sbyte_5 : right.register.sbyte_5); result.register.sbyte_6 = ((left.register.sbyte_6 < right.register.sbyte_6) ? left.register.sbyte_6 : right.register.sbyte_6); result.register.sbyte_7 = ((left.register.sbyte_7 < right.register.sbyte_7) ? left.register.sbyte_7 : right.register.sbyte_7); result.register.sbyte_8 = ((left.register.sbyte_8 < right.register.sbyte_8) ? left.register.sbyte_8 : right.register.sbyte_8); result.register.sbyte_9 = ((left.register.sbyte_9 < right.register.sbyte_9) ? left.register.sbyte_9 : right.register.sbyte_9); result.register.sbyte_10 = ((left.register.sbyte_10 < right.register.sbyte_10) ? left.register.sbyte_10 : right.register.sbyte_10); result.register.sbyte_11 = ((left.register.sbyte_11 < right.register.sbyte_11) ? left.register.sbyte_11 : right.register.sbyte_11); result.register.sbyte_12 = ((left.register.sbyte_12 < right.register.sbyte_12) ? left.register.sbyte_12 : right.register.sbyte_12); result.register.sbyte_13 = ((left.register.sbyte_13 < right.register.sbyte_13) ? left.register.sbyte_13 : right.register.sbyte_13); result.register.sbyte_14 = ((left.register.sbyte_14 < right.register.sbyte_14) ? left.register.sbyte_14 : right.register.sbyte_14); result.register.sbyte_15 = ((left.register.sbyte_15 < right.register.sbyte_15) ? left.register.sbyte_15 : right.register.sbyte_15); return result; } if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = ((left.register.uint16_0 < right.register.uint16_0) ? left.register.uint16_0 : right.register.uint16_0); result.register.uint16_1 = ((left.register.uint16_1 < right.register.uint16_1) ? left.register.uint16_1 : right.register.uint16_1); result.register.uint16_2 = ((left.register.uint16_2 < right.register.uint16_2) ? left.register.uint16_2 : right.register.uint16_2); result.register.uint16_3 = ((left.register.uint16_3 < right.register.uint16_3) ? left.register.uint16_3 : right.register.uint16_3); result.register.uint16_4 = ((left.register.uint16_4 < right.register.uint16_4) ? left.register.uint16_4 : right.register.uint16_4); result.register.uint16_5 = ((left.register.uint16_5 < right.register.uint16_5) ? left.register.uint16_5 : right.register.uint16_5); result.register.uint16_6 = ((left.register.uint16_6 < right.register.uint16_6) ? left.register.uint16_6 : right.register.uint16_6); result.register.uint16_7 = ((left.register.uint16_7 < right.register.uint16_7) ? left.register.uint16_7 : right.register.uint16_7); return result; } if (typeof(T) == typeof(short)) { result.register.int16_0 = ((left.register.int16_0 < right.register.int16_0) ? left.register.int16_0 : right.register.int16_0); result.register.int16_1 = ((left.register.int16_1 < right.register.int16_1) ? left.register.int16_1 : right.register.int16_1); result.register.int16_2 = ((left.register.int16_2 < right.register.int16_2) ? left.register.int16_2 : right.register.int16_2); result.register.int16_3 = ((left.register.int16_3 < right.register.int16_3) ? left.register.int16_3 : right.register.int16_3); result.register.int16_4 = ((left.register.int16_4 < right.register.int16_4) ? left.register.int16_4 : right.register.int16_4); result.register.int16_5 = ((left.register.int16_5 < right.register.int16_5) ? left.register.int16_5 : right.register.int16_5); result.register.int16_6 = ((left.register.int16_6 < right.register.int16_6) ? left.register.int16_6 : right.register.int16_6); result.register.int16_7 = ((left.register.int16_7 < right.register.int16_7) ? left.register.int16_7 : right.register.int16_7); return result; } if (typeof(T) == typeof(uint)) { result.register.uint32_0 = ((left.register.uint32_0 < right.register.uint32_0) ? left.register.uint32_0 : right.register.uint32_0); result.register.uint32_1 = ((left.register.uint32_1 < right.register.uint32_1) ? left.register.uint32_1 : right.register.uint32_1); result.register.uint32_2 = ((left.register.uint32_2 < right.register.uint32_2) ? left.register.uint32_2 : right.register.uint32_2); result.register.uint32_3 = ((left.register.uint32_3 < right.register.uint32_3) ? left.register.uint32_3 : right.register.uint32_3); return result; } if (typeof(T) == typeof(int)) { result.register.int32_0 = ((left.register.int32_0 < right.register.int32_0) ? left.register.int32_0 : right.register.int32_0); result.register.int32_1 = ((left.register.int32_1 < right.register.int32_1) ? left.register.int32_1 : right.register.int32_1); result.register.int32_2 = ((left.register.int32_2 < right.register.int32_2) ? left.register.int32_2 : right.register.int32_2); result.register.int32_3 = ((left.register.int32_3 < right.register.int32_3) ? left.register.int32_3 : right.register.int32_3); return result; } if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = ((left.register.uint64_0 < right.register.uint64_0) ? left.register.uint64_0 : right.register.uint64_0); result.register.uint64_1 = ((left.register.uint64_1 < right.register.uint64_1) ? left.register.uint64_1 : right.register.uint64_1); return result; } if (typeof(T) == typeof(long)) { result.register.int64_0 = ((left.register.int64_0 < right.register.int64_0) ? left.register.int64_0 : right.register.int64_0); result.register.int64_1 = ((left.register.int64_1 < right.register.int64_1) ? left.register.int64_1 : right.register.int64_1); return result; } if (typeof(T) == typeof(float)) { result.register.single_0 = ((left.register.single_0 < right.register.single_0) ? left.register.single_0 : right.register.single_0); result.register.single_1 = ((left.register.single_1 < right.register.single_1) ? left.register.single_1 : right.register.single_1); result.register.single_2 = ((left.register.single_2 < right.register.single_2) ? left.register.single_2 : right.register.single_2); result.register.single_3 = ((left.register.single_3 < right.register.single_3) ? left.register.single_3 : right.register.single_3); return result; } if (typeof(T) == typeof(double)) { result.register.double_0 = ((left.register.double_0 < right.register.double_0) ? left.register.double_0 : right.register.double_0); result.register.double_1 = ((left.register.double_1 < right.register.double_1) ? left.register.double_1 : right.register.double_1); return result; } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [System.Runtime.CompilerServices.Intrinsic] internal unsafe static Vector Max(Vector left, Vector right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (ScalarGreaterThan(left[i], right[i]) ? ((byte)(object)left[i]) : ((byte)(object)right[i])); } return new Vector(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (ScalarGreaterThan(left[j], right[j]) ? ((sbyte)(object)left[j]) : ((sbyte)(object)right[j])); } return new Vector(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ScalarGreaterThan(left[k], right[k]) ? ((ushort)(object)left[k]) : ((ushort)(object)right[k])); } return new Vector(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (ScalarGreaterThan(left[l], right[l]) ? ((short)(object)left[l]) : ((short)(object)right[l])); } return new Vector(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (ScalarGreaterThan(left[m], right[m]) ? ((uint)(object)left[m]) : ((uint)(object)right[m])); } return new Vector(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (ScalarGreaterThan(left[n], right[n]) ? ((int)(object)left[n]) : ((int)(object)right[n])); } return new Vector(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ScalarGreaterThan(left[num], right[num]) ? ((ulong)(object)left[num]) : ((ulong)(object)right[num])); } return new Vector(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (ScalarGreaterThan(left[num2], right[num2]) ? ((long)(object)left[num2]) : ((long)(object)right[num2])); } return new Vector(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (ScalarGreaterThan(left[num3], right[num3]) ? ((float)(object)left[num3]) : ((float)(object)right[num3])); } return new Vector(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (ScalarGreaterThan(left[num4], right[num4]) ? ((double)(object)left[num4]) : ((double)(object)right[num4])); } return new Vector(ptr10); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } Vector result = default(Vector); if (typeof(T) == typeof(byte)) { result.register.byte_0 = ((left.register.byte_0 > right.register.byte_0) ? left.register.byte_0 : right.register.byte_0); result.register.byte_1 = ((left.register.byte_1 > right.register.byte_1) ? left.register.byte_1 : right.register.byte_1); result.register.byte_2 = ((left.register.byte_2 > right.register.byte_2) ? left.register.byte_2 : right.register.byte_2); result.register.byte_3 = ((left.register.byte_3 > right.register.byte_3) ? left.register.byte_3 : right.register.byte_3); result.register.byte_4 = ((left.register.byte_4 > right.register.byte_4) ? left.register.byte_4 : right.register.byte_4); result.register.byte_5 = ((left.register.byte_5 > right.register.byte_5) ? left.register.byte_5 : right.register.byte_5); result.register.byte_6 = ((left.register.byte_6 > right.register.byte_6) ? left.register.byte_6 : right.register.byte_6); result.register.byte_7 = ((left.register.byte_7 > right.register.byte_7) ? left.register.byte_7 : right.register.byte_7); result.register.byte_8 = ((left.register.byte_8 > right.register.byte_8) ? left.register.byte_8 : right.register.byte_8); result.register.byte_9 = ((left.register.byte_9 > right.register.byte_9) ? left.register.byte_9 : right.register.byte_9); result.register.byte_10 = ((left.register.byte_10 > right.register.byte_10) ? left.register.byte_10 : right.register.byte_10); result.register.byte_11 = ((left.register.byte_11 > right.register.byte_11) ? left.register.byte_11 : right.register.byte_11); result.register.byte_12 = ((left.register.byte_12 > right.register.byte_12) ? left.register.byte_12 : right.register.byte_12); result.register.byte_13 = ((left.register.byte_13 > right.register.byte_13) ? left.register.byte_13 : right.register.byte_13); result.register.byte_14 = ((left.register.byte_14 > right.register.byte_14) ? left.register.byte_14 : right.register.byte_14); result.register.byte_15 = ((left.register.byte_15 > right.register.byte_15) ? left.register.byte_15 : right.register.byte_15); return result; } if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = ((left.register.sbyte_0 > right.register.sbyte_0) ? left.register.sbyte_0 : right.register.sbyte_0); result.register.sbyte_1 = ((left.register.sbyte_1 > right.register.sbyte_1) ? left.register.sbyte_1 : right.register.sbyte_1); result.register.sbyte_2 = ((left.register.sbyte_2 > right.register.sbyte_2) ? left.register.sbyte_2 : right.register.sbyte_2); result.register.sbyte_3 = ((left.register.sbyte_3 > right.register.sbyte_3) ? left.register.sbyte_3 : right.register.sbyte_3); result.register.sbyte_4 = ((left.register.sbyte_4 > right.register.sbyte_4) ? left.register.sbyte_4 : right.register.sbyte_4); result.register.sbyte_5 = ((left.register.sbyte_5 > right.register.sbyte_5) ? left.register.sbyte_5 : right.register.sbyte_5); result.register.sbyte_6 = ((left.register.sbyte_6 > right.register.sbyte_6) ? left.register.sbyte_6 : right.register.sbyte_6); result.register.sbyte_7 = ((left.register.sbyte_7 > right.register.sbyte_7) ? left.register.sbyte_7 : right.register.sbyte_7); result.register.sbyte_8 = ((left.register.sbyte_8 > right.register.sbyte_8) ? left.register.sbyte_8 : right.register.sbyte_8); result.register.sbyte_9 = ((left.register.sbyte_9 > right.register.sbyte_9) ? left.register.sbyte_9 : right.register.sbyte_9); result.register.sbyte_10 = ((left.register.sbyte_10 > right.register.sbyte_10) ? left.register.sbyte_10 : right.register.sbyte_10); result.register.sbyte_11 = ((left.register.sbyte_11 > right.register.sbyte_11) ? left.register.sbyte_11 : right.register.sbyte_11); result.register.sbyte_12 = ((left.register.sbyte_12 > right.register.sbyte_12) ? left.register.sbyte_12 : right.register.sbyte_12); result.register.sbyte_13 = ((left.register.sbyte_13 > right.register.sbyte_13) ? left.register.sbyte_13 : right.register.sbyte_13); result.register.sbyte_14 = ((left.register.sbyte_14 > right.register.sbyte_14) ? left.register.sbyte_14 : right.register.sbyte_14); result.register.sbyte_15 = ((left.register.sbyte_15 > right.register.sbyte_15) ? left.register.sbyte_15 : right.register.sbyte_15); return result; } if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = ((left.register.uint16_0 > right.register.uint16_0) ? left.register.uint16_0 : right.register.uint16_0); result.register.uint16_1 = ((left.register.uint16_1 > right.register.uint16_1) ? left.register.uint16_1 : right.register.uint16_1); result.register.uint16_2 = ((left.register.uint16_2 > right.register.uint16_2) ? left.register.uint16_2 : right.register.uint16_2); result.register.uint16_3 = ((left.register.uint16_3 > right.register.uint16_3) ? left.register.uint16_3 : right.register.uint16_3); result.register.uint16_4 = ((left.register.uint16_4 > right.register.uint16_4) ? left.register.uint16_4 : right.register.uint16_4); result.register.uint16_5 = ((left.register.uint16_5 > right.register.uint16_5) ? left.register.uint16_5 : right.register.uint16_5); result.register.uint16_6 = ((left.register.uint16_6 > right.register.uint16_6) ? left.register.uint16_6 : right.register.uint16_6); result.register.uint16_7 = ((left.register.uint16_7 > right.register.uint16_7) ? left.register.uint16_7 : right.register.uint16_7); return result; } if (typeof(T) == typeof(short)) { result.register.int16_0 = ((left.register.int16_0 > right.register.int16_0) ? left.register.int16_0 : right.register.int16_0); result.register.int16_1 = ((left.register.int16_1 > right.register.int16_1) ? left.register.int16_1 : right.register.int16_1); result.register.int16_2 = ((left.register.int16_2 > right.register.int16_2) ? left.register.int16_2 : right.register.int16_2); result.register.int16_3 = ((left.register.int16_3 > right.register.int16_3) ? left.register.int16_3 : right.register.int16_3); result.register.int16_4 = ((left.register.int16_4 > right.register.int16_4) ? left.register.int16_4 : right.register.int16_4); result.register.int16_5 = ((left.register.int16_5 > right.register.int16_5) ? left.register.int16_5 : right.register.int16_5); result.register.int16_6 = ((left.register.int16_6 > right.register.int16_6) ? left.register.int16_6 : right.register.int16_6); result.register.int16_7 = ((left.register.int16_7 > right.register.int16_7) ? left.register.int16_7 : right.register.int16_7); return result; } if (typeof(T) == typeof(uint)) { result.register.uint32_0 = ((left.register.uint32_0 > right.register.uint32_0) ? left.register.uint32_0 : right.register.uint32_0); result.register.uint32_1 = ((left.register.uint32_1 > right.register.uint32_1) ? left.register.uint32_1 : right.register.uint32_1); result.register.uint32_2 = ((left.register.uint32_2 > right.register.uint32_2) ? left.register.uint32_2 : right.register.uint32_2); result.register.uint32_3 = ((left.register.uint32_3 > right.register.uint32_3) ? left.register.uint32_3 : right.register.uint32_3); return result; } if (typeof(T) == typeof(int)) { result.register.int32_0 = ((left.register.int32_0 > right.register.int32_0) ? left.register.int32_0 : right.register.int32_0); result.register.int32_1 = ((left.register.int32_1 > right.register.int32_1) ? left.register.int32_1 : right.register.int32_1); result.register.int32_2 = ((left.register.int32_2 > right.register.int32_2) ? left.register.int32_2 : right.register.int32_2); result.register.int32_3 = ((left.register.int32_3 > right.register.int32_3) ? left.register.int32_3 : right.register.int32_3); return result; } if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = ((left.register.uint64_0 > right.register.uint64_0) ? left.register.uint64_0 : right.register.uint64_0); result.register.uint64_1 = ((left.register.uint64_1 > right.register.uint64_1) ? left.register.uint64_1 : right.register.uint64_1); return result; } if (typeof(T) == typeof(long)) { result.register.int64_0 = ((left.register.int64_0 > right.register.int64_0) ? left.register.int64_0 : right.register.int64_0); result.register.int64_1 = ((left.register.int64_1 > right.register.int64_1) ? left.register.int64_1 : right.register.int64_1); return result; } if (typeof(T) == typeof(float)) { result.register.single_0 = ((left.register.single_0 > right.register.single_0) ? left.register.single_0 : right.register.single_0); result.register.single_1 = ((left.register.single_1 > right.register.single_1) ? left.register.single_1 : right.register.single_1); result.register.single_2 = ((left.register.single_2 > right.register.single_2) ? left.register.single_2 : right.register.single_2); result.register.single_3 = ((left.register.single_3 > right.register.single_3) ? left.register.single_3 : right.register.single_3); return result; } if (typeof(T) == typeof(double)) { result.register.double_0 = ((left.register.double_0 > right.register.double_0) ? left.register.double_0 : right.register.double_0); result.register.double_1 = ((left.register.double_1 > right.register.double_1) ? left.register.double_1 : right.register.double_1); return result; } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [System.Runtime.CompilerServices.Intrinsic] internal static T DotProduct(Vector left, Vector right) { if (Vector.IsHardwareAccelerated) { T val = default(T); for (int i = 0; i < Count; i++) { val = ScalarAdd(val, ScalarMultiply(left[i], right[i])); } return val; } if (typeof(T) == typeof(byte)) { byte b = 0; b += (byte)(left.register.byte_0 * right.register.byte_0); b += (byte)(left.register.byte_1 * right.register.byte_1); b += (byte)(left.register.byte_2 * right.register.byte_2); b += (byte)(left.register.byte_3 * right.register.byte_3); b += (byte)(left.register.byte_4 * right.register.byte_4); b += (byte)(left.register.byte_5 * right.register.byte_5); b += (byte)(left.register.byte_6 * right.register.byte_6); b += (byte)(left.register.byte_7 * right.register.byte_7); b += (byte)(left.register.byte_8 * right.register.byte_8); b += (byte)(left.register.byte_9 * right.register.byte_9); b += (byte)(left.register.byte_10 * right.register.byte_10); b += (byte)(left.register.byte_11 * right.register.byte_11); b += (byte)(left.register.byte_12 * right.register.byte_12); b += (byte)(left.register.byte_13 * right.register.byte_13); b += (byte)(left.register.byte_14 * right.register.byte_14); b += (byte)(left.register.byte_15 * right.register.byte_15); return (T)(object)b; } if (typeof(T) == typeof(sbyte)) { sbyte b2 = 0; b2 += (sbyte)(left.register.sbyte_0 * right.register.sbyte_0); b2 += (sbyte)(left.register.sbyte_1 * right.register.sbyte_1); b2 += (sbyte)(left.register.sbyte_2 * right.register.sbyte_2); b2 += (sbyte)(left.register.sbyte_3 * right.register.sbyte_3); b2 += (sbyte)(left.register.sbyte_4 * right.register.sbyte_4); b2 += (sbyte)(left.register.sbyte_5 * right.register.sbyte_5); b2 += (sbyte)(left.register.sbyte_6 * right.register.sbyte_6); b2 += (sbyte)(left.register.sbyte_7 * right.register.sbyte_7); b2 += (sbyte)(left.register.sbyte_8 * right.register.sbyte_8); b2 += (sbyte)(left.register.sbyte_9 * right.register.sbyte_9); b2 += (sbyte)(left.register.sbyte_10 * right.register.sbyte_10); b2 += (sbyte)(left.register.sbyte_11 * right.register.sbyte_11); b2 += (sbyte)(left.register.sbyte_12 * right.register.sbyte_12); b2 += (sbyte)(left.register.sbyte_13 * right.register.sbyte_13); b2 += (sbyte)(left.register.sbyte_14 * right.register.sbyte_14); b2 += (sbyte)(left.register.sbyte_15 * right.register.sbyte_15); return (T)(object)b2; } if (typeof(T) == typeof(ushort)) { ushort num = 0; num += (ushort)(left.register.uint16_0 * right.register.uint16_0); num += (ushort)(left.register.uint16_1 * right.register.uint16_1); num += (ushort)(left.register.uint16_2 * right.register.uint16_2); num += (ushort)(left.register.uint16_3 * right.register.uint16_3); num += (ushort)(left.register.uint16_4 * right.register.uint16_4); num += (ushort)(left.register.uint16_5 * right.register.uint16_5); num += (ushort)(left.register.uint16_6 * right.register.uint16_6); num += (ushort)(left.register.uint16_7 * right.register.uint16_7); return (T)(object)num; } if (typeof(T) == typeof(short)) { short num2 = 0; num2 += (short)(left.register.int16_0 * right.register.int16_0); num2 += (short)(left.register.int16_1 * right.register.int16_1); num2 += (short)(left.register.int16_2 * right.register.int16_2); num2 += (short)(left.register.int16_3 * right.register.int16_3); num2 += (short)(left.register.int16_4 * right.register.int16_4); num2 += (short)(left.register.int16_5 * right.register.int16_5); num2 += (short)(left.register.int16_6 * right.register.int16_6); num2 += (short)(left.register.int16_7 * right.register.int16_7); return (T)(object)num2; } if (typeof(T) == typeof(uint)) { uint num3 = 0u; num3 += left.register.uint32_0 * right.register.uint32_0; num3 += left.register.uint32_1 * right.register.uint32_1; num3 += left.register.uint32_2 * right.register.uint32_2; num3 += left.register.uint32_3 * right.register.uint32_3; return (T)(object)num3; } if (typeof(T) == typeof(int)) { int num4 = 0; num4 += left.register.int32_0 * right.register.int32_0; num4 += left.register.int32_1 * right.register.int32_1; num4 += left.register.int32_2 * right.register.int32_2; num4 += left.register.int32_3 * right.register.int32_3; return (T)(object)num4; } if (typeof(T) == typeof(ulong)) { ulong num5 = 0uL; num5 += left.register.uint64_0 * right.register.uint64_0; num5 += left.register.uint64_1 * right.register.uint64_1; return (T)(object)num5; } if (typeof(T) == typeof(long)) { long num6 = 0L; num6 += left.register.int64_0 * right.register.int64_0; num6 += left.register.int64_1 * right.register.int64_1; return (T)(object)num6; } if (typeof(T) == typeof(float)) { float num7 = 0f; num7 += left.register.single_0 * right.register.single_0; num7 += left.register.single_1 * right.register.single_1; num7 += left.register.single_2 * right.register.single_2; num7 += left.register.single_3 * right.register.single_3; return (T)(object)num7; } if (typeof(T) == typeof(double)) { double num8 = 0.0; num8 += left.register.double_0 * right.register.double_0; num8 += left.register.double_1 * right.register.double_1; return (T)(object)num8; } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [System.Runtime.CompilerServices.Intrinsic] internal unsafe static Vector SquareRoot(Vector value) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)Math.Sqrt((int)(byte)(object)value[i]); } return new Vector(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)Math.Sqrt((sbyte)(object)value[j]); } return new Vector(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)Math.Sqrt((int)(ushort)(object)value[k]); } return new Vector(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)Math.Sqrt((short)(object)value[l]); } return new Vector(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)Math.Sqrt((uint)(object)value[m]); } return new Vector(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)Math.Sqrt((int)(object)value[n]); } return new Vector(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)Math.Sqrt((ulong)(object)value[num]); } return new Vector(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)Math.Sqrt((long)(object)value[num2]); } return new Vector(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)Math.Sqrt((float)(object)value[num3]); } return new Vector(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = Math.Sqrt((double)(object)value[num4]); } return new Vector(ptr10); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } if (typeof(T) == typeof(byte)) { value.register.byte_0 = (byte)Math.Sqrt((int)value.register.byte_0); value.register.byte_1 = (byte)Math.Sqrt((int)value.register.byte_1); value.register.byte_2 = (byte)Math.Sqrt((int)value.register.byte_2); value.register.byte_3 = (byte)Math.Sqrt((int)value.register.byte_3); value.register.byte_4 = (byte)Math.Sqrt((int)value.register.byte_4); value.register.byte_5 = (byte)Math.Sqrt((int)value.register.byte_5); value.register.byte_6 = (byte)Math.Sqrt((int)value.register.byte_6); value.register.byte_7 = (byte)Math.Sqrt((int)value.register.byte_7); value.register.byte_8 = (byte)Math.Sqrt((int)value.register.byte_8); value.register.byte_9 = (byte)Math.Sqrt((int)value.register.byte_9); value.register.byte_10 = (byte)Math.Sqrt((int)value.register.byte_10); value.register.byte_11 = (byte)Math.Sqrt((int)value.register.byte_11); value.register.byte_12 = (byte)Math.Sqrt((int)value.register.byte_12); value.register.byte_13 = (byte)Math.Sqrt((int)value.register.byte_13); value.register.byte_14 = (byte)Math.Sqrt((int)value.register.byte_14); value.register.byte_15 = (byte)Math.Sqrt((int)value.register.byte_15); return value; } if (typeof(T) == typeof(sbyte)) { value.register.sbyte_0 = (sbyte)Math.Sqrt(value.register.sbyte_0); value.register.sbyte_1 = (sbyte)Math.Sqrt(value.register.sbyte_1); value.register.sbyte_2 = (sbyte)Math.Sqrt(value.register.sbyte_2); value.register.sbyte_3 = (sbyte)Math.Sqrt(value.register.sbyte_3); value.register.sbyte_4 = (sbyte)Math.Sqrt(value.register.sbyte_4); value.register.sbyte_5 = (sbyte)Math.Sqrt(value.register.sbyte_5); value.register.sbyte_6 = (sbyte)Math.Sqrt(value.register.sbyte_6); value.register.sbyte_7 = (sbyte)Math.Sqrt(value.register.sbyte_7); value.register.sbyte_8 = (sbyte)Math.Sqrt(value.register.sbyte_8); value.register.sbyte_9 = (sbyte)Math.Sqrt(value.register.sbyte_9); value.register.sbyte_10 = (sbyte)Math.Sqrt(value.register.sbyte_10); value.register.sbyte_11 = (sbyte)Math.Sqrt(value.register.sbyte_11); value.register.sbyte_12 = (sbyte)Math.Sqrt(value.register.sbyte_12); value.register.sbyte_13 = (sbyte)Math.Sqrt(value.register.sbyte_13); value.register.sbyte_14 = (sbyte)Math.Sqrt(value.register.sbyte_14); value.register.sbyte_15 = (sbyte)Math.Sqrt(value.register.sbyte_15); return value; } if (typeof(T) == typeof(ushort)) { value.register.uint16_0 = (ushort)Math.Sqrt((int)value.register.uint16_0); value.register.uint16_1 = (ushort)Math.Sqrt((int)value.register.uint16_1); value.register.uint16_2 = (ushort)Math.Sqrt((int)value.register.uint16_2); value.register.uint16_3 = (ushort)Math.Sqrt((int)value.register.uint16_3); value.register.uint16_4 = (ushort)Math.Sqrt((int)value.register.uint16_4); value.register.uint16_5 = (ushort)Math.Sqrt((int)value.register.uint16_5); value.register.uint16_6 = (ushort)Math.Sqrt((int)value.register.uint16_6); value.register.uint16_7 = (ushort)Math.Sqrt((int)value.register.uint16_7); return value; } if (typeof(T) == typeof(short)) { value.register.int16_0 = (short)Math.Sqrt(value.register.int16_0); value.register.int16_1 = (short)Math.Sqrt(value.register.int16_1); value.register.int16_2 = (short)Math.Sqrt(value.register.int16_2); value.register.int16_3 = (short)Math.Sqrt(value.register.int16_3); value.register.int16_4 = (short)Math.Sqrt(value.register.int16_4); value.register.int16_5 = (short)Math.Sqrt(value.register.int16_5); value.register.int16_6 = (short)Math.Sqrt(value.register.int16_6); value.register.int16_7 = (short)Math.Sqrt(value.register.int16_7); return value; } if (typeof(T) == typeof(uint)) { value.register.uint32_0 = (uint)Math.Sqrt(value.register.uint32_0); value.register.uint32_1 = (uint)Math.Sqrt(value.register.uint32_1); value.register.uint32_2 = (uint)Math.Sqrt(value.register.uint32_2); value.register.uint32_3 = (uint)Math.Sqrt(value.register.uint32_3); return value; } if (typeof(T) == typeof(int)) { value.register.int32_0 = (int)Math.Sqrt(value.register.int32_0); value.register.int32_1 = (int)Math.Sqrt(value.register.int32_1); value.register.int32_2 = (int)Math.Sqrt(value.register.int32_2); value.register.int32_3 = (int)Math.Sqrt(value.register.int32_3); return value; } if (typeof(T) == typeof(ulong)) { value.register.uint64_0 = (ulong)Math.Sqrt(value.register.uint64_0); value.register.uint64_1 = (ulong)Math.Sqrt(value.register.uint64_1); return value; } if (typeof(T) == typeof(long)) { value.register.int64_0 = (long)Math.Sqrt(value.register.int64_0); value.register.int64_1 = (long)Math.Sqrt(value.register.int64_1); return value; } if (typeof(T) == typeof(float)) { value.register.single_0 = (float)Math.Sqrt(value.register.single_0); value.register.single_1 = (float)Math.Sqrt(value.register.single_1); value.register.single_2 = (float)Math.Sqrt(value.register.single_2); value.register.single_3 = (float)Math.Sqrt(value.register.single_3); return value; } if (typeof(T) == typeof(double)) { value.register.double_0 = Math.Sqrt(value.register.double_0); value.register.double_1 = Math.Sqrt(value.register.double_1); return value; } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool ScalarEquals(T left, T right) { if (typeof(T) == typeof(byte)) { return (byte)(object)left == (byte)(object)right; } if (typeof(T) == typeof(sbyte)) { return (sbyte)(object)left == (sbyte)(object)right; } if (typeof(T) == typeof(ushort)) { return (ushort)(object)left == (ushort)(object)right; } if (typeof(T) == typeof(short)) { return (short)(object)left == (short)(object)right; } if (typeof(T) == typeof(uint)) { return (uint)(object)left == (uint)(object)right; } if (typeof(T) == typeof(int)) { return (int)(object)left == (int)(object)right; } if (typeof(T) == typeof(ulong)) { return (ulong)(object)left == (ulong)(object)right; } if (typeof(T) == typeof(long)) { return (long)(object)left == (long)(object)right; } if (typeof(T) == typeof(float)) { return (float)(object)left == (float)(object)right; } if (typeof(T) == typeof(double)) { return (double)(object)left == (double)(object)right; } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool ScalarLessThan(T left, T right) { if (typeof(T) == typeof(byte)) { return (byte)(object)left < (byte)(object)right; } if (typeof(T) == typeof(sbyte)) { return (sbyte)(object)left < (sbyte)(object)right; } if (typeof(T) == typeof(ushort)) { return (ushort)(object)left < (ushort)(object)right; } if (typeof(T) == typeof(short)) { return (short)(object)left < (short)(object)right; } if (typeof(T) == typeof(uint)) { return (uint)(object)left < (uint)(object)right; } if (typeof(T) == typeof(int)) { return (int)(object)left < (int)(object)right; } if (typeof(T) == typeof(ulong)) { return (ulong)(object)left < (ulong)(object)right; } if (typeof(T) == typeof(long)) { return (long)(object)left < (long)(object)right; } if (typeof(T) == typeof(float)) { return (float)(object)left < (float)(object)right; } if (typeof(T) == typeof(double)) { return (double)(object)left < (double)(object)right; } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool ScalarGreaterThan(T left, T right) { if (typeof(T) == typeof(byte)) { return (byte)(object)left > (byte)(object)right; } if (typeof(T) == typeof(sbyte)) { return (sbyte)(object)left > (sbyte)(object)right; } if (typeof(T) == typeof(ushort)) { return (ushort)(object)left > (ushort)(object)right; } if (typeof(T) == typeof(short)) { return (short)(object)left > (short)(object)right; } if (typeof(T) == typeof(uint)) { return (uint)(object)left > (uint)(object)right; } if (typeof(T) == typeof(int)) { return (int)(object)left > (int)(object)right; } if (typeof(T) == typeof(ulong)) { return (ulong)(object)left > (ulong)(object)right; } if (typeof(T) == typeof(long)) { return (long)(object)left > (long)(object)right; } if (typeof(T) == typeof(float)) { return (float)(object)left > (float)(object)right; } if (typeof(T) == typeof(double)) { return (double)(object)left > (double)(object)right; } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T ScalarAdd(T left, T right) { if (typeof(T) == typeof(byte)) { return (T)(object)(byte)((byte)(object)left + (byte)(object)right); } if (typeof(T) == typeof(sbyte)) { return (T)(object)(sbyte)((sbyte)(object)left + (sbyte)(object)right); } if (typeof(T) == typeof(ushort)) { return (T)(object)(ushort)((ushort)(object)left + (ushort)(object)right); } if (typeof(T) == typeof(short)) { return (T)(object)(short)((short)(object)left + (short)(object)right); } if (typeof(T) == typeof(uint)) { return (T)(object)((uint)(object)left + (uint)(object)right); } if (typeof(T) == typeof(int)) { return (T)(object)((int)(object)left + (int)(object)right); } if (typeof(T) == typeof(ulong)) { return (T)(object)((ulong)(object)left + (ulong)(object)right); } if (typeof(T) == typeof(long)) { return (T)(object)((long)(object)left + (long)(object)right); } if (typeof(T) == typeof(float)) { return (T)(object)((float)(object)left + (float)(object)right); } if (typeof(T) == typeof(double)) { return (T)(object)((double)(object)left + (double)(object)right); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T ScalarSubtract(T left, T right) { if (typeof(T) == typeof(byte)) { return (T)(object)(byte)((byte)(object)left - (byte)(object)right); } if (typeof(T) == typeof(sbyte)) { return (T)(object)(sbyte)((sbyte)(object)left - (sbyte)(object)right); } if (typeof(T) == typeof(ushort)) { return (T)(object)(ushort)((ushort)(object)left - (ushort)(object)right); } if (typeof(T) == typeof(short)) { return (T)(object)(short)((short)(object)left - (short)(object)right); } if (typeof(T) == typeof(uint)) { return (T)(object)((uint)(object)left - (uint)(object)right); } if (typeof(T) == typeof(int)) { return (T)(object)((int)(object)left - (int)(object)right); } if (typeof(T) == typeof(ulong)) { return (T)(object)((ulong)(object)left - (ulong)(object)right); } if (typeof(T) == typeof(long)) { return (T)(object)((long)(object)left - (long)(object)right); } if (typeof(T) == typeof(float)) { return (T)(object)((float)(object)left - (float)(object)right); } if (typeof(T) == typeof(double)) { return (T)(object)((double)(object)left - (double)(object)right); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T ScalarMultiply(T left, T right) { if (typeof(T) == typeof(byte)) { return (T)(object)(byte)((byte)(object)left * (byte)(object)right); } if (typeof(T) == typeof(sbyte)) { return (T)(object)(sbyte)((sbyte)(object)left * (sbyte)(object)right); } if (typeof(T) == typeof(ushort)) { return (T)(object)(ushort)((ushort)(object)left * (ushort)(object)right); } if (typeof(T) == typeof(short)) { return (T)(object)(short)((short)(object)left * (short)(object)right); } if (typeof(T) == typeof(uint)) { return (T)(object)((uint)(object)left * (uint)(object)right); } if (typeof(T) == typeof(int)) { return (T)(object)((int)(object)left * (int)(object)right); } if (typeof(T) == typeof(ulong)) { return (T)(object)((ulong)(object)left * (ulong)(object)right); } if (typeof(T) == typeof(long)) { return (T)(object)((long)(object)left * (long)(object)right); } if (typeof(T) == typeof(float)) { return (T)(object)((float)(object)left * (float)(object)right); } if (typeof(T) == typeof(double)) { return (T)(object)((double)(object)left * (double)(object)right); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T ScalarDivide(T left, T right) { if (typeof(T) == typeof(byte)) { return (T)(object)(byte)((byte)(object)left / (byte)(object)right); } if (typeof(T) == typeof(sbyte)) { return (T)(object)(sbyte)((sbyte)(object)left / (sbyte)(object)right); } if (typeof(T) == typeof(ushort)) { return (T)(object)(ushort)((ushort)(object)left / (ushort)(object)right); } if (typeof(T) == typeof(short)) { return (T)(object)(short)((short)(object)left / (short)(object)right); } if (typeof(T) == typeof(uint)) { return (T)(object)((uint)(object)left / (uint)(object)right); } if (typeof(T) == typeof(int)) { return (T)(object)((int)(object)left / (int)(object)right); } if (typeof(T) == typeof(ulong)) { return (T)(object)((ulong)(object)left / (ulong)(object)right); } if (typeof(T) == typeof(long)) { return (T)(object)((long)(object)left / (long)(object)right); } if (typeof(T) == typeof(float)) { return (T)(object)((float)(object)left / (float)(object)right); } if (typeof(T) == typeof(double)) { return (T)(object)((double)(object)left / (double)(object)right); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T GetOneValue() { if (typeof(T) == typeof(byte)) { byte b = 1; return (T)(object)b; } if (typeof(T) == typeof(sbyte)) { sbyte b2 = 1; return (T)(object)b2; } if (typeof(T) == typeof(ushort)) { ushort num = 1; return (T)(object)num; } if (typeof(T) == typeof(short)) { short num2 = 1; return (T)(object)num2; } if (typeof(T) == typeof(uint)) { uint num3 = 1u; return (T)(object)num3; } if (typeof(T) == typeof(int)) { int num4 = 1; return (T)(object)num4; } if (typeof(T) == typeof(ulong)) { ulong num5 = 1uL; return (T)(object)num5; } if (typeof(T) == typeof(long)) { long num6 = 1L; return (T)(object)num6; } if (typeof(T) == typeof(float)) { float num7 = 1f; return (T)(object)num7; } if (typeof(T) == typeof(double)) { double num8 = 1.0; return (T)(object)num8; } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T GetAllBitsSetValue() { if (typeof(T) == typeof(byte)) { return (T)(object)ConstantHelper.GetByteWithAllBitsSet(); } if (typeof(T) == typeof(sbyte)) { return (T)(object)ConstantHelper.GetSByteWithAllBitsSet(); } if (typeof(T) == typeof(ushort)) { return (T)(object)ConstantHelper.GetUInt16WithAllBitsSet(); } if (typeof(T) == typeof(short)) { return (T)(object)ConstantHelper.GetInt16WithAllBitsSet(); } if (typeof(T) == typeof(uint)) { return (T)(object)ConstantHelper.GetUInt32WithAllBitsSet(); } if (typeof(T) == typeof(int)) { return (T)(object)ConstantHelper.GetInt32WithAllBitsSet(); } if (typeof(T) == typeof(ulong)) { return (T)(object)ConstantHelper.GetUInt64WithAllBitsSet(); } if (typeof(T) == typeof(long)) { return (T)(object)ConstantHelper.GetInt64WithAllBitsSet(); } if (typeof(T) == typeof(float)) { return (T)(object)ConstantHelper.GetSingleWithAllBitsSet(); } if (typeof(T) == typeof(double)) { return (T)(object)ConstantHelper.GetDoubleWithAllBitsSet(); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } } [System.Runtime.CompilerServices.Intrinsic] internal static class Vector { public static bool IsHardwareAccelerated { [System.Runtime.CompilerServices.Intrinsic] get { return false; } } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public unsafe static void Widen(Vector source, out Vector low, out Vector high) { int count = Vector.Count; ushort* ptr = stackalloc ushort[count / 2]; for (int i = 0; i < count / 2; i++) { ptr[i] = source[i]; } ushort* ptr2 = stackalloc ushort[count / 2]; for (int j = 0; j < count / 2; j++) { ptr2[j] = source[j + count / 2]; } low = new Vector(ptr); high = new Vector(ptr2); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public unsafe static void Widen(Vector source, out Vector low, out Vector high) { int count = Vector.Count; uint* ptr = stackalloc uint[count / 2]; for (int i = 0; i < count / 2; i++) { ptr[i] = source[i]; } uint* ptr2 = stackalloc uint[count / 2]; for (int j = 0; j < count / 2; j++) { ptr2[j] = source[j + count / 2]; } low = new Vector(ptr); high = new Vector(ptr2); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public unsafe static void Widen(Vector source, out Vector low, out Vector high) { int count = Vector.Count; ulong* ptr = stackalloc ulong[count / 2]; for (int i = 0; i < count / 2; i++) { ptr[i] = source[i]; } ulong* ptr2 = stackalloc ulong[count / 2]; for (int j = 0; j < count / 2; j++) { ptr2[j] = source[j + count / 2]; } low = new Vector(ptr); high = new Vector(ptr2); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public unsafe static void Widen(Vector source, out Vector low, out Vector high) { int count = Vector.Count; short* ptr = stackalloc short[count / 2]; for (int i = 0; i < count / 2; i++) { ptr[i] = source[i]; } short* ptr2 = stackalloc short[count / 2]; for (int j = 0; j < count / 2; j++) { ptr2[j] = source[j + count / 2]; } low = new Vector(ptr); high = new Vector(ptr2); } [System.Runtime.CompilerServices.Intrinsic] public unsafe static void Widen(Vector source, out Vector low, out Vector high) { int count = Vector.Count; int* ptr = stackalloc int[count / 2]; for (int i = 0; i < count / 2; i++) { ptr[i] = source[i]; } int* ptr2 = stackalloc int[count / 2]; for (int j = 0; j < count / 2; j++) { ptr2[j] = source[j + count / 2]; } low = new Vector(ptr); high = new Vector(ptr2); } [System.Runtime.CompilerServices.Intrinsic] public unsafe static void Widen(Vector source, out Vector low, out Vector high) { int count = Vector.Count; long* ptr = stackalloc long[count / 2]; for (int i = 0; i < count / 2; i++) { ptr[i] = source[i]; } long* ptr2 = stackalloc long[count / 2]; for (int j = 0; j < count / 2; j++) { ptr2[j] = source[j + count / 2]; } low = new Vector(ptr); high = new Vector(ptr2); } [System.Runtime.CompilerServices.Intrinsic] public unsafe static void Widen(Vector source, out Vector low, out Vector high) { int count = Vector.Count; double* ptr = stackalloc double[count / 2]; for (int i = 0; i < count / 2; i++) { ptr[i] = source[i]; } double* ptr2 = stackalloc double[count / 2]; for (int j = 0; j < count / 2; j++) { ptr2[j] = source[j + count / 2]; } low = new Vector(ptr); high = new Vector(ptr2); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector Narrow(Vector low, Vector high) { int count = Vector.Count; byte* ptr = stackalloc byte[(int)(uint)count]; for (int i = 0; i < count / 2; i++) { ptr[i] = (byte)low[i]; } for (int j = 0; j < count / 2; j++) { ptr[j + count / 2] = (byte)high[j]; } return new Vector(ptr); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector Narrow(Vector low, Vector high) { int count = Vector.Count; ushort* ptr = stackalloc ushort[count]; for (int i = 0; i < count / 2; i++) { ptr[i] = (ushort)low[i]; } for (int j = 0; j < count / 2; j++) { ptr[j + count / 2] = (ushort)high[j]; } return new Vector(ptr); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector Narrow(Vector low, Vector high) { int count = Vector.Count; uint* ptr = stackalloc uint[count]; for (int i = 0; i < count / 2; i++) { ptr[i] = (uint)low[i]; } for (int j = 0; j < count / 2; j++) { ptr[j + count / 2] = (uint)high[j]; } return new Vector(ptr); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector Narrow(Vector low, Vector high) { int count = Vector.Count; sbyte* ptr = stackalloc sbyte[(int)(uint)count]; for (int i = 0; i < count / 2; i++) { ptr[i] = (sbyte)low[i]; } for (int j = 0; j < count / 2; j++) { ptr[j + count / 2] = (sbyte)high[j]; } return new Vector(ptr); } [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector Narrow(Vector low, Vector high) { int count = Vector.Count; short* ptr = stackalloc short[count]; for (int i = 0; i < count / 2; i++) { ptr[i] = (short)low[i]; } for (int j = 0; j < count / 2; j++) { ptr[j + count / 2] = (short)high[j]; } return new Vector(ptr); } [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector Narrow(Vector low, Vector high) { int count = Vector.Count; int* ptr = stackalloc int[count]; for (int i = 0; i < count / 2; i++) { ptr[i] = (int)low[i]; } for (int j = 0; j < count / 2; j++) { ptr[j + count / 2] = (int)high[j]; } return new Vector(ptr); } [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector Narrow(Vector low, Vector high) { int count = Vector.Count; float* ptr = stackalloc float[count]; for (int i = 0; i < count / 2; i++) { ptr[i] = (float)low[i]; } for (int j = 0; j < count / 2; j++) { ptr[j + count / 2] = (float)high[j]; } return new Vector(ptr); } [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector ConvertToSingle(Vector value) { int count = Vector.Count; float* ptr = stackalloc float[count]; for (int i = 0; i < count; i++) { ptr[i] = value[i]; } return new Vector(ptr); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector ConvertToSingle(Vector value) { int count = Vector.Count; float* ptr = stackalloc float[count]; for (int i = 0; i < count; i++) { ptr[i] = value[i]; } return new Vector(ptr); } [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector ConvertToDouble(Vector value) { int count = Vector.Count; double* ptr = stackalloc double[count]; for (int i = 0; i < count; i++) { ptr[i] = value[i]; } return new Vector(ptr); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector ConvertToDouble(Vector value) { int count = Vector.Count; double* ptr = stackalloc double[count]; for (int i = 0; i < count; i++) { ptr[i] = value[i]; } return new Vector(ptr); } [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector ConvertToInt32(Vector value) { int count = Vector.Count; int* ptr = stackalloc int[count]; for (int i = 0; i < count; i++) { ptr[i] = (int)value[i]; } return new Vector(ptr); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector ConvertToUInt32(Vector value) { int count = Vector.Count; uint* ptr = stackalloc uint[count]; for (int i = 0; i < count; i++) { ptr[i] = (uint)value[i]; } return new Vector(ptr); } [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector ConvertToInt64(Vector value) { int count = Vector.Count; long* ptr = stackalloc long[count]; for (int i = 0; i < count; i++) { ptr[i] = (long)value[i]; } return new Vector(ptr); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector ConvertToUInt64(Vector value) { int count = Vector.Count; ulong* ptr = stackalloc ulong[count]; for (int i = 0; i < count; i++) { ptr[i] = (ulong)value[i]; } return new Vector(ptr); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector ConditionalSelect(Vector condition, Vector left, Vector right) { return Vector.ConditionalSelect((Vector)condition, left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector ConditionalSelect(Vector condition, Vector left, Vector right) { return Vector.ConditionalSelect((Vector)condition, left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector ConditionalSelect(Vector condition, Vector left, Vector right) where T : struct { return Vector.ConditionalSelect(condition, left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Equals(Vector left, Vector right) where T : struct { return Vector.Equals(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Equals(Vector left, Vector right) { return (Vector)Vector.Equals(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Equals(Vector left, Vector right) { return Vector.Equals(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Equals(Vector left, Vector right) { return (Vector)Vector.Equals(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Equals(Vector left, Vector right) { return Vector.Equals(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EqualsAll(Vector left, Vector right) where T : struct { return left == right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EqualsAny(Vector left, Vector right) where T : struct { return !Vector.Equals(left, right).Equals(Vector.Zero); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector LessThan(Vector left, Vector right) where T : struct { return Vector.LessThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector LessThan(Vector left, Vector right) { return (Vector)Vector.LessThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector LessThan(Vector left, Vector right) { return Vector.LessThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector LessThan(Vector left, Vector right) { return (Vector)Vector.LessThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector LessThan(Vector left, Vector right) { return Vector.LessThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool LessThanAll(Vector left, Vector right) where T : struct { return ((Vector)Vector.LessThan(left, right)).Equals(Vector.AllOnes); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool LessThanAny(Vector left, Vector right) where T : struct { return !((Vector)Vector.LessThan(left, right)).Equals(Vector.Zero); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector LessThanOrEqual(Vector left, Vector right) where T : struct { return Vector.LessThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector LessThanOrEqual(Vector left, Vector right) { return (Vector)Vector.LessThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector LessThanOrEqual(Vector left, Vector right) { return Vector.LessThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector LessThanOrEqual(Vector left, Vector right) { return Vector.LessThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector LessThanOrEqual(Vector left, Vector right) { return (Vector)Vector.LessThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool LessThanOrEqualAll(Vector left, Vector right) where T : struct { return ((Vector)Vector.LessThanOrEqual(left, right)).Equals(Vector.AllOnes); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool LessThanOrEqualAny(Vector left, Vector right) where T : struct { return !((Vector)Vector.LessThanOrEqual(left, right)).Equals(Vector.Zero); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector GreaterThan(Vector left, Vector right) where T : struct { return Vector.GreaterThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector GreaterThan(Vector left, Vector right) { return (Vector)Vector.GreaterThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector GreaterThan(Vector left, Vector right) { return Vector.GreaterThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector GreaterThan(Vector left, Vector right) { return (Vector)Vector.GreaterThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector GreaterThan(Vector left, Vector right) { return Vector.GreaterThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool GreaterThanAll(Vector left, Vector right) where T : struct { return ((Vector)Vector.GreaterThan(left, right)).Equals(Vector.AllOnes); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool GreaterThanAny(Vector left, Vector right) where T : struct { return !((Vector)Vector.GreaterThan(left, right)).Equals(Vector.Zero); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector GreaterThanOrEqual(Vector left, Vector right) where T : struct { return Vector.GreaterThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector GreaterThanOrEqual(Vector left, Vector right) { return (Vector)Vector.GreaterThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector GreaterThanOrEqual(Vector left, Vector right) { return Vector.GreaterThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector GreaterThanOrEqual(Vector left, Vector right) { return Vector.GreaterThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector GreaterThanOrEqual(Vector left, Vector right) { return (Vector)Vector.GreaterThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool GreaterThanOrEqualAll(Vector left, Vector right) where T : struct { return ((Vector)Vector.GreaterThanOrEqual(left, right)).Equals(Vector.AllOnes); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool GreaterThanOrEqualAny(Vector left, Vector right) where T : struct { return !((Vector)Vector.GreaterThanOrEqual(left, right)).Equals(Vector.Zero); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Abs(Vector value) where T : struct { return Vector.Abs(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Min(Vector left, Vector right) where T : struct { return Vector.Min(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Max(Vector left, Vector right) where T : struct { return Vector.Max(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T Dot(Vector left, Vector right) where T : struct { return Vector.DotProduct(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector SquareRoot(Vector value) where T : struct { return Vector.SquareRoot(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Add(Vector left, Vector right) where T : struct { return left + right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Subtract(Vector left, Vector right) where T : struct { return left - right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Multiply(Vector left, Vector right) where T : struct { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Multiply(Vector left, T right) where T : struct { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Multiply(T left, Vector right) where T : struct { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Divide(Vector left, Vector right) where T : struct { return left / right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Negate(Vector value) where T : struct { return -value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector BitwiseAnd(Vector left, Vector right) where T : struct { return left & right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector BitwiseOr(Vector left, Vector right) where T : struct { return left | right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector OnesComplement(Vector value) where T : struct { return ~value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Xor(Vector left, Vector right) where T : struct { return left ^ right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector AndNot(Vector left, Vector right) where T : struct { return left & ~right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector AsVectorByte(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector AsVectorSByte(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector AsVectorUInt16(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector AsVectorInt16(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector AsVectorUInt32(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector AsVectorInt32(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector AsVectorUInt64(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector AsVectorInt64(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector AsVectorSingle(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector AsVectorDouble(Vector value) where T : struct { return (Vector)value; } } internal struct Matrix3x2 : IEquatable { public float M11; public float M12; public float M21; public float M22; public float M31; public float M32; private static readonly Matrix3x2 _identity = new Matrix3x2(1f, 0f, 0f, 1f, 0f, 0f); public static Matrix3x2 Identity => _identity; public bool IsIdentity { get { if (M11 == 1f && M22 == 1f && M12 == 0f && M21 == 0f && M31 == 0f) { return M32 == 0f; } return false; } } public Vector2 Translation { get { return new Vector2(M31, M32); } set { M31 = value.X; M32 = value.Y; } } public Matrix3x2(float m11, float m12, float m21, float m22, float m31, float m32) { M11 = m11; M12 = m12; M21 = m21; M22 = m22; M31 = m31; M32 = m32; } public static Matrix3x2 CreateTranslation(Vector2 position) { Matrix3x2 result = default(Matrix3x2); result.M11 = 1f; result.M12 = 0f; result.M21 = 0f; result.M22 = 1f; result.M31 = position.X; result.M32 = position.Y; return result; } public static Matrix3x2 CreateTranslation(float xPosition, float yPosition) { Matrix3x2 result = default(Matrix3x2); result.M11 = 1f; result.M12 = 0f; result.M21 = 0f; result.M22 = 1f; result.M31 = xPosition; result.M32 = yPosition; return result; } public static Matrix3x2 CreateScale(float xScale, float yScale) { Matrix3x2 result = default(Matrix3x2); result.M11 = xScale; result.M12 = 0f; result.M21 = 0f; result.M22 = yScale; result.M31 = 0f; result.M32 = 0f; return result; } public static Matrix3x2 CreateScale(float xScale, float yScale, Vector2 centerPoint) { float m = centerPoint.X * (1f - xScale); float m2 = centerPoint.Y * (1f - yScale); Matrix3x2 result = default(Matrix3x2); result.M11 = xScale; result.M12 = 0f; result.M21 = 0f; result.M22 = yScale; result.M31 = m; result.M32 = m2; return result; } public static Matrix3x2 CreateScale(Vector2 scales) { Matrix3x2 result = default(Matrix3x2); result.M11 = scales.X; result.M12 = 0f; result.M21 = 0f; result.M22 = scales.Y; result.M31 = 0f; result.M32 = 0f; return result; } public static Matrix3x2 CreateScale(Vector2 scales, Vector2 centerPoint) { float m = centerPoint.X * (1f - scales.X); float m2 = centerPoint.Y * (1f - scales.Y); Matrix3x2 result = default(Matrix3x2); result.M11 = scales.X; result.M12 = 0f; result.M21 = 0f; result.M22 = scales.Y; result.M31 = m; result.M32 = m2; return result; } public static Matrix3x2 CreateScale(float scale) { Matrix3x2 result = default(Matrix3x2); result.M11 = scale; result.M12 = 0f; result.M21 = 0f; result.M22 = scale; result.M31 = 0f; result.M32 = 0f; return result; } public static Matrix3x2 CreateScale(float scale, Vector2 centerPoint) { float m = centerPoint.X * (1f - scale); float m2 = centerPoint.Y * (1f - scale); Matrix3x2 result = default(Matrix3x2); result.M11 = scale; result.M12 = 0f; result.M21 = 0f; result.M22 = scale; result.M31 = m; result.M32 = m2; return result; } public static Matrix3x2 CreateSkew(float radiansX, float radiansY) { float m = MathF.Tan(radiansX); float m2 = MathF.Tan(radiansY); Matrix3x2 result = default(Matrix3x2); result.M11 = 1f; result.M12 = m2; result.M21 = m; result.M22 = 1f; result.M31 = 0f; result.M32 = 0f; return result; } public static Matrix3x2 CreateSkew(float radiansX, float radiansY, Vector2 centerPoint) { float num = MathF.Tan(radiansX); float num2 = MathF.Tan(radiansY); float m = (0f - centerPoint.Y) * num; float m2 = (0f - centerPoint.X) * num2; Matrix3x2 result = default(Matrix3x2); result.M11 = 1f; result.M12 = num2; result.M21 = num; result.M22 = 1f; result.M31 = m; result.M32 = m2; return result; } public static Matrix3x2 CreateRotation(float radians) { radians = MathF.IEEERemainder(radians, (float)Math.PI * 2f); float num; float num2; if (radians > -1.7453294E-05f && radians < 1.7453294E-05f) { num = 1f; num2 = 0f; } else if (radians > 1.570779f && radians < 1.5708138f) { num = 0f; num2 = 1f; } else if (radians < -3.1415753f || radians > 3.1415753f) { num = -1f; num2 = 0f; } else if (radians > -1.5708138f && radians < -1.570779f) { num = 0f; num2 = -1f; } else { num = MathF.Cos(radians); num2 = MathF.Sin(radians); } Matrix3x2 result = default(Matrix3x2); result.M11 = num; result.M12 = num2; result.M21 = 0f - num2; result.M22 = num; result.M31 = 0f; result.M32 = 0f; return result; } public static Matrix3x2 CreateRotation(float radians, Vector2 centerPoint) { radians = MathF.IEEERemainder(radians, (float)Math.PI * 2f); float num; float num2; if (radians > -1.7453294E-05f && radians < 1.7453294E-05f) { num = 1f; num2 = 0f; } else if (radians > 1.570779f && radians < 1.5708138f) { num = 0f; num2 = 1f; } else if (radians < -3.1415753f || radians > 3.1415753f) { num = -1f; num2 = 0f; } else if (radians > -1.5708138f && radians < -1.570779f) { num = 0f; num2 = -1f; } else { num = MathF.Cos(radians); num2 = MathF.Sin(radians); } float m = centerPoint.X * (1f - num) + centerPoint.Y * num2; float m2 = centerPoint.Y * (1f - num) - centerPoint.X * num2; Matrix3x2 result = default(Matrix3x2); result.M11 = num; result.M12 = num2; result.M21 = 0f - num2; result.M22 = num; result.M31 = m; result.M32 = m2; return result; } public float GetDeterminant() { return M11 * M22 - M21 * M12; } public static bool Invert(Matrix3x2 matrix, out Matrix3x2 result) { float num = matrix.M11 * matrix.M22 - matrix.M21 * matrix.M12; if (MathF.Abs(num) < float.Epsilon) { result = new Matrix3x2(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN); return false; } float num2 = 1f / num; result.M11 = matrix.M22 * num2; result.M12 = (0f - matrix.M12) * num2; result.M21 = (0f - matrix.M21) * num2; result.M22 = matrix.M11 * num2; result.M31 = (matrix.M21 * matrix.M32 - matrix.M31 * matrix.M22) * num2; result.M32 = (matrix.M31 * matrix.M12 - matrix.M11 * matrix.M32) * num2; return true; } public static Matrix3x2 Lerp(Matrix3x2 matrix1, Matrix3x2 matrix2, float amount) { Matrix3x2 result = default(Matrix3x2); result.M11 = matrix1.M11 + (matrix2.M11 - matrix1.M11) * amount; result.M12 = matrix1.M12 + (matrix2.M12 - matrix1.M12) * amount; result.M21 = matrix1.M21 + (matrix2.M21 - matrix1.M21) * amount; result.M22 = matrix1.M22 + (matrix2.M22 - matrix1.M22) * amount; result.M31 = matrix1.M31 + (matrix2.M31 - matrix1.M31) * amount; result.M32 = matrix1.M32 + (matrix2.M32 - matrix1.M32) * amount; return result; } public static Matrix3x2 Negate(Matrix3x2 value) { Matrix3x2 result = default(Matrix3x2); result.M11 = 0f - value.M11; result.M12 = 0f - value.M12; result.M21 = 0f - value.M21; result.M22 = 0f - value.M22; result.M31 = 0f - value.M31; result.M32 = 0f - value.M32; return result; } public static Matrix3x2 Add(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 result = default(Matrix3x2); result.M11 = value1.M11 + value2.M11; result.M12 = value1.M12 + value2.M12; result.M21 = value1.M21 + value2.M21; result.M22 = value1.M22 + value2.M22; result.M31 = value1.M31 + value2.M31; result.M32 = value1.M32 + value2.M32; return result; } public static Matrix3x2 Subtract(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 result = default(Matrix3x2); result.M11 = value1.M11 - value2.M11; result.M12 = value1.M12 - value2.M12; result.M21 = value1.M21 - value2.M21; result.M22 = value1.M22 - value2.M22; result.M31 = value1.M31 - value2.M31; result.M32 = value1.M32 - value2.M32; return result; } public static Matrix3x2 Multiply(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 result = default(Matrix3x2); result.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21; result.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22; result.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21; result.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22; result.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value2.M31; result.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value2.M32; return result; } public static Matrix3x2 Multiply(Matrix3x2 value1, float value2) { Matrix3x2 result = default(Matrix3x2); result.M11 = value1.M11 * value2; result.M12 = value1.M12 * value2; result.M21 = value1.M21 * value2; result.M22 = value1.M22 * value2; result.M31 = value1.M31 * value2; result.M32 = value1.M32 * value2; return result; } public static Matrix3x2 operator -(Matrix3x2 value) { Matrix3x2 result = default(Matrix3x2); result.M11 = 0f - value.M11; result.M12 = 0f - value.M12; result.M21 = 0f - value.M21; result.M22 = 0f - value.M22; result.M31 = 0f - value.M31; result.M32 = 0f - value.M32; return result; } public static Matrix3x2 operator +(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 result = default(Matrix3x2); result.M11 = value1.M11 + value2.M11; result.M12 = value1.M12 + value2.M12; result.M21 = value1.M21 + value2.M21; result.M22 = value1.M22 + value2.M22; result.M31 = value1.M31 + value2.M31; result.M32 = value1.M32 + value2.M32; return result; } public static Matrix3x2 operator -(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 result = default(Matrix3x2); result.M11 = value1.M11 - value2.M11; result.M12 = value1.M12 - value2.M12; result.M21 = value1.M21 - value2.M21; result.M22 = value1.M22 - value2.M22; result.M31 = value1.M31 - value2.M31; result.M32 = value1.M32 - value2.M32; return result; } public static Matrix3x2 operator *(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 result = default(Matrix3x2); result.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21; result.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22; result.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21; result.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22; result.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value2.M31; result.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value2.M32; return result; } public static Matrix3x2 operator *(Matrix3x2 value1, float value2) { Matrix3x2 result = default(Matrix3x2); result.M11 = value1.M11 * value2; result.M12 = value1.M12 * value2; result.M21 = value1.M21 * value2; result.M22 = value1.M22 * value2; result.M31 = value1.M31 * value2; result.M32 = value1.M32 * value2; return result; } public static bool operator ==(Matrix3x2 value1, Matrix3x2 value2) { if (value1.M11 == value2.M11 && value1.M22 == value2.M22 && value1.M12 == value2.M12 && value1.M21 == value2.M21 && value1.M31 == value2.M31) { return value1.M32 == value2.M32; } return false; } public static bool operator !=(Matrix3x2 value1, Matrix3x2 value2) { if (value1.M11 == value2.M11 && value1.M12 == value2.M12 && value1.M21 == value2.M21 && value1.M22 == value2.M22 && value1.M31 == value2.M31) { return value1.M32 != value2.M32; } return true; } public bool Equals(Matrix3x2 other) { if (M11 == other.M11 && M22 == other.M22 && M12 == other.M12 && M21 == other.M21 && M31 == other.M31) { return M32 == other.M32; } return false; } public override bool Equals(object obj) { if (obj is Matrix3x2) { return Equals((Matrix3x2)obj); } return false; } public override string ToString() { CultureInfo currentCulture = CultureInfo.CurrentCulture; return string.Format(currentCulture, "{{ {{M11:{0} M12:{1}}} {{M21:{2} M22:{3}}} {{M31:{4} M32:{5}}} }}", M11.ToString(currentCulture), M12.ToString(currentCulture), M21.ToString(currentCulture), M22.ToString(currentCulture), M31.ToString(currentCulture), M32.ToString(currentCulture)); } public override int GetHashCode() { return M11.GetHashCode() + M12.GetHashCode() + M21.GetHashCode() + M22.GetHashCode() + M31.GetHashCode() + M32.GetHashCode(); } } internal struct Matrix4x4 : IEquatable { private struct CanonicalBasis { public Vector3 Row0; public Vector3 Row1; public Vector3 Row2; } private struct VectorBasis { public unsafe Vector3* Element0; public unsafe Vector3* Element1; public unsafe Vector3* Element2; } public float M11; public float M12; public float M13; public float M14; public float M21; public float M22; public float M23; public float M24; public float M31; public float M32; public float M33; public float M34; public float M41; public float M42; public float M43; public float M44; private static readonly Matrix4x4 _identity = new Matrix4x4(1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f); public static Matrix4x4 Identity => _identity; public bool IsIdentity { get { if (M11 == 1f && M22 == 1f && M33 == 1f && M44 == 1f && M12 == 0f && M13 == 0f && M14 == 0f && M21 == 0f && M23 == 0f && M24 == 0f && M31 == 0f && M32 == 0f && M34 == 0f && M41 == 0f && M42 == 0f) { return M43 == 0f; } return false; } } public Vector3 Translation { get { return new Vector3(M41, M42, M43); } set { M41 = value.X; M42 = value.Y; M43 = value.Z; } } public Matrix4x4(float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44) { M11 = m11; M12 = m12; M13 = m13; M14 = m14; M21 = m21; M22 = m22; M23 = m23; M24 = m24; M31 = m31; M32 = m32; M33 = m33; M34 = m34; M41 = m41; M42 = m42; M43 = m43; M44 = m44; } public Matrix4x4(Matrix3x2 value) { M11 = value.M11; M12 = value.M12; M13 = 0f; M14 = 0f; M21 = value.M21; M22 = value.M22; M23 = 0f; M24 = 0f; M31 = 0f; M32 = 0f; M33 = 1f; M34 = 0f; M41 = value.M31; M42 = value.M32; M43 = 0f; M44 = 1f; } public static Matrix4x4 CreateBillboard(Vector3 objectPosition, Vector3 cameraPosition, Vector3 cameraUpVector, Vector3 cameraForwardVector) { Vector3 left = new Vector3(objectPosition.X - cameraPosition.X, objectPosition.Y - cameraPosition.Y, objectPosition.Z - cameraPosition.Z); float num = left.LengthSquared(); left = ((!(num < 0.0001f)) ? Vector3.Multiply(left, 1f / MathF.Sqrt(num)) : (-cameraForwardVector)); Vector3 vector = Vector3.Normalize(Vector3.Cross(cameraUpVector, left)); Vector3 vector2 = Vector3.Cross(left, vector); Matrix4x4 result = default(Matrix4x4); result.M11 = vector.X; result.M12 = vector.Y; result.M13 = vector.Z; result.M14 = 0f; result.M21 = vector2.X; result.M22 = vector2.Y; result.M23 = vector2.Z; result.M24 = 0f; result.M31 = left.X; result.M32 = left.Y; result.M33 = left.Z; result.M34 = 0f; result.M41 = objectPosition.X; result.M42 = objectPosition.Y; result.M43 = objectPosition.Z; result.M44 = 1f; return result; } public static Matrix4x4 CreateConstrainedBillboard(Vector3 objectPosition, Vector3 cameraPosition, Vector3 rotateAxis, Vector3 cameraForwardVector, Vector3 objectForwardVector) { Vector3 left = new Vector3(objectPosition.X - cameraPosition.X, objectPosition.Y - cameraPosition.Y, objectPosition.Z - cameraPosition.Z); float num = left.LengthSquared(); left = ((!(num < 0.0001f)) ? Vector3.Multiply(left, 1f / MathF.Sqrt(num)) : (-cameraForwardVector)); Vector3 vector = rotateAxis; float x = Vector3.Dot(rotateAxis, left); Vector3 vector3; Vector3 vector2; if (MathF.Abs(x) > 0.99825466f) { vector2 = objectForwardVector; x = Vector3.Dot(rotateAxis, vector2); if (MathF.Abs(x) > 0.99825466f) { vector2 = ((MathF.Abs(rotateAxis.Z) > 0.99825466f) ? new Vector3(1f, 0f, 0f) : new Vector3(0f, 0f, -1f)); } vector3 = Vector3.Normalize(Vector3.Cross(rotateAxis, vector2)); vector2 = Vector3.Normalize(Vector3.Cross(vector3, rotateAxis)); } else { vector3 = Vector3.Normalize(Vector3.Cross(rotateAxis, left)); vector2 = Vector3.Normalize(Vector3.Cross(vector3, vector)); } Matrix4x4 result = default(Matrix4x4); result.M11 = vector3.X; result.M12 = vector3.Y; result.M13 = vector3.Z; result.M14 = 0f; result.M21 = vector.X; result.M22 = vector.Y; result.M23 = vector.Z; result.M24 = 0f; result.M31 = vector2.X; result.M32 = vector2.Y; result.M33 = vector2.Z; result.M34 = 0f; result.M41 = objectPosition.X; result.M42 = objectPosition.Y; result.M43 = objectPosition.Z; result.M44 = 1f; return result; } public static Matrix4x4 CreateTranslation(Vector3 position) { Matrix4x4 result = default(Matrix4x4); result.M11 = 1f; result.M12 = 0f; result.M13 = 0f; result.M14 = 0f; result.M21 = 0f; result.M22 = 1f; result.M23 = 0f; result.M24 = 0f; result.M31 = 0f; result.M32 = 0f; result.M33 = 1f; result.M34 = 0f; result.M41 = position.X; result.M42 = position.Y; result.M43 = position.Z; result.M44 = 1f; return result; } public static Matrix4x4 CreateTranslation(float xPosition, float yPosition, float zPosition) { Matrix4x4 result = default(Matrix4x4); result.M11 = 1f; result.M12 = 0f; result.M13 = 0f; result.M14 = 0f; result.M21 = 0f; result.M22 = 1f; result.M23 = 0f; result.M24 = 0f; result.M31 = 0f; result.M32 = 0f; result.M33 = 1f; result.M34 = 0f; result.M41 = xPosition; result.M42 = yPosition; result.M43 = zPosition; result.M44 = 1f; return result; } public static Matrix4x4 CreateScale(float xScale, float yScale, float zScale) { Matrix4x4 result = default(Matrix4x4); result.M11 = xScale; result.M12 = 0f; result.M13 = 0f; result.M14 = 0f; result.M21 = 0f; result.M22 = yScale; result.M23 = 0f; result.M24 = 0f; result.M31 = 0f; result.M32 = 0f; result.M33 = zScale; result.M34 = 0f; result.M41 = 0f; result.M42 = 0f; result.M43 = 0f; result.M44 = 1f; return result; } public static Matrix4x4 CreateScale(float xScale, float yScale, float zScale, Vector3 centerPoint) { float m = centerPoint.X * (1f - xScale); float m2 = centerPoint.Y * (1f - yScale); float m3 = centerPoint.Z * (1f - zScale); Matrix4x4 result = default(Matrix4x4); result.M11 = xScale; result.M12 = 0f; result.M13 = 0f; result.M14 = 0f; result.M21 = 0f; result.M22 = yScale; result.M23 = 0f; result.M24 = 0f; result.M31 = 0f; result.M32 = 0f; result.M33 = zScale; result.M34 = 0f; result.M41 = m; result.M42 = m2; result.M43 = m3; result.M44 = 1f; return result; } public static Matrix4x4 CreateScale(Vector3 scales) { Matrix4x4 result = default(Matrix4x4); result.M11 = scales.X; result.M12 = 0f; result.M13 = 0f; result.M14 = 0f; result.M21 = 0f; result.M22 = scales.Y; result.M23 = 0f; result.M24 = 0f; result.M31 = 0f; result.M32 = 0f; result.M33 = scales.Z; result.M34 = 0f; result.M41 = 0f; result.M42 = 0f; result.M43 = 0f; result.M44 = 1f; return result; } public static Matrix4x4 CreateScale(Vector3 scales, Vector3 centerPoint) { float m = centerPoint.X * (1f - scales.X); float m2 = centerPoint.Y * (1f - scales.Y); float m3 = centerPoint.Z * (1f - scales.Z); Matrix4x4 result = default(Matrix4x4); result.M11 = scales.X; result.M12 = 0f; result.M13 = 0f; result.M14 = 0f; result.M21 = 0f; result.M22 = scales.Y; result.M23 = 0f; result.M24 = 0f; result.M31 = 0f; result.M32 = 0f; result.M33 = scales.Z; result.M34 = 0f; result.M41 = m; result.M42 = m2; result.M43 = m3; result.M44 = 1f; return result; } public static Matrix4x4 CreateScale(float scale) { Matrix4x4 result = default(Matrix4x4); result.M11 = scale; result.M12 = 0f; result.M13 = 0f; result.M14 = 0f; result.M21 = 0f; result.M22 = scale; result.M23 = 0f; result.M24 = 0f; result.M31 = 0f; result.M32 = 0f; result.M33 = scale; result.M34 = 0f; result.M41 = 0f; result.M42 = 0f; result.M43 = 0f; result.M44 = 1f; return result; } public static Matrix4x4 CreateScale(float scale, Vector3 centerPoint) { float m = centerPoint.X * (1f - scale); float m2 = centerPoint.Y * (1f - scale); float m3 = centerPoint.Z * (1f - scale); Matrix4x4 result = default(Matrix4x4); result.M11 = scale; result.M12 = 0f; result.M13 = 0f; result.M14 = 0f; result.M21 = 0f; result.M22 = scale; result.M23 = 0f; result.M24 = 0f; result.M31 = 0f; result.M32 = 0f; result.M33 = scale; result.M34 = 0f; result.M41 = m; result.M42 = m2; result.M43 = m3; result.M44 = 1f; return result; } public static Matrix4x4 CreateRotationX(float radians) { float num = MathF.Cos(radians); float num2 = MathF.Sin(radians); Matrix4x4 result = default(Matrix4x4); result.M11 = 1f; result.M12 = 0f; result.M13 = 0f; result.M14 = 0f; result.M21 = 0f; result.M22 = num; result.M23 = num2; result.M24 = 0f; result.M31 = 0f; result.M32 = 0f - num2; result.M33 = num; result.M34 = 0f; result.M41 = 0f; result.M42 = 0f; result.M43 = 0f; result.M44 = 1f; return result; } public static Matrix4x4 CreateRotationX(float radians, Vector3 centerPoint) { float num = MathF.Cos(radians); float num2 = MathF.Sin(radians); float m = centerPoint.Y * (1f - num) + centerPoint.Z * num2; float m2 = centerPoint.Z * (1f - num) - centerPoint.Y * num2; Matrix4x4 result = default(Matrix4x4); result.M11 = 1f; result.M12 = 0f; result.M13 = 0f; result.M14 = 0f; result.M21 = 0f; result.M22 = num; result.M23 = num2; result.M24 = 0f; result.M31 = 0f; result.M32 = 0f - num2; result.M33 = num; result.M34 = 0f; result.M41 = 0f; result.M42 = m; result.M43 = m2; result.M44 = 1f; return result; } public static Matrix4x4 CreateRotationY(float radians) { float num = MathF.Cos(radians); float num2 = MathF.Sin(radians); Matrix4x4 result = default(Matrix4x4); result.M11 = num; result.M12 = 0f; result.M13 = 0f - num2; result.M14 = 0f; result.M21 = 0f; result.M22 = 1f; result.M23 = 0f; result.M24 = 0f; result.M31 = num2; result.M32 = 0f; result.M33 = num; result.M34 = 0f; result.M41 = 0f; result.M42 = 0f; result.M43 = 0f; result.M44 = 1f; return result; } public static Matrix4x4 CreateRotationY(float radians, Vector3 centerPoint) { float num = MathF.Cos(radians); float num2 = MathF.Sin(radians); float m = centerPoint.X * (1f - num) - centerPoint.Z * num2; float m2 = centerPoint.Z * (1f - num) + centerPoint.X * num2; Matrix4x4 result = default(Matrix4x4); result.M11 = num; result.M12 = 0f; result.M13 = 0f - num2; result.M14 = 0f; result.M21 = 0f; result.M22 = 1f; result.M23 = 0f; result.M24 = 0f; result.M31 = num2; result.M32 = 0f; result.M33 = num; result.M34 = 0f; result.M41 = m; result.M42 = 0f; result.M43 = m2; result.M44 = 1f; return result; } public static Matrix4x4 CreateRotationZ(float radians) { float num = MathF.Cos(radians); float num2 = MathF.Sin(radians); Matrix4x4 result = default(Matrix4x4); result.M11 = num; result.M12 = num2; result.M13 = 0f; result.M14 = 0f; result.M21 = 0f - num2; result.M22 = num; result.M23 = 0f; result.M24 = 0f; result.M31 = 0f; result.M32 = 0f; result.M33 = 1f; result.M34 = 0f; result.M41 = 0f; result.M42 = 0f; result.M43 = 0f; result.M44 = 1f; return result; } public static Matrix4x4 CreateRotationZ(float radians, Vector3 centerPoint) { float num = MathF.Cos(radians); float num2 = MathF.Sin(radians); float m = centerPoint.X * (1f - num) + centerPoint.Y * num2; float m2 = centerPoint.Y * (1f - num) - centerPoint.X * num2; Matrix4x4 result = default(Matrix4x4); result.M11 = num; result.M12 = num2; result.M13 = 0f; result.M14 = 0f; result.M21 = 0f - num2; result.M22 = num; result.M23 = 0f; result.M24 = 0f; result.M31 = 0f; result.M32 = 0f; result.M33 = 1f; result.M34 = 0f; result.M41 = m; result.M42 = m2; result.M43 = 0f; result.M44 = 1f; return result; } public static Matrix4x4 CreateFromAxisAngle(Vector3 axis, float angle) { float x = axis.X; float y = axis.Y; float z = axis.Z; float num = MathF.Sin(angle); float num2 = MathF.Cos(angle); float num3 = x * x; float num4 = y * y; float num5 = z * z; float num6 = x * y; float num7 = x * z; float num8 = y * z; Matrix4x4 result = default(Matrix4x4); result.M11 = num3 + num2 * (1f - num3); result.M12 = num6 - num2 * num6 + num * z; result.M13 = num7 - num2 * num7 - num * y; result.M14 = 0f; result.M21 = num6 - num2 * num6 - num * z; result.M22 = num4 + num2 * (1f - num4); result.M23 = num8 - num2 * num8 + num * x; result.M24 = 0f; result.M31 = num7 - num2 * num7 + num * y; result.M32 = num8 - num2 * num8 - num * x; result.M33 = num5 + num2 * (1f - num5); result.M34 = 0f; result.M41 = 0f; result.M42 = 0f; result.M43 = 0f; result.M44 = 1f; return result; } public static Matrix4x4 CreatePerspectiveFieldOfView(float fieldOfView, float aspectRatio, float nearPlaneDistance, float farPlaneDistance) { if (fieldOfView <= 0f || fieldOfView >= (float)Math.PI) { throw new ArgumentOutOfRangeException("fieldOfView"); } if (nearPlaneDistance <= 0f) { throw new ArgumentOutOfRangeException("nearPlaneDistance"); } if (farPlaneDistance <= 0f) { throw new ArgumentOutOfRangeException("farPlaneDistance"); } if (nearPlaneDistance >= farPlaneDistance) { throw new ArgumentOutOfRangeException("nearPlaneDistance"); } float num = 1f / MathF.Tan(fieldOfView * 0.5f); float m = num / aspectRatio; Matrix4x4 result = default(Matrix4x4); result.M11 = m; result.M12 = (result.M13 = (result.M14 = 0f)); result.M22 = num; result.M21 = (result.M23 = (result.M24 = 0f)); result.M31 = (result.M32 = 0f); float num2 = (result.M33 = (float.IsPositiveInfinity(farPlaneDistance) ? (-1f) : (farPlaneDistance / (nearPlaneDistance - farPlaneDistance)))); result.M34 = -1f; result.M41 = (result.M42 = (result.M44 = 0f)); result.M43 = nearPlaneDistance * num2; return result; } public static Matrix4x4 CreatePerspective(float width, float height, float nearPlaneDistance, float farPlaneDistance) { if (nearPlaneDistance <= 0f) { throw new ArgumentOutOfRangeException("nearPlaneDistance"); } if (farPlaneDistance <= 0f) { throw new ArgumentOutOfRangeException("farPlaneDistance"); } if (nearPlaneDistance >= farPlaneDistance) { throw new ArgumentOutOfRangeException("nearPlaneDistance"); } Matrix4x4 result = default(Matrix4x4); result.M11 = 2f * nearPlaneDistance / width; result.M12 = (result.M13 = (result.M14 = 0f)); result.M22 = 2f * nearPlaneDistance / height; result.M21 = (result.M23 = (result.M24 = 0f)); float num = (result.M33 = (float.IsPositiveInfinity(farPlaneDistance) ? (-1f) : (farPlaneDistance / (nearPlaneDistance - farPlaneDistance)))); result.M31 = (result.M32 = 0f); result.M34 = -1f; result.M41 = (result.M42 = (result.M44 = 0f)); result.M43 = nearPlaneDistance * num; return result; } public static Matrix4x4 CreatePerspectiveOffCenter(float left, float right, float bottom, float top, float nearPlaneDistance, float farPlaneDistance) { if (nearPlaneDistance <= 0f) { throw new ArgumentOutOfRangeException("nearPlaneDistance"); } if (farPlaneDistance <= 0f) { throw new ArgumentOutOfRangeException("farPlaneDistance"); } if (nearPlaneDistance >= farPlaneDistance) { throw new ArgumentOutOfRangeException("nearPlaneDistance"); } Matrix4x4 result = default(Matrix4x4); result.M11 = 2f * nearPlaneDistance / (right - left); result.M12 = (result.M13 = (result.M14 = 0f)); result.M22 = 2f * nearPlaneDistance / (top - bottom); result.M21 = (result.M23 = (result.M24 = 0f)); result.M31 = (left + right) / (right - left); result.M32 = (top + bottom) / (top - bottom); float num = (result.M33 = (float.IsPositiveInfinity(farPlaneDistance) ? (-1f) : (farPlaneDistance / (nearPlaneDistance - farPlaneDistance)))); result.M34 = -1f; result.M43 = nearPlaneDistance * num; result.M41 = (result.M42 = (result.M44 = 0f)); return result; } public static Matrix4x4 CreateOrthographic(float width, float height, float zNearPlane, float zFarPlane) { Matrix4x4 result = default(Matrix4x4); result.M11 = 2f / width; result.M12 = (result.M13 = (result.M14 = 0f)); result.M22 = 2f / height; result.M21 = (result.M23 = (result.M24 = 0f)); result.M33 = 1f / (zNearPlane - zFarPlane); result.M31 = (result.M32 = (result.M34 = 0f)); result.M41 = (result.M42 = 0f); result.M43 = zNearPlane / (zNearPlane - zFarPlane); result.M44 = 1f; return result; } public static Matrix4x4 CreateOrthographicOffCenter(float left, float right, float bottom, float top, float zNearPlane, float zFarPlane) { Matrix4x4 result = default(Matrix4x4); result.M11 = 2f / (right - left); result.M12 = (result.M13 = (result.M14 = 0f)); result.M22 = 2f / (top - bottom); result.M21 = (result.M23 = (result.M24 = 0f)); result.M33 = 1f / (zNearPlane - zFarPlane); result.M31 = (result.M32 = (result.M34 = 0f)); result.M41 = (left + right) / (left - right); result.M42 = (top + bottom) / (bottom - top); result.M43 = zNearPlane / (zNearPlane - zFarPlane); result.M44 = 1f; return result; } public static Matrix4x4 CreateLookAt(Vector3 cameraPosition, Vector3 cameraTarget, Vector3 cameraUpVector) { Vector3 vector = Vector3.Normalize(cameraPosition - cameraTarget); Vector3 vector2 = Vector3.Normalize(Vector3.Cross(cameraUpVector, vector)); Vector3 vector3 = Vector3.Cross(vector, vector2); Matrix4x4 result = default(Matrix4x4); result.M11 = vector2.X; result.M12 = vector3.X; result.M13 = vector.X; result.M14 = 0f; result.M21 = vector2.Y; result.M22 = vector3.Y; result.M23 = vector.Y; result.M24 = 0f; result.M31 = vector2.Z; result.M32 = vector3.Z; result.M33 = vector.Z; result.M34 = 0f; result.M41 = 0f - Vector3.Dot(vector2, cameraPosition); result.M42 = 0f - Vector3.Dot(vector3, cameraPosition); result.M43 = 0f - Vector3.Dot(vector, cameraPosition); result.M44 = 1f; return result; } public static Matrix4x4 CreateWorld(Vector3 position, Vector3 forward, Vector3 up) { Vector3 vector = Vector3.Normalize(-forward); Vector3 vector2 = Vector3.Normalize(Vector3.Cross(up, vector)); Vector3 vector3 = Vector3.Cross(vector, vector2); Matrix4x4 result = default(Matrix4x4); result.M11 = vector2.X; result.M12 = vector2.Y; result.M13 = vector2.Z; result.M14 = 0f; result.M21 = vector3.X; result.M22 = vector3.Y; result.M23 = vector3.Z; result.M24 = 0f; result.M31 = vector.X; result.M32 = vector.Y; result.M33 = vector.Z; result.M34 = 0f; result.M41 = position.X; result.M42 = position.Y; result.M43 = position.Z; result.M44 = 1f; return result; } public static Matrix4x4 CreateFromQuaternion(Quaternion quaternion) { float num = quaternion.X * quaternion.X; float num2 = quaternion.Y * quaternion.Y; float num3 = quaternion.Z * quaternion.Z; float num4 = quaternion.X * quaternion.Y; float num5 = quaternion.Z * quaternion.W; float num6 = quaternion.Z * quaternion.X; float num7 = quaternion.Y * quaternion.W; float num8 = quaternion.Y * quaternion.Z; float num9 = quaternion.X * quaternion.W; Matrix4x4 result = default(Matrix4x4); result.M11 = 1f - 2f * (num2 + num3); result.M12 = 2f * (num4 + num5); result.M13 = 2f * (num6 - num7); result.M14 = 0f; result.M21 = 2f * (num4 - num5); result.M22 = 1f - 2f * (num3 + num); result.M23 = 2f * (num8 + num9); result.M24 = 0f; result.M31 = 2f * (num6 + num7); result.M32 = 2f * (num8 - num9); result.M33 = 1f - 2f * (num2 + num); result.M34 = 0f; result.M41 = 0f; result.M42 = 0f; result.M43 = 0f; result.M44 = 1f; return result; } public static Matrix4x4 CreateFromYawPitchRoll(float yaw, float pitch, float roll) { Quaternion quaternion = Quaternion.CreateFromYawPitchRoll(yaw, pitch, roll); return CreateFromQuaternion(quaternion); } public static Matrix4x4 CreateShadow(Vector3 lightDirection, Plane plane) { Plane plane2 = Plane.Normalize(plane); float num = plane2.Normal.X * lightDirection.X + plane2.Normal.Y * lightDirection.Y + plane2.Normal.Z * lightDirection.Z; float num2 = 0f - plane2.Normal.X; float num3 = 0f - plane2.Normal.Y; float num4 = 0f - plane2.Normal.Z; float num5 = 0f - plane2.D; Matrix4x4 result = default(Matrix4x4); result.M11 = num2 * lightDirection.X + num; result.M21 = num3 * lightDirection.X; result.M31 = num4 * lightDirection.X; result.M41 = num5 * lightDirection.X; result.M12 = num2 * lightDirection.Y; result.M22 = num3 * lightDirection.Y + num; result.M32 = num4 * lightDirection.Y; result.M42 = num5 * lightDirection.Y; result.M13 = num2 * lightDirection.Z; result.M23 = num3 * lightDirection.Z; result.M33 = num4 * lightDirection.Z + num; result.M43 = num5 * lightDirection.Z; result.M14 = 0f; result.M24 = 0f; result.M34 = 0f; result.M44 = num; return result; } public static Matrix4x4 CreateReflection(Plane value) { value = Plane.Normalize(value); float x = value.Normal.X; float y = value.Normal.Y; float z = value.Normal.Z; float num = -2f * x; float num2 = -2f * y; float num3 = -2f * z; Matrix4x4 result = default(Matrix4x4); result.M11 = num * x + 1f; result.M12 = num2 * x; result.M13 = num3 * x; result.M14 = 0f; result.M21 = num * y; result.M22 = num2 * y + 1f; result.M23 = num3 * y; result.M24 = 0f; result.M31 = num * z; result.M32 = num2 * z; result.M33 = num3 * z + 1f; result.M34 = 0f; result.M41 = num * value.D; result.M42 = num2 * value.D; result.M43 = num3 * value.D; result.M44 = 1f; return result; } public float GetDeterminant() { float m = M11; float m2 = M12; float m3 = M13; float m4 = M14; float m5 = M21; float m6 = M22; float m7 = M23; float m8 = M24; float m9 = M31; float m10 = M32; float m11 = M33; float m12 = M34; float m13 = M41; float m14 = M42; float m15 = M43; float m16 = M44; float num = m11 * m16 - m12 * m15; float num2 = m10 * m16 - m12 * m14; float num3 = m10 * m15 - m11 * m14; float num4 = m9 * m16 - m12 * m13; float num5 = m9 * m15 - m11 * m13; float num6 = m9 * m14 - m10 * m13; return m * (m6 * num - m7 * num2 + m8 * num3) - m2 * (m5 * num - m7 * num4 + m8 * num5) + m3 * (m5 * num2 - m6 * num4 + m8 * num6) - m4 * (m5 * num3 - m6 * num5 + m7 * num6); } public static bool Invert(Matrix4x4 matrix, out Matrix4x4 result) { float m = matrix.M11; float m2 = matrix.M12; float m3 = matrix.M13; float m4 = matrix.M14; float m5 = matrix.M21; float m6 = matrix.M22; float m7 = matrix.M23; float m8 = matrix.M24; float m9 = matrix.M31; float m10 = matrix.M32; float m11 = matrix.M33; float m12 = matrix.M34; float m13 = matrix.M41; float m14 = matrix.M42; float m15 = matrix.M43; float m16 = matrix.M44; float num = m11 * m16 - m12 * m15; float num2 = m10 * m16 - m12 * m14; float num3 = m10 * m15 - m11 * m14; float num4 = m9 * m16 - m12 * m13; float num5 = m9 * m15 - m11 * m13; float num6 = m9 * m14 - m10 * m13; float num7 = m6 * num - m7 * num2 + m8 * num3; float num8 = 0f - (m5 * num - m7 * num4 + m8 * num5); float num9 = m5 * num2 - m6 * num4 + m8 * num6; float num10 = 0f - (m5 * num3 - m6 * num5 + m7 * num6); float num11 = m * num7 + m2 * num8 + m3 * num9 + m4 * num10; if (MathF.Abs(num11) < float.Epsilon) { result = new Matrix4x4(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN); return false; } float num12 = 1f / num11; result.M11 = num7 * num12; result.M21 = num8 * num12; result.M31 = num9 * num12; result.M41 = num10 * num12; result.M12 = (0f - (m2 * num - m3 * num2 + m4 * num3)) * num12; result.M22 = (m * num - m3 * num4 + m4 * num5) * num12; result.M32 = (0f - (m * num2 - m2 * num4 + m4 * num6)) * num12; result.M42 = (m * num3 - m2 * num5 + m3 * num6) * num12; float num13 = m7 * m16 - m8 * m15; float num14 = m6 * m16 - m8 * m14; float num15 = m6 * m15 - m7 * m14; float num16 = m5 * m16 - m8 * m13; float num17 = m5 * m15 - m7 * m13; float num18 = m5 * m14 - m6 * m13; result.M13 = (m2 * num13 - m3 * num14 + m4 * num15) * num12; result.M23 = (0f - (m * num13 - m3 * num16 + m4 * num17)) * num12; result.M33 = (m * num14 - m2 * num16 + m4 * num18) * num12; result.M43 = (0f - (m * num15 - m2 * num17 + m3 * num18)) * num12; float num19 = m7 * m12 - m8 * m11; float num20 = m6 * m12 - m8 * m10; float num21 = m6 * m11 - m7 * m10; float num22 = m5 * m12 - m8 * m9; float num23 = m5 * m11 - m7 * m9; float num24 = m5 * m10 - m6 * m9; result.M14 = (0f - (m2 * num19 - m3 * num20 + m4 * num21)) * num12; result.M24 = (m * num19 - m3 * num22 + m4 * num23) * num12; result.M34 = (0f - (m * num20 - m2 * num22 + m4 * num24)) * num12; result.M44 = (m * num21 - m2 * num23 + m3 * num24) * num12; return true; } public unsafe static bool Decompose(Matrix4x4 matrix, out Vector3 scale, out Quaternion rotation, out Vector3 translation) { bool result = true; fixed (Vector3* ptr = &scale) { float* ptr2 = (float*)ptr; VectorBasis vectorBasis = default(VectorBasis); Vector3** ptr3 = (Vector3**)(&vectorBasis); Matrix4x4 identity = Identity; CanonicalBasis canonicalBasis = default(CanonicalBasis); Vector3* ptr4 = &canonicalBasis.Row0; canonicalBasis.Row0 = new Vector3(1f, 0f, 0f); canonicalBasis.Row1 = new Vector3(0f, 1f, 0f); canonicalBasis.Row2 = new Vector3(0f, 0f, 1f); translation = new Vector3(matrix.M41, matrix.M42, matrix.M43); *ptr3 = (Vector3*)(&identity.M11); ptr3[1] = (Vector3*)(&identity.M21); ptr3[2] = (Vector3*)(&identity.M31); *(*ptr3) = new Vector3(matrix.M11, matrix.M12, matrix.M13); *ptr3[1] = new Vector3(matrix.M21, matrix.M22, matrix.M23); *ptr3[2] = new Vector3(matrix.M31, matrix.M32, matrix.M33); scale.X = (*ptr3)->Length(); scale.Y = ptr3[1]->Length(); scale.Z = ptr3[2]->Length(); float num = *ptr2; float num2 = ptr2[1]; float num3 = ptr2[2]; uint num4; uint num5; uint num6; if (num < num2) { if (num2 < num3) { num4 = 2u; num5 = 1u; num6 = 0u; } else { num4 = 1u; if (num < num3) { num5 = 2u; num6 = 0u; } else { num5 = 0u; num6 = 2u; } } } else if (num < num3) { num4 = 2u; num5 = 0u; num6 = 1u; } else { num4 = 0u; if (num2 < num3) { num5 = 2u; num6 = 1u; } else { num5 = 1u; num6 = 2u; } } if (ptr2[num4] < 0.0001f) { *ptr3[num4] = ptr4[num4]; } *ptr3[num4] = Vector3.Normalize(*ptr3[num4]); if (ptr2[num5] < 0.0001f) { float num7 = MathF.Abs(ptr3[num4]->X); float num8 = MathF.Abs(ptr3[num4]->Y); float num9 = MathF.Abs(ptr3[num4]->Z); uint num10 = ((num7 < num8) ? ((!(num8 < num9)) ? ((!(num7 < num9)) ? 2u : 0u) : 0u) : ((num7 < num9) ? 1u : ((num8 < num9) ? 1u : 2u))); *ptr3[num5] = Vector3.Cross(*ptr3[num4], ptr4[num10]); } *ptr3[num5] = Vector3.Normalize(*ptr3[num5]); if (ptr2[num6] < 0.0001f) { *ptr3[num6] = Vector3.Cross(*ptr3[num4], *ptr3[num5]); } *ptr3[num6] = Vector3.Normalize(*ptr3[num6]); float num11 = identity.GetDeterminant(); if (num11 < 0f) { ptr2[num4] = 0f - ptr2[num4]; *ptr3[num4] = -(*ptr3[num4]); num11 = 0f - num11; } num11 -= 1f; num11 *= num11; if (0.0001f < num11) { rotation = Quaternion.Identity; result = false; } else { rotation = Quaternion.CreateFromRotationMatrix(identity); } } return result; } public static Matrix4x4 Transform(Matrix4x4 value, Quaternion rotation) { float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num; float num5 = rotation.W * num2; float num6 = rotation.W * num3; float num7 = rotation.X * num; float num8 = rotation.X * num2; float num9 = rotation.X * num3; float num10 = rotation.Y * num2; float num11 = rotation.Y * num3; float num12 = rotation.Z * num3; float num13 = 1f - num10 - num12; float num14 = num8 - num6; float num15 = num9 + num5; float num16 = num8 + num6; float num17 = 1f - num7 - num12; float num18 = num11 - num4; float num19 = num9 - num5; float num20 = num11 + num4; float num21 = 1f - num7 - num10; Matrix4x4 result = default(Matrix4x4); result.M11 = value.M11 * num13 + value.M12 * num14 + value.M13 * num15; result.M12 = value.M11 * num16 + value.M12 * num17 + value.M13 * num18; result.M13 = value.M11 * num19 + value.M12 * num20 + value.M13 * num21; result.M14 = value.M14; result.M21 = value.M21 * num13 + value.M22 * num14 + value.M23 * num15; result.M22 = value.M21 * num16 + value.M22 * num17 + value.M23 * num18; result.M23 = value.M21 * num19 + value.M22 * num20 + value.M23 * num21; result.M24 = value.M24; result.M31 = value.M31 * num13 + value.M32 * num14 + value.M33 * num15; result.M32 = value.M31 * num16 + value.M32 * num17 + value.M33 * num18; result.M33 = value.M31 * num19 + value.M32 * num20 + value.M33 * num21; result.M34 = value.M34; result.M41 = value.M41 * num13 + value.M42 * num14 + value.M43 * num15; result.M42 = value.M41 * num16 + value.M42 * num17 + value.M43 * num18; result.M43 = value.M41 * num19 + value.M42 * num20 + value.M43 * num21; result.M44 = value.M44; return result; } public static Matrix4x4 Transpose(Matrix4x4 matrix) { Matrix4x4 result = default(Matrix4x4); result.M11 = matrix.M11; result.M12 = matrix.M21; result.M13 = matrix.M31; result.M14 = matrix.M41; result.M21 = matrix.M12; result.M22 = matrix.M22; result.M23 = matrix.M32; result.M24 = matrix.M42; result.M31 = matrix.M13; result.M32 = matrix.M23; result.M33 = matrix.M33; result.M34 = matrix.M43; result.M41 = matrix.M14; result.M42 = matrix.M24; result.M43 = matrix.M34; result.M44 = matrix.M44; return result; } public static Matrix4x4 Lerp(Matrix4x4 matrix1, Matrix4x4 matrix2, float amount) { Matrix4x4 result = default(Matrix4x4); result.M11 = matrix1.M11 + (matrix2.M11 - matrix1.M11) * amount; result.M12 = matrix1.M12 + (matrix2.M12 - matrix1.M12) * amount; result.M13 = matrix1.M13 + (matrix2.M13 - matrix1.M13) * amount; result.M14 = matrix1.M14 + (matrix2.M14 - matrix1.M14) * amount; result.M21 = matrix1.M21 + (matrix2.M21 - matrix1.M21) * amount; result.M22 = matrix1.M22 + (matrix2.M22 - matrix1.M22) * amount; result.M23 = matrix1.M23 + (matrix2.M23 - matrix1.M23) * amount; result.M24 = matrix1.M24 + (matrix2.M24 - matrix1.M24) * amount; result.M31 = matrix1.M31 + (matrix2.M31 - matrix1.M31) * amount; result.M32 = matrix1.M32 + (matrix2.M32 - matrix1.M32) * amount; result.M33 = matrix1.M33 + (matrix2.M33 - matrix1.M33) * amount; result.M34 = matrix1.M34 + (matrix2.M34 - matrix1.M34) * amount; result.M41 = matrix1.M41 + (matrix2.M41 - matrix1.M41) * amount; result.M42 = matrix1.M42 + (matrix2.M42 - matrix1.M42) * amount; result.M43 = matrix1.M43 + (matrix2.M43 - matrix1.M43) * amount; result.M44 = matrix1.M44 + (matrix2.M44 - matrix1.M44) * amount; return result; } public static Matrix4x4 Negate(Matrix4x4 value) { Matrix4x4 result = default(Matrix4x4); result.M11 = 0f - value.M11; result.M12 = 0f - value.M12; result.M13 = 0f - value.M13; result.M14 = 0f - value.M14; result.M21 = 0f - value.M21; result.M22 = 0f - value.M22; result.M23 = 0f - value.M23; result.M24 = 0f - value.M24; result.M31 = 0f - value.M31; result.M32 = 0f - value.M32; result.M33 = 0f - value.M33; result.M34 = 0f - value.M34; result.M41 = 0f - value.M41; result.M42 = 0f - value.M42; result.M43 = 0f - value.M43; result.M44 = 0f - value.M44; return result; } public static Matrix4x4 Add(Matrix4x4 value1, Matrix4x4 value2) { Matrix4x4 result = default(Matrix4x4); result.M11 = value1.M11 + value2.M11; result.M12 = value1.M12 + value2.M12; result.M13 = value1.M13 + value2.M13; result.M14 = value1.M14 + value2.M14; result.M21 = value1.M21 + value2.M21; result.M22 = value1.M22 + value2.M22; result.M23 = value1.M23 + value2.M23; result.M24 = value1.M24 + value2.M24; result.M31 = value1.M31 + value2.M31; result.M32 = value1.M32 + value2.M32; result.M33 = value1.M33 + value2.M33; result.M34 = value1.M34 + value2.M34; result.M41 = value1.M41 + value2.M41; result.M42 = value1.M42 + value2.M42; result.M43 = value1.M43 + value2.M43; result.M44 = value1.M44 + value2.M44; return result; } public static Matrix4x4 Subtract(Matrix4x4 value1, Matrix4x4 value2) { Matrix4x4 result = default(Matrix4x4); result.M11 = value1.M11 - value2.M11; result.M12 = value1.M12 - value2.M12; result.M13 = value1.M13 - value2.M13; result.M14 = value1.M14 - value2.M14; result.M21 = value1.M21 - value2.M21; result.M22 = value1.M22 - value2.M22; result.M23 = value1.M23 - value2.M23; result.M24 = value1.M24 - value2.M24; result.M31 = value1.M31 - value2.M31; result.M32 = value1.M32 - value2.M32; result.M33 = value1.M33 - value2.M33; result.M34 = value1.M34 - value2.M34; result.M41 = value1.M41 - value2.M41; result.M42 = value1.M42 - value2.M42; result.M43 = value1.M43 - value2.M43; result.M44 = value1.M44 - value2.M44; return result; } public static Matrix4x4 Multiply(Matrix4x4 value1, Matrix4x4 value2) { Matrix4x4 result = default(Matrix4x4); result.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21 + value1.M13 * value2.M31 + value1.M14 * value2.M41; result.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22 + value1.M13 * value2.M32 + value1.M14 * value2.M42; result.M13 = value1.M11 * value2.M13 + value1.M12 * value2.M23 + value1.M13 * value2.M33 + value1.M14 * value2.M43; result.M14 = value1.M11 * value2.M14 + value1.M12 * value2.M24 + value1.M13 * value2.M34 + value1.M14 * value2.M44; result.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21 + value1.M23 * value2.M31 + value1.M24 * value2.M41; result.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22 + value1.M23 * value2.M32 + value1.M24 * value2.M42; result.M23 = value1.M21 * value2.M13 + value1.M22 * value2.M23 + value1.M23 * value2.M33 + value1.M24 * value2.M43; result.M24 = value1.M21 * value2.M14 + value1.M22 * value2.M24 + value1.M23 * value2.M34 + value1.M24 * value2.M44; result.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value1.M33 * value2.M31 + value1.M34 * value2.M41; result.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value1.M33 * value2.M32 + value1.M34 * value2.M42; result.M33 = value1.M31 * value2.M13 + value1.M32 * value2.M23 + value1.M33 * value2.M33 + value1.M34 * value2.M43; result.M34 = value1.M31 * value2.M14 + value1.M32 * value2.M24 + value1.M33 * value2.M34 + value1.M34 * value2.M44; result.M41 = value1.M41 * value2.M11 + value1.M42 * value2.M21 + value1.M43 * value2.M31 + value1.M44 * value2.M41; result.M42 = value1.M41 * value2.M12 + value1.M42 * value2.M22 + value1.M43 * value2.M32 + value1.M44 * value2.M42; result.M43 = value1.M41 * value2.M13 + value1.M42 * value2.M23 + value1.M43 * value2.M33 + value1.M44 * value2.M43; result.M44 = value1.M41 * value2.M14 + value1.M42 * value2.M24 + value1.M43 * value2.M34 + value1.M44 * value2.M44; return result; } public static Matrix4x4 Multiply(Matrix4x4 value1, float value2) { Matrix4x4 result = default(Matrix4x4); result.M11 = value1.M11 * value2; result.M12 = value1.M12 * value2; result.M13 = value1.M13 * value2; result.M14 = value1.M14 * value2; result.M21 = value1.M21 * value2; result.M22 = value1.M22 * value2; result.M23 = value1.M23 * value2; result.M24 = value1.M24 * value2; result.M31 = value1.M31 * value2; result.M32 = value1.M32 * value2; result.M33 = value1.M33 * value2; result.M34 = value1.M34 * value2; result.M41 = value1.M41 * value2; result.M42 = value1.M42 * value2; result.M43 = value1.M43 * value2; result.M44 = value1.M44 * value2; return result; } public static Matrix4x4 operator -(Matrix4x4 value) { Matrix4x4 result = default(Matrix4x4); result.M11 = 0f - value.M11; result.M12 = 0f - value.M12; result.M13 = 0f - value.M13; result.M14 = 0f - value.M14; result.M21 = 0f - value.M21; result.M22 = 0f - value.M22; result.M23 = 0f - value.M23; result.M24 = 0f - value.M24; result.M31 = 0f - value.M31; result.M32 = 0f - value.M32; result.M33 = 0f - value.M33; result.M34 = 0f - value.M34; result.M41 = 0f - value.M41; result.M42 = 0f - value.M42; result.M43 = 0f - value.M43; result.M44 = 0f - value.M44; return result; } public static Matrix4x4 operator +(Matrix4x4 value1, Matrix4x4 value2) { Matrix4x4 result = default(Matrix4x4); result.M11 = value1.M11 + value2.M11; result.M12 = value1.M12 + value2.M12; result.M13 = value1.M13 + value2.M13; result.M14 = value1.M14 + value2.M14; result.M21 = value1.M21 + value2.M21; result.M22 = value1.M22 + value2.M22; result.M23 = value1.M23 + value2.M23; result.M24 = value1.M24 + value2.M24; result.M31 = value1.M31 + value2.M31; result.M32 = value1.M32 + value2.M32; result.M33 = value1.M33 + value2.M33; result.M34 = value1.M34 + value2.M34; result.M41 = value1.M41 + value2.M41; result.M42 = value1.M42 + value2.M42; result.M43 = value1.M43 + value2.M43; result.M44 = value1.M44 + value2.M44; return result; } public static Matrix4x4 operator -(Matrix4x4 value1, Matrix4x4 value2) { Matrix4x4 result = default(Matrix4x4); result.M11 = value1.M11 - value2.M11; result.M12 = value1.M12 - value2.M12; result.M13 = value1.M13 - value2.M13; result.M14 = value1.M14 - value2.M14; result.M21 = value1.M21 - value2.M21; result.M22 = value1.M22 - value2.M22; result.M23 = value1.M23 - value2.M23; result.M24 = value1.M24 - value2.M24; result.M31 = value1.M31 - value2.M31; result.M32 = value1.M32 - value2.M32; result.M33 = value1.M33 - value2.M33; result.M34 = value1.M34 - value2.M34; result.M41 = value1.M41 - value2.M41; result.M42 = value1.M42 - value2.M42; result.M43 = value1.M43 - value2.M43; result.M44 = value1.M44 - value2.M44; return result; } public static Matrix4x4 operator *(Matrix4x4 value1, Matrix4x4 value2) { Matrix4x4 result = default(Matrix4x4); result.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21 + value1.M13 * value2.M31 + value1.M14 * value2.M41; result.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22 + value1.M13 * value2.M32 + value1.M14 * value2.M42; result.M13 = value1.M11 * value2.M13 + value1.M12 * value2.M23 + value1.M13 * value2.M33 + value1.M14 * value2.M43; result.M14 = value1.M11 * value2.M14 + value1.M12 * value2.M24 + value1.M13 * value2.M34 + value1.M14 * value2.M44; result.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21 + value1.M23 * value2.M31 + value1.M24 * value2.M41; result.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22 + value1.M23 * value2.M32 + value1.M24 * value2.M42; result.M23 = value1.M21 * value2.M13 + value1.M22 * value2.M23 + value1.M23 * value2.M33 + value1.M24 * value2.M43; result.M24 = value1.M21 * value2.M14 + value1.M22 * value2.M24 + value1.M23 * value2.M34 + value1.M24 * value2.M44; result.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value1.M33 * value2.M31 + value1.M34 * value2.M41; result.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value1.M33 * value2.M32 + value1.M34 * value2.M42; result.M33 = value1.M31 * value2.M13 + value1.M32 * value2.M23 + value1.M33 * value2.M33 + value1.M34 * value2.M43; result.M34 = value1.M31 * value2.M14 + value1.M32 * value2.M24 + value1.M33 * value2.M34 + value1.M34 * value2.M44; result.M41 = value1.M41 * value2.M11 + value1.M42 * value2.M21 + value1.M43 * value2.M31 + value1.M44 * value2.M41; result.M42 = value1.M41 * value2.M12 + value1.M42 * value2.M22 + value1.M43 * value2.M32 + value1.M44 * value2.M42; result.M43 = value1.M41 * value2.M13 + value1.M42 * value2.M23 + value1.M43 * value2.M33 + value1.M44 * value2.M43; result.M44 = value1.M41 * value2.M14 + value1.M42 * value2.M24 + value1.M43 * value2.M34 + value1.M44 * value2.M44; return result; } public static Matrix4x4 operator *(Matrix4x4 value1, float value2) { Matrix4x4 result = default(Matrix4x4); result.M11 = value1.M11 * value2; result.M12 = value1.M12 * value2; result.M13 = value1.M13 * value2; result.M14 = value1.M14 * value2; result.M21 = value1.M21 * value2; result.M22 = value1.M22 * value2; result.M23 = value1.M23 * value2; result.M24 = value1.M24 * value2; result.M31 = value1.M31 * value2; result.M32 = value1.M32 * value2; result.M33 = value1.M33 * value2; result.M34 = value1.M34 * value2; result.M41 = value1.M41 * value2; result.M42 = value1.M42 * value2; result.M43 = value1.M43 * value2; result.M44 = value1.M44 * value2; return result; } public static bool operator ==(Matrix4x4 value1, Matrix4x4 value2) { if (value1.M11 == value2.M11 && value1.M22 == value2.M22 && value1.M33 == value2.M33 && value1.M44 == value2.M44 && value1.M12 == value2.M12 && value1.M13 == value2.M13 && value1.M14 == value2.M14 && value1.M21 == value2.M21 && value1.M23 == value2.M23 && value1.M24 == value2.M24 && value1.M31 == value2.M31 && value1.M32 == value2.M32 && value1.M34 == value2.M34 && value1.M41 == value2.M41 && value1.M42 == value2.M42) { return value1.M43 == value2.M43; } return false; } public static bool operator !=(Matrix4x4 value1, Matrix4x4 value2) { if (value1.M11 == value2.M11 && value1.M12 == value2.M12 && value1.M13 == value2.M13 && value1.M14 == value2.M14 && value1.M21 == value2.M21 && value1.M22 == value2.M22 && value1.M23 == value2.M23 && value1.M24 == value2.M24 && value1.M31 == value2.M31 && value1.M32 == value2.M32 && value1.M33 == value2.M33 && value1.M34 == value2.M34 && value1.M41 == value2.M41 && value1.M42 == value2.M42 && value1.M43 == value2.M43) { return value1.M44 != value2.M44; } return true; } public bool Equals(Matrix4x4 other) { if (M11 == other.M11 && M22 == other.M22 && M33 == other.M33 && M44 == other.M44 && M12 == other.M12 && M13 == other.M13 && M14 == other.M14 && M21 == other.M21 && M23 == other.M23 && M24 == other.M24 && M31 == other.M31 && M32 == other.M32 && M34 == other.M34 && M41 == other.M41 && M42 == other.M42) { return M43 == other.M43; } return false; } public override bool Equals(object obj) { if (obj is Matrix4x4) { return Equals((Matrix4x4)obj); } return false; } public override string ToString() { CultureInfo currentCulture = CultureInfo.CurrentCulture; return string.Format(currentCulture, "{{ {{M11:{0} M12:{1} M13:{2} M14:{3}}} {{M21:{4} M22:{5} M23:{6} M24:{7}}} {{M31:{8} M32:{9} M33:{10} M34:{11}}} {{M41:{12} M42:{13} M43:{14} M44:{15}}} }}", M11.ToString(currentCulture), M12.ToString(currentCulture), M13.ToString(currentCulture), M14.ToString(currentCulture), M21.ToString(currentCulture), M22.ToString(currentCulture), M23.ToString(currentCulture), M24.ToString(currentCulture), M31.ToString(currentCulture), M32.ToString(currentCulture), M33.ToString(currentCulture), M34.ToString(currentCulture), M41.ToString(currentCulture), M42.ToString(currentCulture), M43.ToString(currentCulture), M44.ToString(currentCulture)); } public override int GetHashCode() { return M11.GetHashCode() + M12.GetHashCode() + M13.GetHashCode() + M14.GetHashCode() + M21.GetHashCode() + M22.GetHashCode() + M23.GetHashCode() + M24.GetHashCode() + M31.GetHashCode() + M32.GetHashCode() + M33.GetHashCode() + M34.GetHashCode() + M41.GetHashCode() + M42.GetHashCode() + M43.GetHashCode() + M44.GetHashCode(); } } internal struct Plane : IEquatable { public Vector3 Normal; public float D; public Plane(float x, float y, float z, float d) { Normal = new Vector3(x, y, z); D = d; } public Plane(Vector3 normal, float d) { Normal = normal; D = d; } public Plane(Vector4 value) { Normal = new Vector3(value.X, value.Y, value.Z); D = value.W; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane CreateFromVertices(Vector3 point1, Vector3 point2, Vector3 point3) { if (Vector.IsHardwareAccelerated) { Vector3 vector = point2 - point1; Vector3 vector2 = point3 - point1; Vector3 value = Vector3.Cross(vector, vector2); Vector3 vector3 = Vector3.Normalize(value); float d = 0f - Vector3.Dot(vector3, point1); return new Plane(vector3, d); } float num = point2.X - point1.X; float num2 = point2.Y - point1.Y; float num3 = point2.Z - point1.Z; float num4 = point3.X - point1.X; float num5 = point3.Y - point1.Y; float num6 = point3.Z - point1.Z; float num7 = num2 * num6 - num3 * num5; float num8 = num3 * num4 - num * num6; float num9 = num * num5 - num2 * num4; float x = num7 * num7 + num8 * num8 + num9 * num9; float num10 = 1f / MathF.Sqrt(x); Vector3 normal = new Vector3(num7 * num10, num8 * num10, num9 * num10); return new Plane(normal, 0f - (normal.X * point1.X + normal.Y * point1.Y + normal.Z * point1.Z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane Normalize(Plane value) { if (Vector.IsHardwareAccelerated) { float num = value.Normal.LengthSquared(); if (MathF.Abs(num - 1f) < 1.1920929E-07f) { return value; } float num2 = MathF.Sqrt(num); return new Plane(value.Normal / num2, value.D / num2); } float num3 = value.Normal.X * value.Normal.X + value.Normal.Y * value.Normal.Y + value.Normal.Z * value.Normal.Z; if (MathF.Abs(num3 - 1f) < 1.1920929E-07f) { return value; } float num4 = 1f / MathF.Sqrt(num3); return new Plane(value.Normal.X * num4, value.Normal.Y * num4, value.Normal.Z * num4, value.D * num4); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane Transform(Plane plane, Matrix4x4 matrix) { Matrix4x4.Invert(matrix, out var result); float x = plane.Normal.X; float y = plane.Normal.Y; float z = plane.Normal.Z; float d = plane.D; return new Plane(x * result.M11 + y * result.M12 + z * result.M13 + d * result.M14, x * result.M21 + y * result.M22 + z * result.M23 + d * result.M24, x * result.M31 + y * result.M32 + z * result.M33 + d * result.M34, x * result.M41 + y * result.M42 + z * result.M43 + d * result.M44); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane Transform(Plane plane, Quaternion rotation) { float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num; float num5 = rotation.W * num2; float num6 = rotation.W * num3; float num7 = rotation.X * num; float num8 = rotation.X * num2; float num9 = rotation.X * num3; float num10 = rotation.Y * num2; float num11 = rotation.Y * num3; float num12 = rotation.Z * num3; float num13 = 1f - num10 - num12; float num14 = num8 - num6; float num15 = num9 + num5; float num16 = num8 + num6; float num17 = 1f - num7 - num12; float num18 = num11 - num4; float num19 = num9 - num5; float num20 = num11 + num4; float num21 = 1f - num7 - num10; float x = plane.Normal.X; float y = plane.Normal.Y; float z = plane.Normal.Z; return new Plane(x * num13 + y * num14 + z * num15, x * num16 + y * num17 + z * num18, x * num19 + y * num20 + z * num21, plane.D); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Dot(Plane plane, Vector4 value) { return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z + plane.D * value.W; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DotCoordinate(Plane plane, Vector3 value) { if (Vector.IsHardwareAccelerated) { return Vector3.Dot(plane.Normal, value) + plane.D; } return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z + plane.D; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DotNormal(Plane plane, Vector3 value) { if (Vector.IsHardwareAccelerated) { return Vector3.Dot(plane.Normal, value); } return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Plane value1, Plane value2) { if (value1.Normal.X == value2.Normal.X && value1.Normal.Y == value2.Normal.Y && value1.Normal.Z == value2.Normal.Z) { return value1.D == value2.D; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Plane value1, Plane value2) { if (value1.Normal.X == value2.Normal.X && value1.Normal.Y == value2.Normal.Y && value1.Normal.Z == value2.Normal.Z) { return value1.D != value2.D; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Plane other) { if (Vector.IsHardwareAccelerated) { if (Normal.Equals(other.Normal)) { return D == other.D; } return false; } if (Normal.X == other.Normal.X && Normal.Y == other.Normal.Y && Normal.Z == other.Normal.Z) { return D == other.D; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { if (obj is Plane) { return Equals((Plane)obj); } return false; } public override string ToString() { CultureInfo currentCulture = CultureInfo.CurrentCulture; return string.Format(currentCulture, "{{Normal:{0} D:{1}}}", Normal.ToString(), D.ToString(currentCulture)); } public override int GetHashCode() { return Normal.GetHashCode() + D.GetHashCode(); } } internal struct Quaternion : IEquatable { public float X; public float Y; public float Z; public float W; public static Quaternion Identity => new Quaternion(0f, 0f, 0f, 1f); public bool IsIdentity { get { if (X == 0f && Y == 0f && Z == 0f) { return W == 1f; } return false; } } public Quaternion(float x, float y, float z, float w) { X = x; Y = y; Z = z; W = w; } public Quaternion(Vector3 vectorPart, float scalarPart) { X = vectorPart.X; Y = vectorPart.Y; Z = vectorPart.Z; W = scalarPart; } public float Length() { float x = X * X + Y * Y + Z * Z + W * W; return MathF.Sqrt(x); } public float LengthSquared() { return X * X + Y * Y + Z * Z + W * W; } public static Quaternion Normalize(Quaternion value) { float x = value.X * value.X + value.Y * value.Y + value.Z * value.Z + value.W * value.W; float num = 1f / MathF.Sqrt(x); Quaternion result = default(Quaternion); result.X = value.X * num; result.Y = value.Y * num; result.Z = value.Z * num; result.W = value.W * num; return result; } public static Quaternion Conjugate(Quaternion value) { Quaternion result = default(Quaternion); result.X = 0f - value.X; result.Y = 0f - value.Y; result.Z = 0f - value.Z; result.W = value.W; return result; } public static Quaternion Inverse(Quaternion value) { float num = value.X * value.X + value.Y * value.Y + value.Z * value.Z + value.W * value.W; float num2 = 1f / num; Quaternion result = default(Quaternion); result.X = (0f - value.X) * num2; result.Y = (0f - value.Y) * num2; result.Z = (0f - value.Z) * num2; result.W = value.W * num2; return result; } public static Quaternion CreateFromAxisAngle(Vector3 axis, float angle) { float x = angle * 0.5f; float num = MathF.Sin(x); float w = MathF.Cos(x); Quaternion result = default(Quaternion); result.X = axis.X * num; result.Y = axis.Y * num; result.Z = axis.Z * num; result.W = w; return result; } public static Quaternion CreateFromYawPitchRoll(float yaw, float pitch, float roll) { float x = roll * 0.5f; float num = MathF.Sin(x); float num2 = MathF.Cos(x); float x2 = pitch * 0.5f; float num3 = MathF.Sin(x2); float num4 = MathF.Cos(x2); float x3 = yaw * 0.5f; float num5 = MathF.Sin(x3); float num6 = MathF.Cos(x3); Quaternion result = default(Quaternion); result.X = num6 * num3 * num2 + num5 * num4 * num; result.Y = num5 * num4 * num2 - num6 * num3 * num; result.Z = num6 * num4 * num - num5 * num3 * num2; result.W = num6 * num4 * num2 + num5 * num3 * num; return result; } public static Quaternion CreateFromRotationMatrix(Matrix4x4 matrix) { float num = matrix.M11 + matrix.M22 + matrix.M33; Quaternion result = default(Quaternion); if (num > 0f) { float num2 = MathF.Sqrt(num + 1f); result.W = num2 * 0.5f; num2 = 0.5f / num2; result.X = (matrix.M23 - matrix.M32) * num2; result.Y = (matrix.M31 - matrix.M13) * num2; result.Z = (matrix.M12 - matrix.M21) * num2; } else if (matrix.M11 >= matrix.M22 && matrix.M11 >= matrix.M33) { float num3 = MathF.Sqrt(1f + matrix.M11 - matrix.M22 - matrix.M33); float num4 = 0.5f / num3; result.X = 0.5f * num3; result.Y = (matrix.M12 + matrix.M21) * num4; result.Z = (matrix.M13 + matrix.M31) * num4; result.W = (matrix.M23 - matrix.M32) * num4; } else if (matrix.M22 > matrix.M33) { float num5 = MathF.Sqrt(1f + matrix.M22 - matrix.M11 - matrix.M33); float num6 = 0.5f / num5; result.X = (matrix.M21 + matrix.M12) * num6; result.Y = 0.5f * num5; result.Z = (matrix.M32 + matrix.M23) * num6; result.W = (matrix.M31 - matrix.M13) * num6; } else { float num7 = MathF.Sqrt(1f + matrix.M33 - matrix.M11 - matrix.M22); float num8 = 0.5f / num7; result.X = (matrix.M31 + matrix.M13) * num8; result.Y = (matrix.M32 + matrix.M23) * num8; result.Z = 0.5f * num7; result.W = (matrix.M12 - matrix.M21) * num8; } return result; } public static float Dot(Quaternion quaternion1, Quaternion quaternion2) { return quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y + quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W; } public static Quaternion Slerp(Quaternion quaternion1, Quaternion quaternion2, float amount) { float num = quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y + quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W; bool flag = false; if (num < 0f) { flag = true; num = 0f - num; } float num2; float num3; if (num > 0.999999f) { num2 = 1f - amount; num3 = (flag ? (0f - amount) : amount); } else { float num4 = MathF.Acos(num); float num5 = 1f / MathF.Sin(num4); num2 = MathF.Sin((1f - amount) * num4) * num5; num3 = (flag ? ((0f - MathF.Sin(amount * num4)) * num5) : (MathF.Sin(amount * num4) * num5)); } Quaternion result = default(Quaternion); result.X = num2 * quaternion1.X + num3 * quaternion2.X; result.Y = num2 * quaternion1.Y + num3 * quaternion2.Y; result.Z = num2 * quaternion1.Z + num3 * quaternion2.Z; result.W = num2 * quaternion1.W + num3 * quaternion2.W; return result; } public static Quaternion Lerp(Quaternion quaternion1, Quaternion quaternion2, float amount) { float num = 1f - amount; Quaternion result = default(Quaternion); float num2 = quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y + quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W; if (num2 >= 0f) { result.X = num * quaternion1.X + amount * quaternion2.X; result.Y = num * quaternion1.Y + amount * quaternion2.Y; result.Z = num * quaternion1.Z + amount * quaternion2.Z; result.W = num * quaternion1.W + amount * quaternion2.W; } else { result.X = num * quaternion1.X - amount * quaternion2.X; result.Y = num * quaternion1.Y - amount * quaternion2.Y; result.Z = num * quaternion1.Z - amount * quaternion2.Z; result.W = num * quaternion1.W - amount * quaternion2.W; } float x = result.X * result.X + result.Y * result.Y + result.Z * result.Z + result.W * result.W; float num3 = 1f / MathF.Sqrt(x); result.X *= num3; result.Y *= num3; result.Z *= num3; result.W *= num3; return result; } public static Quaternion Concatenate(Quaternion value1, Quaternion value2) { float x = value2.X; float y = value2.Y; float z = value2.Z; float w = value2.W; float x2 = value1.X; float y2 = value1.Y; float z2 = value1.Z; float w2 = value1.W; float num = y * z2 - z * y2; float num2 = z * x2 - x * z2; float num3 = x * y2 - y * x2; float num4 = x * x2 + y * y2 + z * z2; Quaternion result = default(Quaternion); result.X = x * w2 + x2 * w + num; result.Y = y * w2 + y2 * w + num2; result.Z = z * w2 + z2 * w + num3; result.W = w * w2 - num4; return result; } public static Quaternion Negate(Quaternion value) { Quaternion result = default(Quaternion); result.X = 0f - value.X; result.Y = 0f - value.Y; result.Z = 0f - value.Z; result.W = 0f - value.W; return result; } public static Quaternion Add(Quaternion value1, Quaternion value2) { Quaternion result = default(Quaternion); result.X = value1.X + value2.X; result.Y = value1.Y + value2.Y; result.Z = value1.Z + value2.Z; result.W = value1.W + value2.W; return result; } public static Quaternion Subtract(Quaternion value1, Quaternion value2) { Quaternion result = default(Quaternion); result.X = value1.X - value2.X; result.Y = value1.Y - value2.Y; result.Z = value1.Z - value2.Z; result.W = value1.W - value2.W; return result; } public static Quaternion Multiply(Quaternion value1, Quaternion value2) { float x = value1.X; float y = value1.Y; float z = value1.Z; float w = value1.W; float x2 = value2.X; float y2 = value2.Y; float z2 = value2.Z; float w2 = value2.W; float num = y * z2 - z * y2; float num2 = z * x2 - x * z2; float num3 = x * y2 - y * x2; float num4 = x * x2 + y * y2 + z * z2; Quaternion result = default(Quaternion); result.X = x * w2 + x2 * w + num; result.Y = y * w2 + y2 * w + num2; result.Z = z * w2 + z2 * w + num3; result.W = w * w2 - num4; return result; } public static Quaternion Multiply(Quaternion value1, float value2) { Quaternion result = default(Quaternion); result.X = value1.X * value2; result.Y = value1.Y * value2; result.Z = value1.Z * value2; result.W = value1.W * value2; return result; } public static Quaternion Divide(Quaternion value1, Quaternion value2) { float x = value1.X; float y = value1.Y; float z = value1.Z; float w = value1.W; float num = value2.X * value2.X + value2.Y * value2.Y + value2.Z * value2.Z + value2.W * value2.W; float num2 = 1f / num; float num3 = (0f - value2.X) * num2; float num4 = (0f - value2.Y) * num2; float num5 = (0f - value2.Z) * num2; float num6 = value2.W * num2; float num7 = y * num5 - z * num4; float num8 = z * num3 - x * num5; float num9 = x * num4 - y * num3; float num10 = x * num3 + y * num4 + z * num5; Quaternion result = default(Quaternion); result.X = x * num6 + num3 * w + num7; result.Y = y * num6 + num4 * w + num8; result.Z = z * num6 + num5 * w + num9; result.W = w * num6 - num10; return result; } public static Quaternion operator -(Quaternion value) { Quaternion result = default(Quaternion); result.X = 0f - value.X; result.Y = 0f - value.Y; result.Z = 0f - value.Z; result.W = 0f - value.W; return result; } public static Quaternion operator +(Quaternion value1, Quaternion value2) { Quaternion result = default(Quaternion); result.X = value1.X + value2.X; result.Y = value1.Y + value2.Y; result.Z = value1.Z + value2.Z; result.W = value1.W + value2.W; return result; } public static Quaternion operator -(Quaternion value1, Quaternion value2) { Quaternion result = default(Quaternion); result.X = value1.X - value2.X; result.Y = value1.Y - value2.Y; result.Z = value1.Z - value2.Z; result.W = value1.W - value2.W; return result; } public static Quaternion operator *(Quaternion value1, Quaternion value2) { float x = value1.X; float y = value1.Y; float z = value1.Z; float w = value1.W; float x2 = value2.X; float y2 = value2.Y; float z2 = value2.Z; float w2 = value2.W; float num = y * z2 - z * y2; float num2 = z * x2 - x * z2; float num3 = x * y2 - y * x2; float num4 = x * x2 + y * y2 + z * z2; Quaternion result = default(Quaternion); result.X = x * w2 + x2 * w + num; result.Y = y * w2 + y2 * w + num2; result.Z = z * w2 + z2 * w + num3; result.W = w * w2 - num4; return result; } public static Quaternion operator *(Quaternion value1, float value2) { Quaternion result = default(Quaternion); result.X = value1.X * value2; result.Y = value1.Y * value2; result.Z = value1.Z * value2; result.W = value1.W * value2; return result; } public static Quaternion operator /(Quaternion value1, Quaternion value2) { float x = value1.X; float y = value1.Y; float z = value1.Z; float w = value1.W; float num = value2.X * value2.X + value2.Y * value2.Y + value2.Z * value2.Z + value2.W * value2.W; float num2 = 1f / num; float num3 = (0f - value2.X) * num2; float num4 = (0f - value2.Y) * num2; float num5 = (0f - value2.Z) * num2; float num6 = value2.W * num2; float num7 = y * num5 - z * num4; float num8 = z * num3 - x * num5; float num9 = x * num4 - y * num3; float num10 = x * num3 + y * num4 + z * num5; Quaternion result = default(Quaternion); result.X = x * num6 + num3 * w + num7; result.Y = y * num6 + num4 * w + num8; result.Z = z * num6 + num5 * w + num9; result.W = w * num6 - num10; return result; } public static bool operator ==(Quaternion value1, Quaternion value2) { if (value1.X == value2.X && value1.Y == value2.Y && value1.Z == value2.Z) { return value1.W == value2.W; } return false; } public static bool operator !=(Quaternion value1, Quaternion value2) { if (value1.X == value2.X && value1.Y == value2.Y && value1.Z == value2.Z) { return value1.W != value2.W; } return true; } public bool Equals(Quaternion other) { if (X == other.X && Y == other.Y && Z == other.Z) { return W == other.W; } return false; } public override bool Equals(object obj) { if (obj is Quaternion) { return Equals((Quaternion)obj); } return false; } public override string ToString() { CultureInfo currentCulture = CultureInfo.CurrentCulture; return string.Format(currentCulture, "{{X:{0} Y:{1} Z:{2} W:{3}}}", X.ToString(currentCulture), Y.ToString(currentCulture), Z.ToString(currentCulture), W.ToString(currentCulture)); } public override int GetHashCode() { return X.GetHashCode() + Y.GetHashCode() + Z.GetHashCode() + W.GetHashCode(); } } internal struct Vector2 : IEquatable, IFormattable { public float X; public float Y; public static Vector2 Zero => default(Vector2); public static Vector2 One => new Vector2(1f, 1f); public static Vector2 UnitX => new Vector2(1f, 0f); public static Vector2 UnitY => new Vector2(0f, 1f); public override int GetHashCode() { int hashCode = X.GetHashCode(); return HashHelpers.Combine(hashCode, Y.GetHashCode()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { if (!(obj is Vector2)) { return false; } return Equals((Vector2)obj); } 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('<'); stringBuilder.Append(X.ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); stringBuilder.Append(Y.ToString(format, formatProvider)); stringBuilder.Append('>'); return stringBuilder.ToString(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public float Length() { if (Vector.IsHardwareAccelerated) { float x = Dot(this, this); return MathF.Sqrt(x); } float x2 = X * X + Y * Y; return MathF.Sqrt(x2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public float LengthSquared() { if (Vector.IsHardwareAccelerated) { return Dot(this, this); } return X * X + Y * Y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector2 value1, Vector2 value2) { if (Vector.IsHardwareAccelerated) { Vector2 vector = value1 - value2; float x = Dot(vector, vector); return MathF.Sqrt(x); } float num = value1.X - value2.X; float num2 = value1.Y - value2.Y; float x2 = num * num + num2 * num2; return MathF.Sqrt(x2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DistanceSquared(Vector2 value1, Vector2 value2) { if (Vector.IsHardwareAccelerated) { Vector2 vector = value1 - value2; return Dot(vector, vector); } float num = value1.X - value2.X; float num2 = value1.Y - value2.Y; return num * num + num2 * num2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Normalize(Vector2 value) { if (Vector.IsHardwareAccelerated) { float num = value.Length(); return value / num; } float x = value.X * value.X + value.Y * value.Y; float num2 = 1f / MathF.Sqrt(x); return new Vector2(value.X * num2, value.Y * num2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Reflect(Vector2 vector, Vector2 normal) { if (Vector.IsHardwareAccelerated) { float num = Dot(vector, normal); return vector - 2f * num * normal; } float num2 = vector.X * normal.X + vector.Y * normal.Y; return new Vector2(vector.X - 2f * num2 * normal.X, vector.Y - 2f * num2 * normal.Y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Clamp(Vector2 value1, Vector2 min, Vector2 max) { float x = value1.X; x = ((x > max.X) ? max.X : x); x = ((x < min.X) ? min.X : x); float y = value1.Y; y = ((y > max.Y) ? max.Y : y); y = ((y < min.Y) ? min.Y : y); return new Vector2(x, y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Lerp(Vector2 value1, Vector2 value2, float amount) { return new Vector2(value1.X + (value2.X - value1.X) * amount, value1.Y + (value2.Y - value1.Y) * amount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Transform(Vector2 position, Matrix3x2 matrix) { return new Vector2(position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M31, position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M32); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Transform(Vector2 position, Matrix4x4 matrix) { return new Vector2(position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M41, position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M42); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 TransformNormal(Vector2 normal, Matrix3x2 matrix) { return new Vector2(normal.X * matrix.M11 + normal.Y * matrix.M21, normal.X * matrix.M12 + normal.Y * matrix.M22); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 TransformNormal(Vector2 normal, Matrix4x4 matrix) { return new Vector2(normal.X * matrix.M11 + normal.Y * matrix.M21, normal.X * matrix.M12 + normal.Y * matrix.M22); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Transform(Vector2 value, Quaternion rotation) { float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num3; float num5 = rotation.X * num; float num6 = rotation.X * num2; float num7 = rotation.Y * num2; float num8 = rotation.Z * num3; return new Vector2(value.X * (1f - num7 - num8) + value.Y * (num6 - num4), value.X * (num6 + num4) + value.Y * (1f - num5 - num8)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Add(Vector2 left, Vector2 right) { return left + right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Subtract(Vector2 left, Vector2 right) { return left - right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Multiply(Vector2 left, Vector2 right) { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Multiply(Vector2 left, float right) { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Multiply(float left, Vector2 right) { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Divide(Vector2 left, Vector2 right) { return left / right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Divide(Vector2 left, float divisor) { return left / divisor; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Negate(Vector2 value) { return -value; } [System.Runtime.CompilerServices.Intrinsic] public Vector2(float value) : this(value, value) { } [System.Runtime.CompilerServices.Intrinsic] public Vector2(float x, float y) { X = x; Y = y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(float[] array) { CopyTo(array, 0); } public void CopyTo(float[] array, int index) { if (array == null) { throw new NullReferenceException(SR.Arg_NullArgumentNullRef); } if (index < 0 || index >= array.Length) { throw new ArgumentOutOfRangeException("index", SR.Format(SR.Arg_ArgumentOutOfRangeException, index)); } if (array.Length - index < 2) { throw new ArgumentException(SR.Format(SR.Arg_ElementsInSourceIsGreaterThanDestination, index)); } array[index] = X; array[index + 1] = Y; } [System.Runtime.CompilerServices.Intrinsic] public bool Equals(Vector2 other) { if (X == other.X) { return Y == other.Y; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static float Dot(Vector2 value1, Vector2 value2) { return value1.X * value2.X + value1.Y * value2.Y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector2 Min(Vector2 value1, Vector2 value2) { return new Vector2((value1.X < value2.X) ? value1.X : value2.X, (value1.Y < value2.Y) ? value1.Y : value2.Y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector2 Max(Vector2 value1, Vector2 value2) { return new Vector2((value1.X > value2.X) ? value1.X : value2.X, (value1.Y > value2.Y) ? value1.Y : value2.Y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector2 Abs(Vector2 value) { return new Vector2(MathF.Abs(value.X), MathF.Abs(value.Y)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector2 SquareRoot(Vector2 value) { return new Vector2(MathF.Sqrt(value.X), MathF.Sqrt(value.Y)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector2 operator +(Vector2 left, Vector2 right) { return new Vector2(left.X + right.X, left.Y + right.Y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector2 operator -(Vector2 left, Vector2 right) { return new Vector2(left.X - right.X, left.Y - right.Y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector2 operator *(Vector2 left, Vector2 right) { return new Vector2(left.X * right.X, left.Y * right.Y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector2 operator *(float left, Vector2 right) { return new Vector2(left, left) * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector2 operator *(Vector2 left, float right) { return left * new Vector2(right, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector2 operator /(Vector2 left, Vector2 right) { return new Vector2(left.X / right.X, left.Y / right.Y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator /(Vector2 value1, float value2) { return value1 / new Vector2(value2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator -(Vector2 value) { return Zero - value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Vector2 left, Vector2 right) { return left.Equals(right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Vector2 left, Vector2 right) { return !(left == right); } } internal struct Vector3 : IEquatable, IFormattable { public float X; public float Y; public float Z; public static Vector3 Zero => default(Vector3); public static Vector3 One => new Vector3(1f, 1f, 1f); public static Vector3 UnitX => new Vector3(1f, 0f, 0f); public static Vector3 UnitY => new Vector3(0f, 1f, 0f); public static Vector3 UnitZ => new Vector3(0f, 0f, 1f); public override int GetHashCode() { int hashCode = X.GetHashCode(); hashCode = HashHelpers.Combine(hashCode, Y.GetHashCode()); return HashHelpers.Combine(hashCode, Z.GetHashCode()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { if (!(obj is Vector3)) { return false; } return Equals((Vector3)obj); } 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('<'); stringBuilder.Append(((IFormattable)X).ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); stringBuilder.Append(((IFormattable)Y).ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); stringBuilder.Append(((IFormattable)Z).ToString(format, formatProvider)); stringBuilder.Append('>'); return stringBuilder.ToString(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public float Length() { if (Vector.IsHardwareAccelerated) { float x = Dot(this, this); return MathF.Sqrt(x); } float x2 = X * X + Y * Y + Z * Z; return MathF.Sqrt(x2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public float LengthSquared() { if (Vector.IsHardwareAccelerated) { return Dot(this, this); } return X * X + Y * Y + Z * Z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector3 value1, Vector3 value2) { if (Vector.IsHardwareAccelerated) { Vector3 vector = value1 - value2; float x = Dot(vector, vector); return MathF.Sqrt(x); } float num = value1.X - value2.X; float num2 = value1.Y - value2.Y; float num3 = value1.Z - value2.Z; float x2 = num * num + num2 * num2 + num3 * num3; return MathF.Sqrt(x2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DistanceSquared(Vector3 value1, Vector3 value2) { if (Vector.IsHardwareAccelerated) { Vector3 vector = value1 - value2; return Dot(vector, vector); } float num = value1.X - value2.X; float num2 = value1.Y - value2.Y; float num3 = value1.Z - value2.Z; return num * num + num2 * num2 + num3 * num3; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Normalize(Vector3 value) { if (Vector.IsHardwareAccelerated) { float num = value.Length(); return value / num; } float x = value.X * value.X + value.Y * value.Y + value.Z * value.Z; float num2 = MathF.Sqrt(x); return new Vector3(value.X / num2, value.Y / num2, value.Z / num2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Cross(Vector3 vector1, Vector3 vector2) { return new Vector3(vector1.Y * vector2.Z - vector1.Z * vector2.Y, vector1.Z * vector2.X - vector1.X * vector2.Z, vector1.X * vector2.Y - vector1.Y * vector2.X); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Reflect(Vector3 vector, Vector3 normal) { if (Vector.IsHardwareAccelerated) { float num = Dot(vector, normal); Vector3 vector2 = normal * num * 2f; return vector - vector2; } float num2 = vector.X * normal.X + vector.Y * normal.Y + vector.Z * normal.Z; float num3 = normal.X * num2 * 2f; float num4 = normal.Y * num2 * 2f; float num5 = normal.Z * num2 * 2f; return new Vector3(vector.X - num3, vector.Y - num4, vector.Z - num5); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max) { float x = value1.X; x = ((x > max.X) ? max.X : x); x = ((x < min.X) ? min.X : x); float y = value1.Y; y = ((y > max.Y) ? max.Y : y); y = ((y < min.Y) ? min.Y : y); float z = value1.Z; z = ((z > max.Z) ? max.Z : z); z = ((z < min.Z) ? min.Z : z); return new Vector3(x, y, z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Lerp(Vector3 value1, Vector3 value2, float amount) { if (Vector.IsHardwareAccelerated) { Vector3 vector = value1 * (1f - amount); Vector3 vector2 = value2 * amount; return vector + vector2; } return new Vector3(value1.X + (value2.X - value1.X) * amount, value1.Y + (value2.Y - value1.Y) * amount, value1.Z + (value2.Z - value1.Z) * amount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Transform(Vector3 position, Matrix4x4 matrix) { return new Vector3(position.X * matrix.M11 + position.Y * matrix.M21 + position.Z * matrix.M31 + matrix.M41, position.X * matrix.M12 + position.Y * matrix.M22 + position.Z * matrix.M32 + matrix.M42, position.X * matrix.M13 + position.Y * matrix.M23 + position.Z * matrix.M33 + matrix.M43); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 TransformNormal(Vector3 normal, Matrix4x4 matrix) { return new Vector3(normal.X * matrix.M11 + normal.Y * matrix.M21 + normal.Z * matrix.M31, normal.X * matrix.M12 + normal.Y * matrix.M22 + normal.Z * matrix.M32, normal.X * matrix.M13 + normal.Y * matrix.M23 + normal.Z * matrix.M33); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Transform(Vector3 value, Quaternion rotation) { float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num; float num5 = rotation.W * num2; float num6 = rotation.W * num3; float num7 = rotation.X * num; float num8 = rotation.X * num2; float num9 = rotation.X * num3; float num10 = rotation.Y * num2; float num11 = rotation.Y * num3; float num12 = rotation.Z * num3; return new Vector3(value.X * (1f - num10 - num12) + value.Y * (num8 - num6) + value.Z * (num9 + num5), value.X * (num8 + num6) + value.Y * (1f - num7 - num12) + value.Z * (num11 - num4), value.X * (num9 - num5) + value.Y * (num11 + num4) + value.Z * (1f - num7 - num10)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Add(Vector3 left, Vector3 right) { return left + right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Subtract(Vector3 left, Vector3 right) { return left - right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Multiply(Vector3 left, Vector3 right) { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Multiply(Vector3 left, float right) { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Multiply(float left, Vector3 right) { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Divide(Vector3 left, Vector3 right) { return left / right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Divide(Vector3 left, float divisor) { return left / divisor; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Negate(Vector3 value) { return -value; } [System.Runtime.CompilerServices.Intrinsic] public Vector3(float value) : this(value, value, value) { } public Vector3(Vector2 value, float z) : this(value.X, value.Y, z) { } [System.Runtime.CompilerServices.Intrinsic] public Vector3(float x, float y, float z) { X = x; Y = y; Z = z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(float[] array) { CopyTo(array, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public void CopyTo(float[] array, int index) { if (array == null) { throw new NullReferenceException(SR.Arg_NullArgumentNullRef); } if (index < 0 || index >= array.Length) { throw new ArgumentOutOfRangeException("index", SR.Format(SR.Arg_ArgumentOutOfRangeException, index)); } if (array.Length - index < 3) { throw new ArgumentException(SR.Format(SR.Arg_ElementsInSourceIsGreaterThanDestination, index)); } array[index] = X; array[index + 1] = Y; array[index + 2] = Z; } [System.Runtime.CompilerServices.Intrinsic] public bool Equals(Vector3 other) { if (X == other.X && Y == other.Y) { return Z == other.Z; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static float Dot(Vector3 vector1, Vector3 vector2) { return vector1.X * vector2.X + vector1.Y * vector2.Y + vector1.Z * vector2.Z; } [System.Runtime.CompilerServices.Intrinsic] public static Vector3 Min(Vector3 value1, Vector3 value2) { return new Vector3((value1.X < value2.X) ? value1.X : value2.X, (value1.Y < value2.Y) ? value1.Y : value2.Y, (value1.Z < value2.Z) ? value1.Z : value2.Z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector3 Max(Vector3 value1, Vector3 value2) { return new Vector3((value1.X > value2.X) ? value1.X : value2.X, (value1.Y > value2.Y) ? value1.Y : value2.Y, (value1.Z > value2.Z) ? value1.Z : value2.Z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector3 Abs(Vector3 value) { return new Vector3(MathF.Abs(value.X), MathF.Abs(value.Y), MathF.Abs(value.Z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector3 SquareRoot(Vector3 value) { return new Vector3(MathF.Sqrt(value.X), MathF.Sqrt(value.Y), MathF.Sqrt(value.Z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector3 operator +(Vector3 left, Vector3 right) { return new Vector3(left.X + right.X, left.Y + right.Y, left.Z + right.Z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector3 operator -(Vector3 left, Vector3 right) { return new Vector3(left.X - right.X, left.Y - right.Y, left.Z - right.Z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector3 operator *(Vector3 left, Vector3 right) { return new Vector3(left.X * right.X, left.Y * right.Y, left.Z * right.Z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector3 operator *(Vector3 left, float right) { return left * new Vector3(right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector3 operator *(float left, Vector3 right) { return new Vector3(left) * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector3 operator /(Vector3 left, Vector3 right) { return new Vector3(left.X / right.X, left.Y / right.Y, left.Z / right.Z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator /(Vector3 value1, float value2) { return value1 / new Vector3(value2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator -(Vector3 value) { return Zero - value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static bool operator ==(Vector3 left, Vector3 right) { if (left.X == right.X && left.Y == right.Y) { return left.Z == right.Z; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Vector3 left, Vector3 right) { if (left.X == right.X && left.Y == right.Y) { return left.Z != right.Z; } return true; } } internal struct Vector4 : IEquatable, IFormattable { public float X; public float Y; public float Z; public float W; public static Vector4 Zero => default(Vector4); public static Vector4 One => new Vector4(1f, 1f, 1f, 1f); public static Vector4 UnitX => new Vector4(1f, 0f, 0f, 0f); public static Vector4 UnitY => new Vector4(0f, 1f, 0f, 0f); public static Vector4 UnitZ => new Vector4(0f, 0f, 1f, 0f); public static Vector4 UnitW => new Vector4(0f, 0f, 0f, 1f); public override int GetHashCode() { int hashCode = X.GetHashCode(); hashCode = HashHelpers.Combine(hashCode, Y.GetHashCode()); hashCode = HashHelpers.Combine(hashCode, Z.GetHashCode()); return HashHelpers.Combine(hashCode, W.GetHashCode()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { if (!(obj is Vector4)) { return false; } return Equals((Vector4)obj); } 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('<'); stringBuilder.Append(X.ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); stringBuilder.Append(Y.ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); stringBuilder.Append(Z.ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); stringBuilder.Append(W.ToString(format, formatProvider)); stringBuilder.Append('>'); return stringBuilder.ToString(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public float Length() { if (Vector.IsHardwareAccelerated) { float x = Dot(this, this); return MathF.Sqrt(x); } float x2 = X * X + Y * Y + Z * Z + W * W; return MathF.Sqrt(x2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public float LengthSquared() { if (Vector.IsHardwareAccelerated) { return Dot(this, this); } return X * X + Y * Y + Z * Z + W * W; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector4 value1, Vector4 value2) { if (Vector.IsHardwareAccelerated) { Vector4 vector = value1 - value2; float x = Dot(vector, vector); return MathF.Sqrt(x); } float num = value1.X - value2.X; float num2 = value1.Y - value2.Y; float num3 = value1.Z - value2.Z; float num4 = value1.W - value2.W; float x2 = num * num + num2 * num2 + num3 * num3 + num4 * num4; return MathF.Sqrt(x2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DistanceSquared(Vector4 value1, Vector4 value2) { if (Vector.IsHardwareAccelerated) { Vector4 vector = value1 - value2; return Dot(vector, vector); } float num = value1.X - value2.X; float num2 = value1.Y - value2.Y; float num3 = value1.Z - value2.Z; float num4 = value1.W - value2.W; return num * num + num2 * num2 + num3 * num3 + num4 * num4; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Normalize(Vector4 vector) { if (Vector.IsHardwareAccelerated) { float num = vector.Length(); return vector / num; } float x = vector.X * vector.X + vector.Y * vector.Y + vector.Z * vector.Z + vector.W * vector.W; float num2 = 1f / MathF.Sqrt(x); return new Vector4(vector.X * num2, vector.Y * num2, vector.Z * num2, vector.W * num2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Clamp(Vector4 value1, Vector4 min, Vector4 max) { float x = value1.X; x = ((x > max.X) ? max.X : x); x = ((x < min.X) ? min.X : x); float y = value1.Y; y = ((y > max.Y) ? max.Y : y); y = ((y < min.Y) ? min.Y : y); float z = value1.Z; z = ((z > max.Z) ? max.Z : z); z = ((z < min.Z) ? min.Z : z); float w = value1.W; w = ((w > max.W) ? max.W : w); w = ((w < min.W) ? min.W : w); return new Vector4(x, y, z, w); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Lerp(Vector4 value1, Vector4 value2, float amount) { return new Vector4(value1.X + (value2.X - value1.X) * amount, value1.Y + (value2.Y - value1.Y) * amount, value1.Z + (value2.Z - value1.Z) * amount, value1.W + (value2.W - value1.W) * amount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector2 position, Matrix4x4 matrix) { return new Vector4(position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M41, position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M42, position.X * matrix.M13 + position.Y * matrix.M23 + matrix.M43, position.X * matrix.M14 + position.Y * matrix.M24 + matrix.M44); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector3 position, Matrix4x4 matrix) { return new Vector4(position.X * matrix.M11 + position.Y * matrix.M21 + position.Z * matrix.M31 + matrix.M41, position.X * matrix.M12 + position.Y * matrix.M22 + position.Z * matrix.M32 + matrix.M42, position.X * matrix.M13 + position.Y * matrix.M23 + position.Z * matrix.M33 + matrix.M43, position.X * matrix.M14 + position.Y * matrix.M24 + position.Z * matrix.M34 + matrix.M44); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector4 vector, Matrix4x4 matrix) { return new Vector4(vector.X * matrix.M11 + vector.Y * matrix.M21 + vector.Z * matrix.M31 + vector.W * matrix.M41, vector.X * matrix.M12 + vector.Y * matrix.M22 + vector.Z * matrix.M32 + vector.W * matrix.M42, vector.X * matrix.M13 + vector.Y * matrix.M23 + vector.Z * matrix.M33 + vector.W * matrix.M43, vector.X * matrix.M14 + vector.Y * matrix.M24 + vector.Z * matrix.M34 + vector.W * matrix.M44); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector2 value, Quaternion rotation) { float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num; float num5 = rotation.W * num2; float num6 = rotation.W * num3; float num7 = rotation.X * num; float num8 = rotation.X * num2; float num9 = rotation.X * num3; float num10 = rotation.Y * num2; float num11 = rotation.Y * num3; float num12 = rotation.Z * num3; return new Vector4(value.X * (1f - num10 - num12) + value.Y * (num8 - num6), value.X * (num8 + num6) + value.Y * (1f - num7 - num12), value.X * (num9 - num5) + value.Y * (num11 + num4), 1f); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector3 value, Quaternion rotation) { float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num; float num5 = rotation.W * num2; float num6 = rotation.W * num3; float num7 = rotation.X * num; float num8 = rotation.X * num2; float num9 = rotation.X * num3; float num10 = rotation.Y * num2; float num11 = rotation.Y * num3; float num12 = rotation.Z * num3; return new Vector4(value.X * (1f - num10 - num12) + value.Y * (num8 - num6) + value.Z * (num9 + num5), value.X * (num8 + num6) + value.Y * (1f - num7 - num12) + value.Z * (num11 - num4), value.X * (num9 - num5) + value.Y * (num11 + num4) + value.Z * (1f - num7 - num10), 1f); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector4 value, Quaternion rotation) { float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num; float num5 = rotation.W * num2; float num6 = rotation.W * num3; float num7 = rotation.X * num; float num8 = rotation.X * num2; float num9 = rotation.X * num3; float num10 = rotation.Y * num2; float num11 = rotation.Y * num3; float num12 = rotation.Z * num3; return new Vector4(value.X * (1f - num10 - num12) + value.Y * (num8 - num6) + value.Z * (num9 + num5), value.X * (num8 + num6) + value.Y * (1f - num7 - num12) + value.Z * (num11 - num4), value.X * (num9 - num5) + value.Y * (num11 + num4) + value.Z * (1f - num7 - num10), value.W); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Add(Vector4 left, Vector4 right) { return left + right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Subtract(Vector4 left, Vector4 right) { return left - right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Multiply(Vector4 left, Vector4 right) { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Multiply(Vector4 left, float right) { return left * new Vector4(right, right, right, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Multiply(float left, Vector4 right) { return new Vector4(left, left, left, left) * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Divide(Vector4 left, Vector4 right) { return left / right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Divide(Vector4 left, float divisor) { return left / divisor; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Negate(Vector4 value) { return -value; } [System.Runtime.CompilerServices.Intrinsic] public Vector4(float value) : this(value, value, value, value) { } [System.Runtime.CompilerServices.Intrinsic] public Vector4(float x, float y, float z, float w) { W = w; X = x; Y = y; Z = z; } public Vector4(Vector2 value, float z, float w) { X = value.X; Y = value.Y; Z = z; W = w; } public Vector4(Vector3 value, float w) { X = value.X; Y = value.Y; Z = value.Z; W = w; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(float[] array) { CopyTo(array, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public void CopyTo(float[] array, int index) { if (array == null) { throw new NullReferenceException(SR.Arg_NullArgumentNullRef); } if (index < 0 || index >= array.Length) { throw new ArgumentOutOfRangeException("index", SR.Format(SR.Arg_ArgumentOutOfRangeException, index)); } if (array.Length - index < 4) { throw new ArgumentException(SR.Format(SR.Arg_ElementsInSourceIsGreaterThanDestination, index)); } array[index] = X; array[index + 1] = Y; array[index + 2] = Z; array[index + 3] = W; } [System.Runtime.CompilerServices.Intrinsic] public bool Equals(Vector4 other) { if (X == other.X && Y == other.Y && Z == other.Z) { return W == other.W; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static float Dot(Vector4 vector1, Vector4 vector2) { return vector1.X * vector2.X + vector1.Y * vector2.Y + vector1.Z * vector2.Z + vector1.W * vector2.W; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector4 Min(Vector4 value1, Vector4 value2) { return new Vector4((value1.X < value2.X) ? value1.X : value2.X, (value1.Y < value2.Y) ? value1.Y : value2.Y, (value1.Z < value2.Z) ? value1.Z : value2.Z, (value1.W < value2.W) ? value1.W : value2.W); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector4 Max(Vector4 value1, Vector4 value2) { return new Vector4((value1.X > value2.X) ? value1.X : value2.X, (value1.Y > value2.Y) ? value1.Y : value2.Y, (value1.Z > value2.Z) ? value1.Z : value2.Z, (value1.W > value2.W) ? value1.W : value2.W); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector4 Abs(Vector4 value) { return new Vector4(MathF.Abs(value.X), MathF.Abs(value.Y), MathF.Abs(value.Z), MathF.Abs(value.W)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector4 SquareRoot(Vector4 value) { return new Vector4(MathF.Sqrt(value.X), MathF.Sqrt(value.Y), MathF.Sqrt(value.Z), MathF.Sqrt(value.W)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector4 operator +(Vector4 left, Vector4 right) { return new Vector4(left.X + right.X, left.Y + right.Y, left.Z + right.Z, left.W + right.W); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector4 operator -(Vector4 left, Vector4 right) { return new Vector4(left.X - right.X, left.Y - right.Y, left.Z - right.Z, left.W - right.W); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector4 operator *(Vector4 left, Vector4 right) { return new Vector4(left.X * right.X, left.Y * right.Y, left.Z * right.Z, left.W * right.W); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector4 operator *(Vector4 left, float right) { return left * new Vector4(right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector4 operator *(float left, Vector4 right) { return new Vector4(left) * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static Vector4 operator /(Vector4 left, Vector4 right) { return new Vector4(left.X / right.X, left.Y / right.Y, left.Z / right.Z, left.W / right.W); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator /(Vector4 value1, float value2) { return value1 / new Vector4(value2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator -(Vector4 value) { return Zero - value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.CompilerServices.Intrinsic] public static bool operator ==(Vector4 left, Vector4 right) { return left.Equals(right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Vector4 left, Vector4 right) { return !(left == right); } } } namespace System.Numerics.Hashing { internal static class HashHelpers { public static readonly int RandomSeed = Guid.NewGuid().GetHashCode(); public static int Combine(int h1, int h2) { uint num = (uint)(h1 << 5) | ((uint)h1 >> 27); return ((int)num + h1) ^ h2; } } } namespace System.Runtime.CompilerServices { internal static class Unsafe { [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static T Read(void* source) { return Unsafe.Read(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static T ReadUnaligned(void* source) { return Unsafe.ReadUnaligned(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static T ReadUnaligned(ref byte source) { return Unsafe.ReadUnaligned(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Write(void* destination, T value) { Unsafe.Write(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void WriteUnaligned(void* destination, T value) { Unsafe.WriteUnaligned(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void WriteUnaligned(ref byte destination, T value) { Unsafe.WriteUnaligned(ref destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Copy(void* destination, ref T source) { Unsafe.Write(destination, source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Copy(ref T destination, void* source) { destination = Unsafe.Read(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* AsPointer(ref T value) { return Unsafe.AsPointer(ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void SkipInit(out T value) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static int SizeOf() { return Unsafe.SizeOf(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void CopyBlock(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void CopyBlock(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void InitBlock(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static T As(object o) where T : class { return (T)o; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static ref T AsRef(void* source) { return ref *(T*)source; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T AsRef(in T source) { return ref source; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref TTo As(ref TFrom source) { return ref Unsafe.As(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Unbox(object box) { return ref (T)box; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Add(ref T source, int elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* Add(void* source, int elementOffset) { return (byte*)source + (nint)elementOffset * (nint)Unsafe.SizeOf(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Add(ref T source, IntPtr elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T AddByteOffset(ref T source, IntPtr byteOffset) { return ref Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Subtract(ref T source, int elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* Subtract(void* source, int elementOffset) { return (byte*)source - (nint)elementOffset * (nint)Unsafe.SizeOf(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Subtract(ref T source, IntPtr elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T SubtractByteOffset(ref T source, IntPtr byteOffset) { return ref Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static IntPtr ByteOffset(ref T origin, ref T target) { return Unsafe.ByteOffset(target: ref target, origin: ref origin); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool AreSame(ref T left, ref T right) { return Unsafe.AreSame(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool IsAddressGreaterThan(ref T left, ref T right) { return Unsafe.IsAddressGreaterThan(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool IsAddressLessThan(ref T left, ref T right) { return Unsafe.IsAddressLessThan(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static bool IsNullRef(ref T source) { return Unsafe.AsPointer(ref source) == null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static ref T NullRef() { return ref *(T*)null; } } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class NonVersionableAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } } namespace FxResources.System.Text.Encodings.Web { internal static class SR { } } namespace System { internal static class HexConverter { public enum Casing : uint { Upper = 0u, Lower = 8224u } public static ReadOnlySpan CharToHexLookup => new byte[256] { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToBytesBuffer(byte value, Span buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (byte)num2; buffer[startingIndex] = (byte)(num2 >> 8); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToCharsBuffer(byte value, Span buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (char)(num2 & 0xFFu); buffer[startingIndex] = (char)(num2 >> 8); } public static void EncodeToUtf16(ReadOnlySpan bytes, Span chars, Casing casing = Casing.Upper) { for (int i = 0; i < bytes.Length; i++) { ToCharsBuffer(bytes[i], chars, i * 2, casing); } } public unsafe static string ToString(ReadOnlySpan bytes, Casing casing = Casing.Upper) { fixed (byte* ptr = bytes) { return string.Create(bytes.Length * 2, ((IntPtr)ptr, bytes.Length, casing), delegate(Span chars, (IntPtr Ptr, int Length, Casing casing) args) { ReadOnlySpan bytes2 = new ReadOnlySpan((void*)args.Ptr, args.Length); EncodeToUtf16(bytes2, chars, args.casing); }); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharUpper(int value) { value &= 0xF; value += 48; if (value > 57) { value += 7; } return (char)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharLower(int value) { value &= 0xF; value += 48; if (value > 57) { value += 39; } return (char)value; } public static bool TryDecodeFromUtf16(ReadOnlySpan chars, Span bytes) { int charsProcessed; return TryDecodeFromUtf16(chars, bytes, out charsProcessed); } public static bool TryDecodeFromUtf16(ReadOnlySpan chars, Span bytes, out int charsProcessed) { int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; while (num2 < bytes.Length) { num3 = FromChar(chars[num + 1]); num4 = FromChar(chars[num]); if ((num3 | num4) == 255) { break; } bytes[num2++] = (byte)((num4 << 4) | num3); num += 2; } if (num3 == 255) { num++; } charsProcessed = num; return (num3 | num4) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromChar(int c) { if (c < CharToHexLookup.Length) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromUpperChar(int c) { if (c <= 71) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromLowerChar(int c) { switch (c) { case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return c - 48; case 97: case 98: case 99: case 100: case 101: case 102: return c - 97 + 10; default: return 255; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexChar(int c) { return FromChar(c) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexUpperChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 65) <= 5u; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexLowerChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 97) <= 5u; } return true; } } internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(FxResources.System.Text.Encodings.Web.SR))); internal static string TextEncoderDoesNotImplementMaxOutputCharsPerInputChar => GetResourceString("TextEncoderDoesNotImplementMaxOutputCharsPerInputChar"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey, string defaultString = null) { if (UsingResourceKeys()) { return defaultString ?? resourceKey; } string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text)) { return defaultString; } return text; } 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); } 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(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Text { internal static class UnicodeDebug { [Conditional("DEBUG")] internal static void AssertIsHighSurrogateCodePoint(uint codePoint) { System.Text.UnicodeUtility.IsHighSurrogateCodePoint(codePoint); } [Conditional("DEBUG")] internal static void AssertIsLowSurrogateCodePoint(uint codePoint) { System.Text.UnicodeUtility.IsLowSurrogateCodePoint(codePoint); } [Conditional("DEBUG")] internal static void AssertIsValidCodePoint(uint codePoint) { System.Text.UnicodeUtility.IsValidCodePoint(codePoint); } [Conditional("DEBUG")] internal static void AssertIsValidScalar(uint scalarValue) { System.Text.UnicodeUtility.IsValidUnicodeScalar(scalarValue); } [Conditional("DEBUG")] internal static void AssertIsValidSupplementaryPlaneScalar(uint scalarValue) { if (System.Text.UnicodeUtility.IsValidUnicodeScalar(scalarValue)) { System.Text.UnicodeUtility.IsBmpCodePoint(scalarValue); } } private static string ToHexString(uint codePoint) { return FormattableString.Invariant($"U+{codePoint:X4}"); } } internal static class UnicodeUtility { public const uint ReplacementChar = 65533u; public static int GetPlane(uint codePoint) { return (int)(codePoint >> 16); } public static uint GetScalarFromUtf16SurrogatePair(uint highSurrogateCodePoint, uint lowSurrogateCodePoint) { return (highSurrogateCodePoint << 10) + lowSurrogateCodePoint - 56613888; } public static int GetUtf16SequenceLength(uint value) { value -= 65536; value += 33554432; value >>= 24; return (int)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void GetUtf16SurrogatesFromSupplementaryPlaneScalar(uint value, out char highSurrogateCodePoint, out char lowSurrogateCodePoint) { highSurrogateCodePoint = (char)(value + 56557568 >> 10); lowSurrogateCodePoint = (char)((value & 0x3FF) + 56320); } public static int GetUtf8SequenceLength(uint value) { int num = (int)(value - 2048) >> 31; value ^= 0xF800u; value -= 63616; value += 67108864; value >>= 24; return (int)value + num * 2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsAsciiCodePoint(uint value) { return value <= 127; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsBmpCodePoint(uint value) { return value <= 65535; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHighSurrogateCodePoint(uint value) { return IsInRangeInclusive(value, 55296u, 56319u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInRangeInclusive(uint value, uint lowerBound, uint upperBound) { return value - lowerBound <= upperBound - lowerBound; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsLowSurrogateCodePoint(uint value) { return IsInRangeInclusive(value, 56320u, 57343u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsSurrogateCodePoint(uint value) { return IsInRangeInclusive(value, 55296u, 57343u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsValidCodePoint(uint codePoint) { return codePoint <= 1114111; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsValidUnicodeScalar(uint value) { return ((value - 1114112) ^ 0xD800) >= 4293855232u; } } internal ref struct ValueStringBuilder { private char[] _arrayToReturnToPool; private Span _chars; private int _pos; public int Length { get { return _pos; } set { _pos = value; } } public int Capacity => _chars.Length; public ref char this[int index] => ref _chars[index]; public Span RawChars => _chars; public ValueStringBuilder(Span initialBuffer) { _arrayToReturnToPool = null; _chars = initialBuffer; _pos = 0; } public ValueStringBuilder(int initialCapacity) { _arrayToReturnToPool = ArrayPool.Shared.Rent(initialCapacity); _chars = _arrayToReturnToPool; _pos = 0; } public void EnsureCapacity(int capacity) { if (capacity > _chars.Length) { Grow(capacity - _pos); } } public ref char GetPinnableReference() { return ref MemoryMarshal.GetReference(_chars); } public ref char GetPinnableReference(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return ref MemoryMarshal.GetReference(_chars); } public override string ToString() { string result = _chars.Slice(0, _pos).ToString(); Dispose(); return result; } public ReadOnlySpan AsSpan(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return _chars.Slice(0, _pos); } public ReadOnlySpan AsSpan() { return _chars.Slice(0, _pos); } public ReadOnlySpan AsSpan(int start) { return _chars.Slice(start, _pos - start); } public ReadOnlySpan AsSpan(int start, int length) { return _chars.Slice(start, length); } public bool TryCopyTo(Span destination, out int charsWritten) { if (_chars.Slice(0, _pos).TryCopyTo(destination)) { charsWritten = _pos; Dispose(); return true; } charsWritten = 0; Dispose(); return false; } public void Insert(int index, char value, int count) { if (_pos > _chars.Length - count) { Grow(count); } int length = _pos - index; _chars.Slice(index, length).CopyTo(_chars.Slice(index + count)); _chars.Slice(index, count).Fill(value); _pos += count; } public void Insert(int index, string s) { if (s != null) { int length = s.Length; if (_pos > _chars.Length - length) { Grow(length); } int length2 = _pos - index; _chars.Slice(index, length2).CopyTo(_chars.Slice(index + length)); MemoryExtensions.AsSpan(s).CopyTo(_chars.Slice(index)); _pos += length; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(char c) { int pos = _pos; if ((uint)pos < (uint)_chars.Length) { _chars[pos] = c; _pos = pos + 1; } else { GrowAndAppend(c); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(string s) { if (s != null) { int pos = _pos; if (s.Length == 1 && (uint)pos < (uint)_chars.Length) { _chars[pos] = s[0]; _pos = pos + 1; } else { AppendSlow(s); } } } private void AppendSlow(string s) { int pos = _pos; if (pos > _chars.Length - s.Length) { Grow(s.Length); } MemoryExtensions.AsSpan(s).CopyTo(_chars.Slice(pos)); _pos += s.Length; } public void Append(char c, int count) { if (_pos > _chars.Length - count) { Grow(count); } Span span = _chars.Slice(_pos, count); for (int i = 0; i < span.Length; i++) { span[i] = c; } _pos += count; } public unsafe void Append(char* value, int length) { int pos = _pos; if (pos > _chars.Length - length) { Grow(length); } Span span = _chars.Slice(_pos, length); for (int i = 0; i < span.Length; i++) { span[i] = *(value++); } _pos += length; } public void Append(ReadOnlySpan value) { int pos = _pos; if (pos > _chars.Length - value.Length) { Grow(value.Length); } value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span AppendSpan(int length) { int pos = _pos; if (pos > _chars.Length - length) { Grow(length); } _pos = pos + length; return _chars.Slice(pos, length); } [MethodImpl(MethodImplOptions.NoInlining)] private void GrowAndAppend(char c) { Grow(1); Append(c); } [MethodImpl(MethodImplOptions.NoInlining)] private void Grow(int additionalCapacityBeyondPos) { char[] array = ArrayPool.Shared.Rent(Math.Max(_pos + additionalCapacityBeyondPos, _chars.Length * 2)); _chars.Slice(0, _pos).CopyTo(array); char[] arrayToReturnToPool = _arrayToReturnToPool; _chars = (_arrayToReturnToPool = array); if (arrayToReturnToPool != null) { ArrayPool.Shared.Return(arrayToReturnToPool); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { char[] arrayToReturnToPool = _arrayToReturnToPool; this = default(System.Text.ValueStringBuilder); if (arrayToReturnToPool != null) { ArrayPool.Shared.Return(arrayToReturnToPool); } } } } namespace System.Text.Unicode { internal static class UnicodeHelpers { internal const int UNICODE_LAST_CODEPOINT = 1114111; private static readonly uint[] _definedCharacterBitmapBigEndian = (BitConverter.IsLittleEndian ? null : CreateDefinedCharacterBitmapMachineEndian()); private static ReadOnlySpan DefinedCharsBitmapSpan => new byte[8192] { 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 0, 0, 0, 0, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 240, 215, 255, 255, 251, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 127, 254, 255, 255, 255, 255, 255, 231, 254, 255, 255, 255, 255, 255, 255, 0, 255, 255, 255, 135, 31, 0, 255, 255, 255, 223, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 191, 255, 255, 255, 255, 255, 255, 255, 231, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 3, 0, 255, 255, 255, 255, 255, 255, 255, 231, 255, 255, 255, 255, 255, 63, 255, 127, 255, 255, 255, 79, 255, 7, 0, 0, 0, 0, 0, 0, 255, 255, 223, 255, 255, 0, 248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 239, 159, 249, 255, 255, 253, 197, 243, 159, 121, 128, 176, 207, 255, 255, 127, 238, 135, 249, 255, 255, 253, 109, 211, 135, 57, 2, 94, 192, 255, 127, 0, 238, 191, 251, 255, 255, 253, 237, 243, 191, 59, 1, 0, 207, 255, 3, 254, 238, 159, 249, 255, 255, 253, 237, 243, 159, 57, 224, 176, 207, 255, 255, 0, 236, 199, 61, 214, 24, 199, 255, 195, 199, 61, 129, 0, 192, 255, 255, 7, 255, 223, 253, 255, 255, 253, 255, 227, 223, 61, 96, 7, 207, 255, 128, 255, 255, 223, 253, 255, 255, 253, 239, 243, 223, 61, 96, 64, 207, 255, 6, 0, 255, 223, 253, 255, 255, 255, 255, 255, 223, 253, 240, 255, 207, 255, 255, 255, 238, 255, 127, 252, 255, 255, 251, 47, 127, 132, 95, 255, 192, 255, 28, 0, 254, 255, 255, 255, 255, 255, 255, 135, 255, 255, 255, 15, 0, 0, 0, 0, 214, 247, 255, 255, 175, 255, 255, 63, 95, 63, 255, 243, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 31, 254, 255, 255, 255, 255, 254, 255, 255, 255, 223, 255, 223, 255, 7, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 191, 32, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 61, 127, 61, 255, 255, 255, 255, 255, 61, 255, 255, 255, 255, 61, 127, 61, 255, 127, 255, 255, 255, 255, 255, 255, 255, 61, 255, 255, 255, 255, 255, 255, 255, 255, 231, 255, 255, 255, 31, 255, 255, 255, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 31, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1, 255, 223, 31, 0, 255, 255, 127, 0, 255, 255, 15, 0, 255, 223, 13, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 255, 3, 255, 3, 255, 127, 255, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1, 255, 255, 255, 255, 255, 7, 255, 255, 255, 255, 255, 255, 255, 255, 63, 0, 255, 255, 255, 127, 255, 15, 255, 15, 241, 255, 255, 255, 255, 63, 31, 0, 255, 255, 255, 255, 255, 15, 255, 255, 255, 3, 255, 199, 255, 255, 255, 255, 255, 255, 255, 207, 255, 255, 255, 255, 255, 255, 255, 127, 255, 255, 255, 159, 255, 3, 255, 3, 255, 63, 255, 255, 1, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 255, 255, 255, 255, 255, 31, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 240, 255, 255, 255, 255, 255, 255, 255, 248, 255, 227, 255, 255, 255, 255, 255, 255, 255, 1, 255, 255, 255, 255, 255, 231, 255, 0, 255, 255, 255, 255, 255, 7, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 251, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 63, 255, 255, 255, 255, 63, 63, 255, 170, 255, 255, 255, 63, 255, 255, 255, 255, 255, 255, 223, 255, 223, 255, 207, 239, 255, 255, 220, 127, 0, 248, 255, 255, 255, 124, 255, 255, 255, 255, 255, 127, 223, 255, 243, 255, 255, 127, 255, 31, 255, 255, 255, 255, 0, 0, 255, 255, 255, 255, 1, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 0, 0, 0, 255, 7, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 207, 255, 255, 255, 191, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 255, 255, 255, 255, 255, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 254, 255, 255, 255, 255, 191, 32, 255, 255, 255, 255, 255, 255, 255, 128, 1, 128, 255, 255, 127, 0, 127, 127, 127, 127, 127, 127, 127, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 7, 0, 0, 0, 0, 0, 255, 255, 255, 251, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 0, 0, 0, 255, 15, 254, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 224, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 0, 255, 255, 255, 255, 255, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 31, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 31, 255, 255, 255, 255, 255, 255, 127, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 7, 0, 0, 0, 0, 224, 255, 255, 255, 255, 255, 255, 31, 255, 3, 255, 255, 255, 255, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255, 255, 255, 63, 192, 255, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 128, 255, 255, 255, 31, 255, 255, 255, 255, 255, 255, 255, 255, 255, 191, 255, 195, 255, 255, 255, 127, 255, 255, 255, 255, 255, 255, 127, 0, 255, 63, 255, 243, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 7, 0, 0, 248, 255, 255, 127, 0, 126, 126, 126, 0, 127, 127, 255, 255, 255, 255, 255, 255, 255, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 255, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 0, 255, 255, 127, 248, 255, 255, 255, 255, 255, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 3, 0, 0, 0, 0, 127, 0, 248, 224, 255, 255, 127, 95, 219, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 3, 0, 248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 63, 255, 255, 255, 3, 255, 255, 255, 255, 255, 255, 247, 255, 127, 15, 223, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 31, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 252, 252, 252, 28, 127, 127, 0, 62 }; private static uint[] CreateDefinedCharacterBitmapMachineEndian() { ReadOnlySpan source = DefinedCharsBitmapSpan; uint[] array = new uint[source.Length / 4]; for (int i = 0; i < array.Length; i++) { array[i] = BinaryPrimitives.ReadUInt32LittleEndian(source); source = source.Slice(4); } return array; } public static OperationStatus DecodeScalarValueFromUtf8(ReadOnlySpan source, out uint result, out int bytesConsumed) { int num = 0; uint num2; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Text.UnicodeUtility.IsAsciiCodePoint(num2)) { goto IL_0021; } if (System.Text.UnicodeUtility.IsInRangeInclusive(num2, 194u, 244u)) { num2 = num2 - 194 << 6; num++; if ((uint)num >= (uint)source.Length) { goto IL_0150; } int num3 = (sbyte)source[num]; if (num3 < -64) { num2 += (uint)num3; num2 += 128; num2 += 128; if (num2 < 2048) { goto IL_0021; } if (System.Text.UnicodeUtility.IsInRangeInclusive(num2, 2080u, 3343u) && !System.Text.UnicodeUtility.IsInRangeInclusive(num2, 2912u, 2943u) && !System.Text.UnicodeUtility.IsInRangeInclusive(num2, 3072u, 3087u)) { num++; if ((uint)num >= (uint)source.Length) { goto IL_0150; } num3 = (sbyte)source[num]; if (num3 < -64) { num2 <<= 6; num2 += (uint)num3; num2 += 128; num2 -= 131072; if (num2 > 65535) { num++; if ((uint)num >= (uint)source.Length) { goto IL_0150; } num3 = (sbyte)source[num]; if (num3 >= -64) { goto IL_0144; } num2 <<= 6; num2 += (uint)num3; num2 += 128; num2 -= 4194304; } goto IL_0021; } } } } else { num = 1; } goto IL_0144; } goto IL_0150; IL_0021: bytesConsumed = num + 1; result = num2; return OperationStatus.Done; IL_0144: bytesConsumed = num; result = 65533u; return OperationStatus.InvalidData; IL_0150: bytesConsumed = num; result = 65533u; return OperationStatus.NeedMoreData; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static ReadOnlySpan GetDefinedCharacterBitmap() { if (BitConverter.IsLittleEndian) { return MemoryMarshal.Cast(DefinedCharsBitmapSpan); } return _definedCharacterBitmapBigEndian; } internal static void GetUtf16SurrogatePairFromAstralScalarValue(int scalar, out char highSurrogate, out char lowSurrogate) { int num = scalar & 0xFFFF; int num2 = scalar >> 16; int num3 = num2 - 1; highSurrogate = (char)(0xD800u | (uint)(num3 << 6) | (uint)(num >> 10)); lowSurrogate = (char)(0xDC00u | ((uint)num & 0x3FFu)); } internal static int GetUtf8RepresentationForScalarValue(uint scalar) { if (scalar <= 127) { return (byte)scalar; } if (scalar <= 2047) { byte b = (byte)(0xC0u | (scalar >> 6)); byte b2 = (byte)(0x80u | (scalar & 0x3Fu)); return (b2 << 8) | b; } if (scalar <= 65535) { byte b3 = (byte)(0xE0u | (scalar >> 12)); byte b4 = (byte)(0x80u | ((scalar >> 6) & 0x3Fu)); byte b5 = (byte)(0x80u | (scalar & 0x3Fu)); return (((b5 << 8) | b4) << 8) | b3; } byte b6 = (byte)(0xF0u | (scalar >> 18)); byte b7 = (byte)(0x80u | ((scalar >> 12) & 0x3Fu)); byte b8 = (byte)(0x80u | ((scalar >> 6) & 0x3Fu)); byte b9 = (byte)(0x80u | (scalar & 0x3Fu)); return (((((b9 << 8) | b8) << 8) | b7) << 8) | b6; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsSupplementaryCodePoint(int scalar) { return (scalar & -65536) != 0; } } internal sealed class UnicodeRange { public int FirstCodePoint { get; private set; } public int Length { get; private set; } public UnicodeRange(int firstCodePoint, int length) { if (firstCodePoint < 0 || firstCodePoint > 65535) { throw new ArgumentOutOfRangeException("firstCodePoint"); } if (length < 0 || (long)firstCodePoint + (long)length > 65536) { throw new ArgumentOutOfRangeException("length"); } FirstCodePoint = firstCodePoint; Length = length; } public static UnicodeRange Create(char firstCharacter, char lastCharacter) { if (lastCharacter < firstCharacter) { throw new ArgumentOutOfRangeException("lastCharacter"); } return new UnicodeRange(firstCharacter, 1 + (lastCharacter - firstCharacter)); } } internal static class UnicodeRanges { private static UnicodeRange _none; private static UnicodeRange _all; private static UnicodeRange _u0000; private static UnicodeRange _u0080; private static UnicodeRange _u0100; private static UnicodeRange _u0180; private static UnicodeRange _u0250; private static UnicodeRange _u02B0; private static UnicodeRange _u0300; private static UnicodeRange _u0370; private static UnicodeRange _u0400; private static UnicodeRange _u0500; private static UnicodeRange _u0530; private static UnicodeRange _u0590; private static UnicodeRange _u0600; private static UnicodeRange _u0700; private static UnicodeRange _u0750; private static UnicodeRange _u0780; private static UnicodeRange _u07C0; private static UnicodeRange _u0800; private static UnicodeRange _u0840; private static UnicodeRange _u0860; private static UnicodeRange _u08A0; private static UnicodeRange _u0900; private static UnicodeRange _u0980; private static UnicodeRange _u0A00; private static UnicodeRange _u0A80; private static UnicodeRange _u0B00; private static UnicodeRange _u0B80; private static UnicodeRange _u0C00; private static UnicodeRange _u0C80; private static UnicodeRange _u0D00; private static UnicodeRange _u0D80; private static UnicodeRange _u0E00; private static UnicodeRange _u0E80; private static UnicodeRange _u0F00; private static UnicodeRange _u1000; private static UnicodeRange _u10A0; private static UnicodeRange _u1100; private static UnicodeRange _u1200; private static UnicodeRange _u1380; private static UnicodeRange _u13A0; private static UnicodeRange _u1400; private static UnicodeRange _u1680; private static UnicodeRange _u16A0; private static UnicodeRange _u1700; private static UnicodeRange _u1720; private static UnicodeRange _u1740; private static UnicodeRange _u1760; private static UnicodeRange _u1780; private static UnicodeRange _u1800; private static UnicodeRange _u18B0; private static UnicodeRange _u1900; private static UnicodeRange _u1950; private static UnicodeRange _u1980; private static UnicodeRange _u19E0; private static UnicodeRange _u1A00; private static UnicodeRange _u1A20; private static UnicodeRange _u1AB0; private static UnicodeRange _u1B00; private static UnicodeRange _u1B80; private static UnicodeRange _u1BC0; private static UnicodeRange _u1C00; private static UnicodeRange _u1C50; private static UnicodeRange _u1C80; private static UnicodeRange _u1C90; private static UnicodeRange _u1CC0; private static UnicodeRange _u1CD0; private static UnicodeRange _u1D00; private static UnicodeRange _u1D80; private static UnicodeRange _u1DC0; private static UnicodeRange _u1E00; private static UnicodeRange _u1F00; private static UnicodeRange _u2000; private static UnicodeRange _u2070; private static UnicodeRange _u20A0; private static UnicodeRange _u20D0; private static UnicodeRange _u2100; private static UnicodeRange _u2150; private static UnicodeRange _u2190; private static UnicodeRange _u2200; private static UnicodeRange _u2300; private static UnicodeRange _u2400; private static UnicodeRange _u2440; private static UnicodeRange _u2460; private static UnicodeRange _u2500; private static UnicodeRange _u2580; private static UnicodeRange _u25A0; private static UnicodeRange _u2600; private static UnicodeRange _u2700; private static UnicodeRange _u27C0; private static UnicodeRange _u27F0; private static UnicodeRange _u2800; private static UnicodeRange _u2900; private static UnicodeRange _u2980; private static UnicodeRange _u2A00; private static UnicodeRange _u2B00; private static UnicodeRange _u2C00; private static UnicodeRange _u2C60; private static UnicodeRange _u2C80; private static UnicodeRange _u2D00; private static UnicodeRange _u2D30; private static UnicodeRange _u2D80; private static UnicodeRange _u2DE0; private static UnicodeRange _u2E00; private static UnicodeRange _u2E80; private static UnicodeRange _u2F00; private static UnicodeRange _u2FF0; private static UnicodeRange _u3000; private static UnicodeRange _u3040; private static UnicodeRange _u30A0; private static UnicodeRange _u3100; private static UnicodeRange _u3130; private static UnicodeRange _u3190; private static UnicodeRange _u31A0; private static UnicodeRange _u31C0; private static UnicodeRange _u31F0; private static UnicodeRange _u3200; private static UnicodeRange _u3300; private static UnicodeRange _u3400; private static UnicodeRange _u4DC0; private static UnicodeRange _u4E00; private static UnicodeRange _uA000; private static UnicodeRange _uA490; private static UnicodeRange _uA4D0; private static UnicodeRange _uA500; private static UnicodeRange _uA640; private static UnicodeRange _uA6A0; private static UnicodeRange _uA700; private static UnicodeRange _uA720; private static UnicodeRange _uA800; private static UnicodeRange _uA830; private static UnicodeRange _uA840; private static UnicodeRange _uA880; private static UnicodeRange _uA8E0; private static UnicodeRange _uA900; private static UnicodeRange _uA930; private static UnicodeRange _uA960; private static UnicodeRange _uA980; private static UnicodeRange _uA9E0; private static UnicodeRange _uAA00; private static UnicodeRange _uAA60; private static UnicodeRange _uAA80; private static UnicodeRange _uAAE0; private static UnicodeRange _uAB00; private static UnicodeRange _uAB30; private static UnicodeRange _uAB70; private static UnicodeRange _uABC0; private static UnicodeRange _uAC00; private static UnicodeRange _uD7B0; private static UnicodeRange _uF900; private static UnicodeRange _uFB00; private static UnicodeRange _uFB50; private static UnicodeRange _uFE00; private static UnicodeRange _uFE10; private static UnicodeRange _uFE20; private static UnicodeRange _uFE30; private static UnicodeRange _uFE50; private static UnicodeRange _uFE70; private static UnicodeRange _uFF00; private static UnicodeRange _uFFF0; public static UnicodeRange None => _none ?? CreateEmptyRange(ref _none); public static UnicodeRange All => _all ?? CreateRange(ref _all, '\0', '\uffff'); public static UnicodeRange BasicLatin => _u0000 ?? CreateRange(ref _u0000, '\0', '\u007f'); public static UnicodeRange Latin1Supplement => _u0080 ?? CreateRange(ref _u0080, '\u0080', 'ÿ'); public static UnicodeRange LatinExtendedA => _u0100 ?? CreateRange(ref _u0100, 'Ā', 'ſ'); public static UnicodeRange LatinExtendedB => _u0180 ?? CreateRange(ref _u0180, 'ƀ', 'ɏ'); public static UnicodeRange IpaExtensions => _u0250 ?? CreateRange(ref _u0250, 'ɐ', 'ʯ'); public static UnicodeRange SpacingModifierLetters => _u02B0 ?? CreateRange(ref _u02B0, 'ʰ', '\u02ff'); public static UnicodeRange CombiningDiacriticalMarks => _u0300 ?? CreateRange(ref _u0300, '\u0300', '\u036f'); public static UnicodeRange GreekandCoptic => _u0370 ?? CreateRange(ref _u0370, 'Ͱ', 'Ͽ'); public static UnicodeRange Cyrillic => _u0400 ?? CreateRange(ref _u0400, 'Ѐ', 'ӿ'); public static UnicodeRange CyrillicSupplement => _u0500 ?? CreateRange(ref _u0500, 'Ԁ', 'ԯ'); public static UnicodeRange Armenian => _u0530 ?? CreateRange(ref _u0530, '\u0530', '֏'); public static UnicodeRange Hebrew => _u0590 ?? CreateRange(ref _u0590, '\u0590', '\u05ff'); public static UnicodeRange Arabic => _u0600 ?? CreateRange(ref _u0600, '\u0600', 'ۿ'); public static UnicodeRange Syriac => _u0700 ?? CreateRange(ref _u0700, '܀', 'ݏ'); public static UnicodeRange ArabicSupplement => _u0750 ?? CreateRange(ref _u0750, 'ݐ', 'ݿ'); public static UnicodeRange Thaana => _u0780 ?? CreateRange(ref _u0780, 'ހ', '\u07bf'); public static UnicodeRange NKo => _u07C0 ?? CreateRange(ref _u07C0, '߀', '߿'); public static UnicodeRange Samaritan => _u0800 ?? CreateRange(ref _u0800, 'ࠀ', '\u083f'); public static UnicodeRange Mandaic => _u0840 ?? CreateRange(ref _u0840, 'ࡀ', '\u085f'); public static UnicodeRange SyriacSupplement => _u0860 ?? CreateRange(ref _u0860, 'ࡠ', '\u086f'); public static UnicodeRange ArabicExtendedA => _u08A0 ?? CreateRange(ref _u08A0, 'ࢠ', '\u08ff'); public static UnicodeRange Devanagari => _u0900 ?? CreateRange(ref _u0900, '\u0900', 'ॿ'); public static UnicodeRange Bengali => _u0980 ?? CreateRange(ref _u0980, 'ঀ', '\u09ff'); public static UnicodeRange Gurmukhi => _u0A00 ?? CreateRange(ref _u0A00, '\u0a00', '\u0a7f'); public static UnicodeRange Gujarati => _u0A80 ?? CreateRange(ref _u0A80, '\u0a80', '\u0aff'); public static UnicodeRange Oriya => _u0B00 ?? CreateRange(ref _u0B00, '\u0b00', '\u0b7f'); public static UnicodeRange Tamil => _u0B80 ?? CreateRange(ref _u0B80, '\u0b80', '\u0bff'); public static UnicodeRange Telugu => _u0C00 ?? CreateRange(ref _u0C00, '\u0c00', '౿'); public static UnicodeRange Kannada => _u0C80 ?? CreateRange(ref _u0C80, 'ಀ', '\u0cff'); public static UnicodeRange Malayalam => _u0D00 ?? CreateRange(ref _u0D00, '\u0d00', 'ൿ'); public static UnicodeRange Sinhala => _u0D80 ?? CreateRange(ref _u0D80, '\u0d80', '\u0dff'); public static UnicodeRange Thai => _u0E00 ?? CreateRange(ref _u0E00, '\u0e00', '\u0e7f'); public static UnicodeRange Lao => _u0E80 ?? CreateRange(ref _u0E80, '\u0e80', '\u0eff'); public static UnicodeRange Tibetan => _u0F00 ?? CreateRange(ref _u0F00, 'ༀ', '\u0fff'); public static UnicodeRange Myanmar => _u1000 ?? CreateRange(ref _u1000, 'က', '႟'); public static UnicodeRange Georgian => _u10A0 ?? CreateRange(ref _u10A0, 'Ⴀ', 'ჿ'); public static UnicodeRange HangulJamo => _u1100 ?? CreateRange(ref _u1100, 'ᄀ', 'ᇿ'); public static UnicodeRange Ethiopic => _u1200 ?? CreateRange(ref _u1200, 'ሀ', '\u137f'); public static UnicodeRange EthiopicSupplement => _u1380 ?? CreateRange(ref _u1380, 'ᎀ', '\u139f'); public static UnicodeRange Cherokee => _u13A0 ?? CreateRange(ref _u13A0, 'Ꭰ', '\u13ff'); public static UnicodeRange UnifiedCanadianAboriginalSyllabics => _u1400 ?? CreateRange(ref _u1400, '᐀', 'ᙿ'); public static UnicodeRange Ogham => _u1680 ?? CreateRange(ref _u1680, '\u1680', '\u169f'); public static UnicodeRange Runic => _u16A0 ?? CreateRange(ref _u16A0, 'ᚠ', '\u16ff'); public static UnicodeRange Tagalog => _u1700 ?? CreateRange(ref _u1700, 'ᜀ', '\u171f'); public static UnicodeRange Hanunoo => _u1720 ?? CreateRange(ref _u1720, 'ᜠ', '\u173f'); public static UnicodeRange Buhid => _u1740 ?? CreateRange(ref _u1740, 'ᝀ', '\u175f'); public static UnicodeRange Tagbanwa => _u1760 ?? CreateRange(ref _u1760, 'ᝠ', '\u177f'); public static UnicodeRange Khmer => _u1780 ?? CreateRange(ref _u1780, 'ក', '\u17ff'); public static UnicodeRange Mongolian => _u1800 ?? CreateRange(ref _u1800, '᠀', '\u18af'); public static UnicodeRange UnifiedCanadianAboriginalSyllabicsExtended => _u18B0 ?? CreateRange(ref _u18B0, 'ᢰ', '\u18ff'); public static UnicodeRange Limbu => _u1900 ?? CreateRange(ref _u1900, 'ᤀ', '᥏'); public static UnicodeRange TaiLe => _u1950 ?? CreateRange(ref _u1950, 'ᥐ', '\u197f'); public static UnicodeRange NewTaiLue => _u1980 ?? CreateRange(ref _u1980, 'ᦀ', '᧟'); public static UnicodeRange KhmerSymbols => _u19E0 ?? CreateRange(ref _u19E0, '᧠', '᧿'); public static UnicodeRange Buginese => _u1A00 ?? CreateRange(ref _u1A00, 'ᨀ', '᨟'); public static UnicodeRange TaiTham => _u1A20 ?? CreateRange(ref _u1A20, 'ᨠ', '\u1aaf'); public static UnicodeRange CombiningDiacriticalMarksExtended => _u1AB0 ?? CreateRange(ref _u1AB0, '\u1ab0', '\u1aff'); public static UnicodeRange Balinese => _u1B00 ?? CreateRange(ref _u1B00, '\u1b00', '\u1b7f'); public static UnicodeRange Sundanese => _u1B80 ?? CreateRange(ref _u1B80, '\u1b80', 'ᮿ'); public static UnicodeRange Batak => _u1BC0 ?? CreateRange(ref _u1BC0, 'ᯀ', '᯿'); public static UnicodeRange Lepcha => _u1C00 ?? CreateRange(ref _u1C00, 'ᰀ', 'ᱏ'); public static UnicodeRange OlChiki => _u1C50 ?? CreateRange(ref _u1C50, '᱐', '᱿'); public static UnicodeRange CyrillicExtendedC => _u1C80 ?? CreateRange(ref _u1C80, 'ᲀ', '\u1c8f'); public static UnicodeRange GeorgianExtended => _u1C90 ?? CreateRange(ref _u1C90, 'Ა', 'Ჿ'); public static UnicodeRange SundaneseSupplement => _u1CC0 ?? CreateRange(ref _u1CC0, '᳀', '\u1ccf'); public static UnicodeRange VedicExtensions => _u1CD0 ?? CreateRange(ref _u1CD0, '\u1cd0', '\u1cff'); public static UnicodeRange PhoneticExtensions => _u1D00 ?? CreateRange(ref _u1D00, 'ᴀ', 'ᵿ'); public static UnicodeRange PhoneticExtensionsSupplement => _u1D80 ?? CreateRange(ref _u1D80, 'ᶀ', 'ᶿ'); public static UnicodeRange CombiningDiacriticalMarksSupplement => _u1DC0 ?? CreateRange(ref _u1DC0, '\u1dc0', '\u1dff'); public static UnicodeRange LatinExtendedAdditional => _u1E00 ?? CreateRange(ref _u1E00, 'Ḁ', 'ỿ'); public static UnicodeRange GreekExtended => _u1F00 ?? CreateRange(ref _u1F00, 'ἀ', '\u1fff'); public static UnicodeRange GeneralPunctuation => _u2000 ?? CreateRange(ref _u2000, '\u2000', '\u206f'); public static UnicodeRange SuperscriptsandSubscripts => _u2070 ?? CreateRange(ref _u2070, '⁰', '\u209f'); public static UnicodeRange CurrencySymbols => _u20A0 ?? CreateRange(ref _u20A0, '₠', '\u20cf'); public static UnicodeRange CombiningDiacriticalMarksforSymbols => _u20D0 ?? CreateRange(ref _u20D0, '\u20d0', '\u20ff'); public static UnicodeRange LetterlikeSymbols => _u2100 ?? CreateRange(ref _u2100, '℀', '⅏'); public static UnicodeRange NumberForms => _u2150 ?? CreateRange(ref _u2150, '⅐', '\u218f'); public static UnicodeRange Arrows => _u2190 ?? CreateRange(ref _u2190, '←', '⇿'); public static UnicodeRange MathematicalOperators => _u2200 ?? CreateRange(ref _u2200, '∀', '⋿'); public static UnicodeRange MiscellaneousTechnical => _u2300 ?? CreateRange(ref _u2300, '⌀', '⏿'); public static UnicodeRange ControlPictures => _u2400 ?? CreateRange(ref _u2400, '␀', '\u243f'); public static UnicodeRange OpticalCharacterRecognition => _u2440 ?? CreateRange(ref _u2440, '⑀', '\u245f'); public static UnicodeRange EnclosedAlphanumerics => _u2460 ?? CreateRange(ref _u2460, '①', '⓿'); public static UnicodeRange BoxDrawing => _u2500 ?? CreateRange(ref _u2500, '─', '╿'); public static UnicodeRange BlockElements => _u2580 ?? CreateRange(ref _u2580, '▀', '▟'); public static UnicodeRange GeometricShapes => _u25A0 ?? CreateRange(ref _u25A0, '■', '◿'); public static UnicodeRange MiscellaneousSymbols => _u2600 ?? CreateRange(ref _u2600, '☀', '⛿'); public static UnicodeRange Dingbats => _u2700 ?? CreateRange(ref _u2700, '✀', '➿'); public static UnicodeRange MiscellaneousMathematicalSymbolsA => _u27C0 ?? CreateRange(ref _u27C0, '⟀', '⟯'); public static UnicodeRange SupplementalArrowsA => _u27F0 ?? CreateRange(ref _u27F0, '⟰', '⟿'); public static UnicodeRange BraillePatterns => _u2800 ?? CreateRange(ref _u2800, '⠀', '⣿'); public static UnicodeRange SupplementalArrowsB => _u2900 ?? CreateRange(ref _u2900, '⤀', '⥿'); public static UnicodeRange MiscellaneousMathematicalSymbolsB => _u2980 ?? CreateRange(ref _u2980, '⦀', '⧿'); public static UnicodeRange SupplementalMathematicalOperators => _u2A00 ?? CreateRange(ref _u2A00, '⨀', '⫿'); public static UnicodeRange MiscellaneousSymbolsandArrows => _u2B00 ?? CreateRange(ref _u2B00, '⬀', '⯿'); public static UnicodeRange Glagolitic => _u2C00 ?? CreateRange(ref _u2C00, 'Ⰰ', '\u2c5f'); public static UnicodeRange LatinExtendedC => _u2C60 ?? CreateRange(ref _u2C60, 'Ⱡ', 'Ɀ'); public static UnicodeRange Coptic => _u2C80 ?? CreateRange(ref _u2C80, 'Ⲁ', '⳿'); public static UnicodeRange GeorgianSupplement => _u2D00 ?? CreateRange(ref _u2D00, 'ⴀ', '\u2d2f'); public static UnicodeRange Tifinagh => _u2D30 ?? CreateRange(ref _u2D30, 'ⴰ', '\u2d7f'); public static UnicodeRange EthiopicExtended => _u2D80 ?? CreateRange(ref _u2D80, 'ⶀ', '\u2ddf'); public static UnicodeRange CyrillicExtendedA => _u2DE0 ?? CreateRange(ref _u2DE0, '\u2de0', '\u2dff'); public static UnicodeRange SupplementalPunctuation => _u2E00 ?? CreateRange(ref _u2E00, '⸀', '\u2e7f'); public static UnicodeRange CjkRadicalsSupplement => _u2E80 ?? CreateRange(ref _u2E80, '⺀', '\u2eff'); public static UnicodeRange KangxiRadicals => _u2F00 ?? CreateRange(ref _u2F00, '⼀', '\u2fdf'); public static UnicodeRange IdeographicDescriptionCharacters => _u2FF0 ?? CreateRange(ref _u2FF0, '⿰', '\u2fff'); public static UnicodeRange CjkSymbolsandPunctuation => _u3000 ?? CreateRange(ref _u3000, '\u3000', '〿'); public static UnicodeRange Hiragana => _u3040 ?? CreateRange(ref _u3040, '\u3040', 'ゟ'); public static UnicodeRange Katakana => _u30A0 ?? CreateRange(ref _u30A0, '゠', 'ヿ'); public static UnicodeRange Bopomofo => _u3100 ?? CreateRange(ref _u3100, '\u3100', 'ㄯ'); public static UnicodeRange HangulCompatibilityJamo => _u3130 ?? CreateRange(ref _u3130, '\u3130', '\u318f'); public static UnicodeRange Kanbun => _u3190 ?? CreateRange(ref _u3190, '㆐', '㆟'); public static UnicodeRange BopomofoExtended => _u31A0 ?? CreateRange(ref _u31A0, 'ㆠ', 'ㆿ'); public static UnicodeRange CjkStrokes => _u31C0 ?? CreateRange(ref _u31C0, '㇀', '\u31ef'); public static UnicodeRange KatakanaPhoneticExtensions => _u31F0 ?? CreateRange(ref _u31F0, 'ㇰ', 'ㇿ'); public static UnicodeRange EnclosedCjkLettersandMonths => _u3200 ?? CreateRange(ref _u3200, '㈀', '㋿'); public static UnicodeRange CjkCompatibility => _u3300 ?? CreateRange(ref _u3300, '㌀', '㏿'); public static UnicodeRange CjkUnifiedIdeographsExtensionA => _u3400 ?? CreateRange(ref _u3400, '㐀', '䶿'); public static UnicodeRange YijingHexagramSymbols => _u4DC0 ?? CreateRange(ref _u4DC0, '䷀', '䷿'); public static UnicodeRange CjkUnifiedIdeographs => _u4E00 ?? CreateRange(ref _u4E00, '一', '\u9fff'); public static UnicodeRange YiSyllables => _uA000 ?? CreateRange(ref _uA000, 'ꀀ', '\ua48f'); public static UnicodeRange YiRadicals => _uA490 ?? CreateRange(ref _uA490, '꒐', '\ua4cf'); public static UnicodeRange Lisu => _uA4D0 ?? CreateRange(ref _uA4D0, 'ꓐ', '꓿'); public static UnicodeRange Vai => _uA500 ?? CreateRange(ref _uA500, 'ꔀ', '\ua63f'); public static UnicodeRange CyrillicExtendedB => _uA640 ?? CreateRange(ref _uA640, 'Ꙁ', '\ua69f'); public static UnicodeRange Bamum => _uA6A0 ?? CreateRange(ref _uA6A0, 'ꚠ', '\ua6ff'); public static UnicodeRange ModifierToneLetters => _uA700 ?? CreateRange(ref _uA700, '\ua700', 'ꜟ'); public static UnicodeRange LatinExtendedD => _uA720 ?? CreateRange(ref _uA720, '\ua720', 'ꟿ'); public static UnicodeRange SylotiNagri => _uA800 ?? CreateRange(ref _uA800, 'ꠀ', '\ua82f'); public static UnicodeRange CommonIndicNumberForms => _uA830 ?? CreateRange(ref _uA830, '꠰', '\ua83f'); public static UnicodeRange Phagspa => _uA840 ?? CreateRange(ref _uA840, 'ꡀ', '\ua87f'); public static UnicodeRange Saurashtra => _uA880 ?? CreateRange(ref _uA880, '\ua880', '\ua8df'); public static UnicodeRange DevanagariExtended => _uA8E0 ?? CreateRange(ref _uA8E0, '\ua8e0', '\ua8ff'); public static UnicodeRange KayahLi => _uA900 ?? CreateRange(ref _uA900, '꤀', '꤯'); public static UnicodeRange Rejang => _uA930 ?? CreateRange(ref _uA930, 'ꤰ', '꥟'); public static UnicodeRange HangulJamoExtendedA => _uA960 ?? CreateRange(ref _uA960, 'ꥠ', '\ua97f'); public static UnicodeRange Javanese => _uA980 ?? CreateRange(ref _uA980, '\ua980', '꧟'); public static UnicodeRange MyanmarExtendedB => _uA9E0 ?? CreateRange(ref _uA9E0, 'ꧠ', '\ua9ff'); public static UnicodeRange Cham => _uAA00 ?? CreateRange(ref _uAA00, 'ꨀ', '꩟'); public static UnicodeRange MyanmarExtendedA => _uAA60 ?? CreateRange(ref _uAA60, 'ꩠ', 'ꩿ'); public static UnicodeRange TaiViet => _uAA80 ?? CreateRange(ref _uAA80, 'ꪀ', '꫟'); public static UnicodeRange MeeteiMayekExtensions => _uAAE0 ?? CreateRange(ref _uAAE0, 'ꫠ', '\uaaff'); public static UnicodeRange EthiopicExtendedA => _uAB00 ?? CreateRange(ref _uAB00, '\uab00', '\uab2f'); public static UnicodeRange LatinExtendedE => _uAB30 ?? CreateRange(ref _uAB30, 'ꬰ', '\uab6f'); public static UnicodeRange CherokeeSupplement => _uAB70 ?? CreateRange(ref _uAB70, 'ꭰ', 'ꮿ'); public static UnicodeRange MeeteiMayek => _uABC0 ?? CreateRange(ref _uABC0, 'ꯀ', '\uabff'); public static UnicodeRange HangulSyllables => _uAC00 ?? CreateRange(ref _uAC00, '가', '\ud7af'); public static UnicodeRange HangulJamoExtendedB => _uD7B0 ?? CreateRange(ref _uD7B0, 'ힰ', '\ud7ff'); public static UnicodeRange CjkCompatibilityIdeographs => _uF900 ?? CreateRange(ref _uF900, '豈', '\ufaff'); public static UnicodeRange AlphabeticPresentationForms => _uFB00 ?? CreateRange(ref _uFB00, 'ff', 'ﭏ'); public static UnicodeRange ArabicPresentationFormsA => _uFB50 ?? CreateRange(ref _uFB50, 'ﭐ', '\ufdff'); public static UnicodeRange VariationSelectors => _uFE00 ?? CreateRange(ref _uFE00, '\ufe00', '\ufe0f'); public static UnicodeRange VerticalForms => _uFE10 ?? CreateRange(ref _uFE10, '︐', '\ufe1f'); public static UnicodeRange CombiningHalfMarks => _uFE20 ?? CreateRange(ref _uFE20, '\ufe20', '\ufe2f'); public static UnicodeRange CjkCompatibilityForms => _uFE30 ?? CreateRange(ref _uFE30, '︰', '\ufe4f'); public static UnicodeRange SmallFormVariants => _uFE50 ?? CreateRange(ref _uFE50, '﹐', '\ufe6f'); public static UnicodeRange ArabicPresentationFormsB => _uFE70 ?? CreateRange(ref _uFE70, 'ﹰ', '\ufeff'); public static UnicodeRange HalfwidthandFullwidthForms => _uFF00 ?? CreateRange(ref _uFF00, '\uff00', '\uffef'); public static UnicodeRange Specials => _uFFF0 ?? CreateRange(ref _uFFF0, '\ufff0', '\uffff'); [MethodImpl(MethodImplOptions.NoInlining)] private static UnicodeRange CreateEmptyRange([NotNull] ref UnicodeRange range) { Volatile.Write(ref range, new UnicodeRange(0, 0)); return range; } [MethodImpl(MethodImplOptions.NoInlining)] private static UnicodeRange CreateRange([NotNull] ref UnicodeRange range, char first, char last) { Volatile.Write(ref range, UnicodeRange.Create(first, last)); return range; } } } namespace System.Text.Internal { internal readonly struct AllowedCharactersBitmap { private const int ALLOWED_CHARS_BITMAP_LENGTH = 2048; private readonly uint[] _allowedCharacters; public static AllowedCharactersBitmap CreateNew() { return new AllowedCharactersBitmap(new uint[2048]); } private AllowedCharactersBitmap(uint[] allowedCharacters) { if (allowedCharacters == null) { throw new ArgumentNullException("allowedCharacters"); } _allowedCharacters = allowedCharacters; } public void AllowCharacter(char character) { int num = (int)character >> 5; int num2 = character & 0x1F; _allowedCharacters[num] |= (uint)(1 << num2); } public void ForbidCharacter(char character) { int num = (int)character >> 5; int num2 = character & 0x1F; _allowedCharacters[num] &= (uint)(~(1 << num2)); } public void ForbidUndefinedCharacters() { ReadOnlySpan definedCharacterBitmap = UnicodeHelpers.GetDefinedCharacterBitmap(); for (int i = 0; i < _allowedCharacters.Length; i++) { _allowedCharacters[i] &= definedCharacterBitmap[i]; } } public void Clear() { Array.Clear(_allowedCharacters, 0, _allowedCharacters.Length); } public AllowedCharactersBitmap Clone() { return new AllowedCharactersBitmap((uint[])_allowedCharacters.Clone()); } public bool IsCharacterAllowed(char character) { return IsUnicodeScalarAllowed(character); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsUnicodeScalarAllowed(int unicodeScalar) { int num = unicodeScalar >> 5; int num2 = unicodeScalar & 0x1F; return (_allowedCharacters[num] & (uint)(1 << num2)) != 0; } public unsafe int FindFirstCharacterToEncode(char* text, int textLength) { int num = 0; while (true) { if (num <= textLength - 8) { if (!IsCharacterAllowed(text[num]) || !IsCharacterAllowed(text[++num]) || !IsCharacterAllowed(text[++num]) || !IsCharacterAllowed(text[++num]) || !IsCharacterAllowed(text[++num]) || !IsCharacterAllowed(text[++num]) || !IsCharacterAllowed(text[++num]) || !IsCharacterAllowed(text[++num])) { break; } num++; continue; } while (true) { if (num <= textLength - 4) { if (!IsCharacterAllowed(text[num]) || !IsCharacterAllowed(text[++num]) || !IsCharacterAllowed(text[++num]) || !IsCharacterAllowed(text[++num])) { break; } num++; continue; } while (true) { if (num < textLength) { if (!IsCharacterAllowed(text[num])) { break; } num++; continue; } num = -1; break; } break; } break; } return num; } } } namespace System.Text.Encodings.Web { internal sealed class DefaultJavaScriptEncoder : JavaScriptEncoder { private readonly AllowedCharactersBitmap _allowedCharacters; private readonly int[] _asciiNeedsEscaping = new int[128]; private static readonly char[] s_b = new char[2] { '\\', 'b' }; private static readonly char[] s_t = new char[2] { '\\', 't' }; private static readonly char[] s_n = new char[2] { '\\', 'n' }; private static readonly char[] s_f = new char[2] { '\\', 'f' }; private static readonly char[] s_r = new char[2] { '\\', 'r' }; private static readonly char[] s_back = new char[2] { '\\', '\\' }; public override int MaxOutputCharactersPerInputCharacter => 12; public DefaultJavaScriptEncoder(TextEncoderSettings filter) { if (filter == null) { throw new ArgumentNullException("filter"); } _allowedCharacters = filter.GetAllowedCharacters(); _allowedCharacters.ForbidUndefinedCharacters(); DefaultHtmlEncoder.ForbidHtmlCharacters(_allowedCharacters); _allowedCharacters.ForbidCharacter('\\'); _allowedCharacters.ForbidCharacter('`'); for (int i = 0; i < _asciiNeedsEscaping.Length; i++) { _asciiNeedsEscaping[i] = (WillEncode(i) ? 1 : (-1)); } } public DefaultJavaScriptEncoder(params UnicodeRange[] allowedRanges) : this(new TextEncoderSettings(allowedRanges)) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool WillEncode(int unicodeScalar) { if (UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar)) { return true; } return !_allowedCharacters.IsUnicodeScalarAllowed(unicodeScalar); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe override int FindFirstCharacterToEncode(char* text, int textLength) { if (text == null) { throw new ArgumentNullException("text"); } return _allowedCharacters.FindFirstCharacterToEncode(text, textLength); } public unsafe override int FindFirstCharacterToEncodeUtf8(ReadOnlySpan utf8Text) { fixed (byte* ptr = utf8Text) { int num = 0; while (true) { if (num < utf8Text.Length) { if (System.Text.UnicodeUtility.IsAsciiCodePoint(ptr[num])) { if (DoesAsciiNeedEncoding(ptr[num]) == 1) { break; } num++; } else { if (UnicodeHelpers.DecodeScalarValueFromUtf8(utf8Text.Slice(num), out var result, out var bytesConsumed) != 0 || WillEncode((int)result)) { break; } num += bytesConsumed; } continue; } num = -1; break; } return num; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private int DoesAsciiNeedEncoding(byte value) { return _asciiNeedsEscaping[value]; } public unsafe override bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (!WillEncode(unicodeScalar)) { return TextEncoder.TryWriteScalarAsChar(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); } char[] source; switch (unicodeScalar) { case 8: source = s_b; break; case 9: source = s_t; break; case 10: source = s_n; break; case 12: source = s_f; break; case 13: source = s_r; break; case 92: source = s_back; break; default: return JavaScriptEncoderHelper.TryWriteEncodedScalarAsNumericEntity(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); } return TextEncoder.TryCopyCharacters(source, buffer, bufferLength, out numberOfCharactersWritten); } } internal sealed class DefaultJavaScriptEncoderBasicLatin : JavaScriptEncoder { internal static readonly DefaultJavaScriptEncoderBasicLatin s_singleton = new DefaultJavaScriptEncoderBasicLatin(); private static readonly char[] s_b = new char[2] { '\\', 'b' }; private static readonly char[] s_t = new char[2] { '\\', 't' }; private static readonly char[] s_n = new char[2] { '\\', 'n' }; private static readonly char[] s_f = new char[2] { '\\', 'f' }; private static readonly char[] s_r = new char[2] { '\\', 'r' }; private static readonly char[] s_back = new char[2] { '\\', '\\' }; public const int LastAsciiCharacter = 127; public override int MaxOutputCharactersPerInputCharacter => 12; private static ReadOnlySpan AllowList => new byte[256] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; private DefaultJavaScriptEncoderBasicLatin() { TextEncoderSettings textEncoderSettings = new TextEncoderSettings(UnicodeRanges.BasicLatin); AllowedCharactersBitmap allowedCharacters = textEncoderSettings.GetAllowedCharacters(); allowedCharacters.ForbidUndefinedCharacters(); DefaultHtmlEncoder.ForbidHtmlCharacters(allowedCharacters); allowedCharacters.ForbidCharacter('\\'); allowedCharacters.ForbidCharacter('`'); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool WillEncode(int unicodeScalar) { if (UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar)) { return true; } return NeedsEscaping((char)unicodeScalar); } public unsafe override int FindFirstCharacterToEncode(char* text, int textLength) { if (text == null) { throw new ArgumentNullException("text"); } if (textLength == 0) { goto IL_0048; } int num = 0; short* ptr = (short*)text; short* ptr2 = ptr + (uint)textLength; ReadOnlySpan allowList = AllowList; while (true) { char c = (char)(*ptr); if (c > '\u007f' || allowList[c] == 0) { break; } ptr++; num++; if (ptr < ptr2) { continue; } goto IL_0048; } goto IL_004a; IL_004a: return num; IL_0048: num = -1; goto IL_004a; } public unsafe override int FindFirstCharacterToEncodeUtf8(ReadOnlySpan utf8Text) { fixed (byte* ptr = utf8Text) { uint length = (uint)utf8Text.Length; if (length == 0) { goto IL_0046; } int num = 0; byte* ptr2 = ptr; byte* ptr3 = ptr2 + length; ReadOnlySpan allowList = AllowList; while (allowList[*ptr2] != 0) { ptr2++; num++; if (ptr2 < ptr3) { continue; } goto IL_0046; } goto IL_0048; IL_0048: return num; IL_0046: num = -1; goto IL_0048; } } public unsafe override bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (!WillEncode(unicodeScalar)) { return TextEncoder.TryWriteScalarAsChar(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); } char[] source; switch (unicodeScalar) { case 8: source = s_b; break; case 9: source = s_t; break; case 10: source = s_n; break; case 12: source = s_f; break; case 13: source = s_r; break; case 92: source = s_back; break; default: return JavaScriptEncoderHelper.TryWriteEncodedScalarAsNumericEntity(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); } return TextEncoder.TryCopyCharacters(source, buffer, bufferLength, out numberOfCharactersWritten); } private static bool NeedsEscaping(byte value) { return AllowList[value] == 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool NeedsEscaping(char value) { if (value <= '\u007f') { return AllowList[value] == 0; } return true; } } internal abstract class HtmlEncoder : TextEncoder { public static HtmlEncoder Default => DefaultHtmlEncoder.Singleton; public static HtmlEncoder Create(TextEncoderSettings settings) { return new DefaultHtmlEncoder(settings); } public static HtmlEncoder Create(params UnicodeRange[] allowedRanges) { return new DefaultHtmlEncoder(allowedRanges); } } internal sealed class DefaultHtmlEncoder : HtmlEncoder { private readonly AllowedCharactersBitmap _allowedCharacters; internal static readonly DefaultHtmlEncoder Singleton = new DefaultHtmlEncoder(new TextEncoderSettings(UnicodeRanges.BasicLatin)); private static readonly char[] s_quote = """.ToCharArray(); private static readonly char[] s_ampersand = "&".ToCharArray(); private static readonly char[] s_lessthan = "<".ToCharArray(); private static readonly char[] s_greaterthan = ">".ToCharArray(); public override int MaxOutputCharactersPerInputCharacter => 10; public DefaultHtmlEncoder(TextEncoderSettings settings) { if (settings == null) { throw new ArgumentNullException("settings"); } _allowedCharacters = settings.GetAllowedCharacters(); _allowedCharacters.ForbidUndefinedCharacters(); ForbidHtmlCharacters(_allowedCharacters); } internal static void ForbidHtmlCharacters(AllowedCharactersBitmap allowedCharacters) { allowedCharacters.ForbidCharacter('<'); allowedCharacters.ForbidCharacter('>'); allowedCharacters.ForbidCharacter('&'); allowedCharacters.ForbidCharacter('\''); allowedCharacters.ForbidCharacter('"'); allowedCharacters.ForbidCharacter('+'); } public DefaultHtmlEncoder(params UnicodeRange[] allowedRanges) : this(new TextEncoderSettings(allowedRanges)) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool WillEncode(int unicodeScalar) { if (UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar)) { return true; } return !_allowedCharacters.IsUnicodeScalarAllowed(unicodeScalar); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe override int FindFirstCharacterToEncode(char* text, int textLength) { return _allowedCharacters.FindFirstCharacterToEncode(text, textLength); } public unsafe override bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (!WillEncode(unicodeScalar)) { return TextEncoder.TryWriteScalarAsChar(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); } return unicodeScalar switch { 34 => TextEncoder.TryCopyCharacters(s_quote, buffer, bufferLength, out numberOfCharactersWritten), 38 => TextEncoder.TryCopyCharacters(s_ampersand, buffer, bufferLength, out numberOfCharactersWritten), 60 => TextEncoder.TryCopyCharacters(s_lessthan, buffer, bufferLength, out numberOfCharactersWritten), 62 => TextEncoder.TryCopyCharacters(s_greaterthan, buffer, bufferLength, out numberOfCharactersWritten), _ => TryWriteEncodedScalarAsNumericEntity(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten), }; } private unsafe static bool TryWriteEncodedScalarAsNumericEntity(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten) { int num = 0; int num2 = unicodeScalar; do { num++; num2 >>= 4; } while (num2 != 0); numberOfCharactersWritten = num + 4; if (num + 4 > bufferLength) { numberOfCharactersWritten = 0; return false; } *buffer = '&'; buffer++; *buffer = '#'; buffer++; *buffer = 'x'; buffer += num; do { *buffer = HexConverter.ToCharUpper(unicodeScalar); unicodeScalar >>= 4; buffer--; } while (unicodeScalar != 0); buffer += num + 1; *buffer = ';'; return true; } } internal abstract class JavaScriptEncoder : TextEncoder { public static JavaScriptEncoder Default => DefaultJavaScriptEncoderBasicLatin.s_singleton; public static JavaScriptEncoder UnsafeRelaxedJsonEscaping => UnsafeRelaxedJavaScriptEncoder.s_singleton; public static JavaScriptEncoder Create(TextEncoderSettings settings) { return new DefaultJavaScriptEncoder(settings); } public static JavaScriptEncoder Create(params UnicodeRange[] allowedRanges) { return new DefaultJavaScriptEncoder(allowedRanges); } } internal static class JavaScriptEncoderHelper { public unsafe static bool TryWriteEncodedScalarAsNumericEntity(int unicodeScalar, char* buffer, int length, out int numberOfCharactersWritten) { if (UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar)) { UnicodeHelpers.GetUtf16SurrogatePairFromAstralScalarValue(unicodeScalar, out var highSurrogate, out var lowSurrogate); if (TryWriteEncodedSingleCharacter(highSurrogate, buffer, length, out var numberOfCharactersWritten2) && TryWriteEncodedSingleCharacter(lowSurrogate, buffer + numberOfCharactersWritten2, length - numberOfCharactersWritten2, out numberOfCharactersWritten)) { numberOfCharactersWritten += numberOfCharactersWritten2; return true; } numberOfCharactersWritten = 0; return false; } return TryWriteEncodedSingleCharacter(unicodeScalar, buffer, length, out numberOfCharactersWritten); } private unsafe static bool TryWriteEncodedSingleCharacter(int unicodeScalar, char* buffer, int length, out int numberOfCharactersWritten) { if (length < 6) { numberOfCharactersWritten = 0; return false; } *buffer = '\\'; buffer++; *buffer = 'u'; buffer++; *buffer = HexConverter.ToCharUpper(unicodeScalar >> 12); buffer++; *buffer = HexConverter.ToCharUpper(unicodeScalar >> 8); buffer++; *buffer = HexConverter.ToCharUpper(unicodeScalar >> 4); buffer++; *buffer = HexConverter.ToCharUpper(unicodeScalar); numberOfCharactersWritten = 6; return true; } } internal abstract class TextEncoder { private struct AsciiNeedsEscapingData { public unsafe fixed bool Data[128]; } private const int EncodeStartingOutputBufferSize = 1024; private readonly byte[][] _asciiEscape = new byte[128][]; private volatile bool _isAsciiCacheInitialized; private AsciiNeedsEscapingData _asciiNeedsEscaping; private static readonly byte[] s_noEscape = Array.Empty(); [EditorBrowsable(EditorBrowsableState.Never)] public abstract int MaxOutputCharactersPerInputCharacter { get; } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] public unsafe abstract bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten); [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] public unsafe abstract int FindFirstCharacterToEncode(char* text, int textLength); [EditorBrowsable(EditorBrowsableState.Never)] public abstract bool WillEncode(int unicodeScalar); public virtual string Encode(string value) { if (value == null) { throw new ArgumentNullException("value"); } int num = FindFirstCharacterToEncode(MemoryExtensions.AsSpan(value)); if (num < 0) { return value; } ReadOnlySpan source = MemoryExtensions.AsSpan(value, num); Span initialBuffer = stackalloc char[1024]; System.Text.ValueStringBuilder valueStringBuilder = new System.Text.ValueStringBuilder(initialBuffer); valueStringBuilder.Append(MemoryExtensions.AsSpan(value, 0, num)); int val = Math.Max(MaxOutputCharactersPerInputCharacter, 1024); do { Span destination = valueStringBuilder.AppendSpan(Math.Max(source.Length, val)); Encode(source, destination, out var charsConsumed, out var charsWritten); if (charsWritten == 0 || (uint)charsWritten > (uint)destination.Length) { ThrowArgumentException_MaxOutputCharsPerInputChar(); } source = source.Slice(charsConsumed); valueStringBuilder.Length -= destination.Length - charsWritten; } while (!source.IsEmpty); return valueStringBuilder.ToString(); } public void Encode(TextWriter output, string value) { Encode(output, value, 0, value.Length); } public virtual void Encode(TextWriter output, string value, int startIndex, int characterCount) { if (value == null) { throw new ArgumentNullException("value"); } if (output == null) { throw new ArgumentNullException("output"); } ValidateRanges(startIndex, characterCount, value.Length); int num = FindFirstCharacterToEncode(MemoryExtensions.AsSpan(value, startIndex, characterCount)); if (num < 0) { num = characterCount; } output.WritePartialString(value, startIndex, num); if (num != characterCount) { Encode(output, MemoryExtensions.AsSpan(value, startIndex + num, characterCount - num)); } } public virtual void Encode(TextWriter output, char[] value, int startIndex, int characterCount) { if (value == null) { throw new ArgumentNullException("value"); } if (output == null) { throw new ArgumentNullException("output"); } ValidateRanges(startIndex, characterCount, value.Length); int num = FindFirstCharacterToEncode(MemoryExtensions.AsSpan(value, startIndex, characterCount)); if (num < 0) { num = characterCount; } output.Write(value, startIndex, num); if (num != characterCount) { Encode(output, MemoryExtensions.AsSpan(value, startIndex + num, characterCount - num)); } } public unsafe virtual OperationStatus EncodeUtf8(ReadOnlySpan utf8Source, Span utf8Destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { int length = utf8Source.Length; int length2 = utf8Destination.Length; char* ptr = stackalloc char[24]; byte* ptr2 = stackalloc byte[72]; int bytesConsumed2 = 0; int num = 0; OperationStatus operationStatus = OperationStatus.Done; while (true) { if (!utf8Source.IsEmpty) { uint result; do { result = utf8Source[num]; if (System.Text.UnicodeUtility.IsAsciiCodePoint(result)) { byte[] asciiEncoding = GetAsciiEncoding((byte)result); if (asciiEncoding == s_noEscape) { if (++num > utf8Destination.Length) { num--; operationStatus = OperationStatus.DestinationTooSmall; break; } continue; } if (asciiEncoding == null) { operationStatus = OperationStatus.Done; bytesConsumed2 = 1; break; } if (num > 0) { utf8Source.Slice(0, num).CopyTo(utf8Destination); utf8Source = utf8Source.Slice(num); utf8Destination = utf8Destination.Slice(num); num = 0; } if (!((ReadOnlySpan)asciiEncoding).TryCopyTo(utf8Destination)) { operationStatus = OperationStatus.DestinationTooSmall; break; } utf8Destination = utf8Destination.Slice(asciiEncoding.Length); utf8Source = utf8Source.Slice(1); } else { operationStatus = UnicodeHelpers.DecodeScalarValueFromUtf8(utf8Source.Slice(num), out result, out bytesConsumed2); if (operationStatus != 0 || WillEncode((int)result)) { break; } num += bytesConsumed2; if (num > utf8Destination.Length) { num -= bytesConsumed2; operationStatus = OperationStatus.DestinationTooSmall; break; } } } while (num < utf8Source.Length); if (num > 0) { utf8Source.Slice(0, num).CopyTo(utf8Destination); utf8Source = utf8Source.Slice(num); utf8Destination = utf8Destination.Slice(num); num = 0; } if (!utf8Source.IsEmpty) { if (operationStatus != 0) { if (operationStatus == OperationStatus.NeedMoreData) { if (!isFinalBlock) { bytesConsumed = length - utf8Source.Length; bytesWritten = length2 - utf8Destination.Length; return OperationStatus.NeedMoreData; } } else if (operationStatus == OperationStatus.DestinationTooSmall) { break; } } if (TryEncodeUnicodeScalar((int)result, ptr, 24, out var numberOfCharactersWritten)) { int bytes = Encoding.UTF8.GetBytes(ptr, numberOfCharactersWritten, ptr2, 72); ReadOnlySpan readOnlySpan = new ReadOnlySpan(ptr2, bytes); if (System.Text.UnicodeUtility.IsAsciiCodePoint(result)) { _asciiEscape[result] = readOnlySpan.ToArray(); } if (!readOnlySpan.TryCopyTo(utf8Destination)) { break; } utf8Destination = utf8Destination.Slice(bytes); utf8Source = utf8Source.Slice(bytesConsumed2); continue; } bytesConsumed = length - utf8Source.Length; bytesWritten = length2 - utf8Destination.Length; return OperationStatus.InvalidData; } } bytesConsumed = length; bytesWritten = length2 - utf8Destination.Length; return OperationStatus.Done; } bytesConsumed = length - utf8Source.Length; bytesWritten = length2 - utf8Destination.Length; return OperationStatus.DestinationTooSmall; } public virtual OperationStatus Encode(ReadOnlySpan source, Span destination, out int charsConsumed, out int charsWritten, bool isFinalBlock = true) { if (source.IsEmpty) { charsConsumed = 0; charsWritten = 0; return OperationStatus.Done; } ReadOnlySpan text = source; if (destination.Length < source.Length) { text = source.Slice(0, destination.Length); } int num = FindFirstCharacterToEncode(text); if (num < 0) { num = text.Length; } source.Slice(0, num).CopyTo(destination); if (num == source.Length) { charsConsumed = source.Length; charsWritten = source.Length; return OperationStatus.Done; } int charsConsumed2; int charsWritten2; OperationStatus result = EncodeCore(source.Slice(num), destination.Slice(num), out charsConsumed2, out charsWritten2, isFinalBlock); charsConsumed = num + charsConsumed2; charsWritten = num + charsWritten2; return result; unsafe OperationStatus EncodeCore(ReadOnlySpan source, Span destination, out int charsConsumed, out int charsWritten, bool isFinalBlock) { if (destination.IsEmpty) { destination = Array.Empty(); } int num2 = 0; int num3 = 0; OperationStatus result2; while (true) { if ((uint)num3 >= (uint)source.Length) { result2 = OperationStatus.Done; break; } int num4 = source[num3]; if (!System.Text.UnicodeUtility.IsSurrogateCodePoint((uint)num4)) { if (!WillEncode(num4)) { if ((uint)num2 < (uint)destination.Length) { destination[num2++] = (char)num4; num3++; continue; } goto IL_0143; } } else { uint num5 = (uint)num4; num4 = 65533; if (System.Text.UnicodeUtility.IsHighSurrogateCodePoint(num5)) { int num6 = num3 + 1; if ((uint)num6 >= (uint)source.Length) { if (!isFinalBlock) { result2 = OperationStatus.NeedMoreData; break; } } else { uint num7 = source[num6]; if (System.Text.UnicodeUtility.IsLowSurrogateCodePoint(num7)) { num4 = (int)System.Text.UnicodeUtility.GetScalarFromUtf16SurrogatePair(num5, num7); if (!WillEncode(num4)) { if ((uint)(num2 + 1) < (uint)destination.Length) { destination[num2] = (char)num5; destination[num2 + 1] = (char)num7; num2 += 2; num3 += 2; continue; } goto IL_0143; } } } } } int numberOfCharactersWritten; fixed (char* ptr = &MemoryMarshal.GetReference(destination)) { if (!TryEncodeUnicodeScalar(num4, ptr + num2, destination.Length - num2, out numberOfCharactersWritten)) { goto IL_0143; } } num3 += System.Text.UnicodeUtility.GetUtf16SequenceLength((uint)num4); num2 += numberOfCharactersWritten; continue; IL_0143: result2 = OperationStatus.DestinationTooSmall; break; } charsConsumed = num3; charsWritten = num2; return result2; } } private void Encode(TextWriter output, ReadOnlySpan value) { int val = Math.Max(MaxOutputCharactersPerInputCharacter, 1024); char[] array = ArrayPool.Shared.Rent(Math.Max(value.Length, val)); Span destination = array; do { Encode(value, destination, out var charsConsumed, out var charsWritten); if (charsWritten == 0 || (uint)charsWritten > (uint)destination.Length) { ThrowArgumentException_MaxOutputCharsPerInputChar(); } output.Write(array, 0, charsWritten); value = value.Slice(charsConsumed); } while (!value.IsEmpty); ArrayPool.Shared.Return(array); } private unsafe int FindFirstCharacterToEncode(ReadOnlySpan text) { fixed (char* text2 = &MemoryMarshal.GetReference(text)) { return FindFirstCharacterToEncode(text2, text.Length); } } [EditorBrowsable(EditorBrowsableState.Never)] public unsafe virtual int FindFirstCharacterToEncodeUtf8(ReadOnlySpan utf8Text) { if (!_isAsciiCacheInitialized) { InitializeAsciiCache(); } fixed (byte* ptr = utf8Text) { int num = 0; while (true) { if (num < utf8Text.Length) { if (System.Text.UnicodeUtility.IsAsciiCodePoint(ptr[num])) { if (DoesAsciiNeedEncoding(ptr[num])) { break; } num++; } else { if (UnicodeHelpers.DecodeScalarValueFromUtf8(utf8Text.Slice(num), out var result, out var bytesConsumed) != 0 || WillEncode((int)result)) { break; } num += bytesConsumed; } continue; } num = -1; break; } return num; } } internal unsafe static bool TryCopyCharacters(char[] source, char* destination, int destinationLength, out int numberOfCharactersWritten) { if (destinationLength < source.Length) { numberOfCharactersWritten = 0; return false; } for (int i = 0; i < source.Length; i++) { destination[i] = source[i]; } numberOfCharactersWritten = source.Length; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe static bool TryWriteScalarAsChar(int unicodeScalar, char* destination, int destinationLength, out int numberOfCharactersWritten) { if (destinationLength < 1) { numberOfCharactersWritten = 0; return false; } *destination = (char)unicodeScalar; numberOfCharactersWritten = 1; return true; } private static void ValidateRanges(int startIndex, int characterCount, int actualInputLength) { if (startIndex < 0 || startIndex > actualInputLength) { throw new ArgumentOutOfRangeException("startIndex"); } if (characterCount < 0 || characterCount > actualInputLength - startIndex) { throw new ArgumentOutOfRangeException("characterCount"); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private byte[] GetAsciiEncoding(byte value) { byte[] array = _asciiEscape[value]; if (array == null && !WillEncode(value)) { array = s_noEscape; _asciiEscape[value] = array; } return array; } [MethodImpl(MethodImplOptions.NoInlining)] private unsafe void InitializeAsciiCache() { for (int i = 0; i < 128; i++) { _asciiNeedsEscaping.Data[i] = WillEncode(i); } _isAsciiCacheInitialized = true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe bool DoesAsciiNeedEncoding(uint value) { return _asciiNeedsEscaping.Data[value]; } private static void ThrowArgumentException_MaxOutputCharsPerInputChar() { throw new ArgumentException(SR.TextEncoderDoesNotImplementMaxOutputCharsPerInputChar); } } internal class TextEncoderSettings { private readonly AllowedCharactersBitmap _allowedCharactersBitmap; public TextEncoderSettings() { _allowedCharactersBitmap = AllowedCharactersBitmap.CreateNew(); } public TextEncoderSettings(TextEncoderSettings other) { if (other == null) { throw new ArgumentNullException("other"); } _allowedCharactersBitmap = AllowedCharactersBitmap.CreateNew(); AllowCodePoints(other.GetAllowedCodePoints()); } public TextEncoderSettings(params UnicodeRange[] allowedRanges) { if (allowedRanges == null) { throw new ArgumentNullException("allowedRanges"); } _allowedCharactersBitmap = AllowedCharactersBitmap.CreateNew(); AllowRanges(allowedRanges); } public virtual void AllowCharacter(char character) { _allowedCharactersBitmap.AllowCharacter(character); } public virtual void AllowCharacters(params char[] characters) { if (characters == null) { throw new ArgumentNullException("characters"); } for (int i = 0; i < characters.Length; i++) { _allowedCharactersBitmap.AllowCharacter(characters[i]); } } public virtual void AllowCodePoints(IEnumerable codePoints) { if (codePoints == null) { throw new ArgumentNullException("codePoints"); } foreach (int codePoint in codePoints) { char c = (char)codePoint; if (codePoint == c) { _allowedCharactersBitmap.AllowCharacter(c); } } } public virtual void AllowRange(UnicodeRange range) { if (range == null) { throw new ArgumentNullException("range"); } int firstCodePoint = range.FirstCodePoint; int length = range.Length; for (int i = 0; i < length; i++) { _allowedCharactersBitmap.AllowCharacter((char)(firstCodePoint + i)); } } public virtual void AllowRanges(params UnicodeRange[] ranges) { if (ranges == null) { throw new ArgumentNullException("ranges"); } for (int i = 0; i < ranges.Length; i++) { AllowRange(ranges[i]); } } public virtual void Clear() { _allowedCharactersBitmap.Clear(); } public virtual void ForbidCharacter(char character) { _allowedCharactersBitmap.ForbidCharacter(character); } public virtual void ForbidCharacters(params char[] characters) { if (characters == null) { throw new ArgumentNullException("characters"); } for (int i = 0; i < characters.Length; i++) { _allowedCharactersBitmap.ForbidCharacter(characters[i]); } } public virtual void ForbidRange(UnicodeRange range) { if (range == null) { throw new ArgumentNullException("range"); } int firstCodePoint = range.FirstCodePoint; int length = range.Length; for (int i = 0; i < length; i++) { _allowedCharactersBitmap.ForbidCharacter((char)(firstCodePoint + i)); } } public virtual void ForbidRanges(params UnicodeRange[] ranges) { if (ranges == null) { throw new ArgumentNullException("ranges"); } for (int i = 0; i < ranges.Length; i++) { ForbidRange(ranges[i]); } } internal AllowedCharactersBitmap GetAllowedCharacters() { return _allowedCharactersBitmap.Clone(); } public virtual IEnumerable GetAllowedCodePoints() { for (int i = 0; i < 65536; i++) { if (_allowedCharactersBitmap.IsCharacterAllowed((char)i)) { yield return i; } } } } internal sealed class UnsafeRelaxedJavaScriptEncoder : JavaScriptEncoder { private readonly AllowedCharactersBitmap _allowedCharacters; internal static readonly UnsafeRelaxedJavaScriptEncoder s_singleton = new UnsafeRelaxedJavaScriptEncoder(); private static readonly char[] s_b = new char[2] { '\\', 'b' }; private static readonly char[] s_t = new char[2] { '\\', 't' }; private static readonly char[] s_n = new char[2] { '\\', 'n' }; private static readonly char[] s_f = new char[2] { '\\', 'f' }; private static readonly char[] s_r = new char[2] { '\\', 'r' }; private static readonly char[] s_back = new char[2] { '\\', '\\' }; private static readonly char[] s_doubleQuote = new char[2] { '\\', '"' }; public override int MaxOutputCharactersPerInputCharacter => 12; private UnsafeRelaxedJavaScriptEncoder() { TextEncoderSettings textEncoderSettings = new TextEncoderSettings(UnicodeRanges.All); _allowedCharacters = textEncoderSettings.GetAllowedCharacters(); _allowedCharacters.ForbidUndefinedCharacters(); _allowedCharacters.ForbidCharacter('"'); _allowedCharacters.ForbidCharacter('\\'); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool WillEncode(int unicodeScalar) { if (UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar)) { return true; } return !_allowedCharacters.IsUnicodeScalarAllowed(unicodeScalar); } public unsafe override int FindFirstCharacterToEncode(char* text, int textLength) { if (text == null) { throw new ArgumentNullException("text"); } int num = 0; while (true) { if (num < textLength) { if (!_allowedCharacters.IsCharacterAllowed(text[num])) { break; } num++; continue; } num = -1; break; } return num; } public unsafe override int FindFirstCharacterToEncodeUtf8(ReadOnlySpan utf8Text) { fixed (byte* ptr = utf8Text) { int num = 0; while (true) { if (num < utf8Text.Length) { if (System.Text.UnicodeUtility.IsAsciiCodePoint(ptr[num])) { if (!_allowedCharacters.IsUnicodeScalarAllowed(ptr[num])) { break; } num++; } else { if (UnicodeHelpers.DecodeScalarValueFromUtf8(utf8Text.Slice(num), out var result, out var bytesConsumed) != 0 || WillEncode((int)result)) { break; } num += bytesConsumed; } continue; } num = -1; break; } return num; } } public unsafe override bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (!WillEncode(unicodeScalar)) { return TextEncoder.TryWriteScalarAsChar(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); } char[] source; switch (unicodeScalar) { case 34: source = s_doubleQuote; break; case 8: source = s_b; break; case 9: source = s_t; break; case 10: source = s_n; break; case 12: source = s_f; break; case 13: source = s_r; break; case 92: source = s_back; break; default: return JavaScriptEncoderHelper.TryWriteEncodedScalarAsNumericEntity(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); } return TextEncoder.TryCopyCharacters(source, buffer, bufferLength, out numberOfCharactersWritten); } } internal abstract class UrlEncoder : TextEncoder { public static UrlEncoder Default => DefaultUrlEncoder.Singleton; public static UrlEncoder Create(TextEncoderSettings settings) { return new DefaultUrlEncoder(settings); } public static UrlEncoder Create(params UnicodeRange[] allowedRanges) { return new DefaultUrlEncoder(allowedRanges); } } internal sealed class DefaultUrlEncoder : UrlEncoder { private readonly AllowedCharactersBitmap _allowedCharacters; internal static readonly DefaultUrlEncoder Singleton = new DefaultUrlEncoder(new TextEncoderSettings(UnicodeRanges.BasicLatin)); public override int MaxOutputCharactersPerInputCharacter => 12; public DefaultUrlEncoder(TextEncoderSettings filter) { if (filter == null) { throw new ArgumentNullException("filter"); } _allowedCharacters = filter.GetAllowedCharacters(); _allowedCharacters.ForbidUndefinedCharacters(); DefaultHtmlEncoder.ForbidHtmlCharacters(_allowedCharacters); string text = " #%/:=?[\\]^`{|}"; foreach (char character in text) { _allowedCharacters.ForbidCharacter(character); } for (int j = 0; j < 16; j++) { _allowedCharacters.ForbidCharacter((char)(0xFFF0u | (uint)j)); } } public DefaultUrlEncoder(params UnicodeRange[] allowedRanges) : this(new TextEncoderSettings(allowedRanges)) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool WillEncode(int unicodeScalar) { if (UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar)) { return true; } return !_allowedCharacters.IsUnicodeScalarAllowed(unicodeScalar); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe override int FindFirstCharacterToEncode(char* text, int textLength) { if (text == null) { throw new ArgumentNullException("text"); } return _allowedCharacters.FindFirstCharacterToEncode(text, textLength); } public unsafe override bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (!WillEncode(unicodeScalar)) { return TextEncoder.TryWriteScalarAsChar(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); } numberOfCharactersWritten = 0; uint num = (uint)UnicodeHelpers.GetUtf8RepresentationForScalarValue((uint)unicodeScalar); do { if (numberOfCharactersWritten + 3 > bufferLength) { numberOfCharactersWritten = 0; return false; } *buffer = '%'; buffer++; *buffer = HexConverter.ToCharUpper((int)num >> 4); buffer++; *buffer = HexConverter.ToCharUpper((int)num); buffer++; numberOfCharactersWritten += 3; } while ((num >>= 8) != 0); return true; } } } namespace System.IO { internal static class TextWriterExtensions { public static void WritePartialString(this TextWriter writer, string value, int offset, int count) { if (offset == 0 && count == value.Length) { writer.Write(value); return; } ReadOnlySpan buffer = MemoryExtensions.AsSpan(value, offset, count); writer.Write(buffer); } } } [CompilerGenerated] internal sealed class { [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 256)] private struct __StaticArrayInitTypeSize=256 { } [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 8192)] private struct __StaticArrayInitTypeSize=8192 { } internal static readonly __StaticArrayInitTypeSize=256 21244F82B210125632917591768F6BF22EB6861F80C6C25A25BD26DFB580EA7B/* Not supported: data(FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 00 01 02 03 04 05 06 07 08 09 FF FF FF FF FF FF FF 0A 0B 0C 0D 0E 0F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 0A 0B 0C 0D 0E 0F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF) */; internal static readonly __StaticArrayInitTypeSize=8192 8B30AFDCF07C4ABDFE0FAF65F79FC40A2E9AC497C42B1BA5C996BDFB3F6EC2F6/* Not supported: data(00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF 7F 00 00 00 00 FE FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FC F0 D7 FF FF FB FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FE FF FF FF 7F FE FF FF FF FF FF E7 FE FF FF FF FF FF FF 00 FF FF FF 87 1F 00 FF FF FF DF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF BF FF FF FF FF FF FF FF E7 FF FF FF FF FF FF FF FF FF FF FF FF 03 00 FF FF FF FF FF FF FF E7 FF FF FF FF FF 3F FF 7F FF FF FF 4F FF 07 00 00 00 00 00 00 FF FF DF FF FF 00 F8 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF EF 9F F9 FF FF FD C5 F3 9F 79 80 B0 CF FF FF 7F EE 87 F9 FF FF FD 6D D3 87 39 02 5E C0 FF 7F 00 EE BF FB FF FF FD ED F3 BF 3B 01 00 CF FF 03 FE EE 9F F9 FF FF FD ED F3 9F 39 E0 B0 CF FF FF 00 EC C7 3D D6 18 C7 FF C3 C7 3D 81 00 C0 FF FF 07 FF DF FD FF FF FD FF E3 DF 3D 60 07 CF FF 80 FF FF DF FD FF FF FD EF F3 DF 3D 60 40 CF FF 06 00 FF DF FD FF FF FF FF FF DF FD F0 FF CF FF FF FF EE FF 7F FC FF FF FB 2F 7F 84 5F FF C0 FF 1C 00 FE FF FF FF FF FF FF 87 FF FF FF 0F 00 00 00 00 D6 F7 FF FF AF FF FF 3F 5F 3F FF F3 00 00 00 00 FF FF FF FF FF FF FF FF FF FE FF FF FF 1F FE FF FF FF FF FE FF FF FF DF FF DF FF 07 00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF BF 20 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 3D 7F 3D FF FF FF FF FF 3D FF FF FF FF 3D 7F 3D FF 7F FF FF FF FF FF FF FF 3D FF FF FF FF FF FF FF FF E7 FF FF FF 1F FF FF FF 03 FF FF FF FF FF FF FF FF FF FF 3F 3F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FE FF FF 1F FF FF FF FF FF FF FF FF FF FF FF 01 FF DF 1F 00 FF FF 7F 00 FF FF 0F 00 FF DF 0D 00 FF FF FF FF FF FF FF FF FF FF FF 3F FF 03 FF 03 FF 7F FF 03 FF FF FF FF FF FF FF FF FF FF FF 01 FF FF FF FF FF 07 FF FF FF FF FF FF FF FF 3F 00 FF FF FF 7F FF 0F FF 0F F1 FF FF FF FF 3F 1F 00 FF FF FF FF FF 0F FF FF FF 03 FF C7 FF FF FF FF FF FF FF CF FF FF FF FF FF FF FF 7F FF FF FF 9F FF 03 FF 03 FF 3F FF FF 01 00 00 00 00 00 00 00 FF FF FF FF FF FF FF FF FF 0F FF FF FF FF FF 1F FF FF FF FF FF FF FF FF FF FF FF FF FF FF 0F F0 FF FF FF FF FF FF FF F8 FF E3 FF FF FF FF FF FF FF 01 FF FF FF FF FF E7 FF 00 FF FF FF FF FF 07 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FB FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 3F 3F FF FF FF FF 3F 3F FF AA FF FF FF 3F FF FF FF FF FF FF DF FF DF FF CF EF FF FF DC 7F 00 F8 FF FF FF 7C FF FF FF FF FF 7F DF FF F3 FF FF 7F FF 1F FF FF FF FF 00 00 FF FF FF FF 01 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 0F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 7F 00 00 00 FF 07 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF CF FF FF FF BF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 7F FF FF FF FF FF 7F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 0F FE FF FF FF FF BF 20 FF FF FF FF FF FF FF 80 01 80 FF FF 7F 00 7F 7F 7F 7F 7F 7F 7F 7F FF FF FF FF FF FF FF FF FF FF FF FF FF FF 07 00 00 00 00 00 FF FF FF FB FF FF FF FF FF FF FF FF FF FF 0F 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 3F 00 00 00 FF 0F FE FF FF FF FF FF FF FF FE FF FF FF FF FF FF FF FF FF 7F FE FF FF FF FF FF FF FF FF FF FF FF FF E0 FF FF FF FF FF FE FF FF FF FF FF FF FF FF FF FF 7F FF FF FF FF FF FF FF FF FF FF 0F 00 FF FF FF FF FF 7F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 1F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 1F FF FF FF FF FF FF 7F 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 0F 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FC 07 00 00 00 00 E0 FF FF FF FF FF FF 1F FF 03 FF FF FF FF FF FF FF 00 FF FF FF FF FF FF FF FF 3F C0 FF 03 FF FF FF FF FF FF FF FF FF FF FF FF FF FF 0F 80 FF FF FF 1F FF FF FF FF FF FF FF FF FF BF FF C3 FF FF FF 7F FF FF FF FF FF FF 7F 00 FF 3F FF F3 FF FF FF FF FF FF FF FF FF FF FF FF 07 00 00 F8 FF FF 7F 00 7E 7E 7E 00 7F 7F FF FF FF FF FF FF FF 0F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 3F FF 03 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 0F 00 FF FF 7F F8 FF FF FF FF FF 0F 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 3F FF FF FF FF FF FF FF FF FF FF FF FF FF 03 00 00 00 00 7F 00 F8 E0 FF FF 7F 5F DB FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 03 00 F8 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 00 00 FF FF FF FF FF FF FF FF FC FF FF FF FF FF FF 00 00 00 00 00 FF 3F FF FF FF 03 FF FF FF FF FF FF F7 FF 7F 0F DF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 1F FE FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 7F FC FC FC 1C 7F 7F 00 3E) */; internal static readonly __StaticArrayInitTypeSize=256 EFE627BE173681E4F55F4133AB4C1782E26D1080CB80CDB6BFAAC81416A2714E/* Not supported: data(00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 01 00 01 01 01 00 00 01 01 01 00 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 00 01 00 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 00 01 01 01 00 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00) */; } namespace FxResources.System.Text.Json { internal static class SR { } } namespace System { internal static class HexConverter { public enum Casing : uint { Upper = 0u, Lower = 8224u } public static ReadOnlySpan CharToHexLookup => new byte[256] { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToBytesBuffer(byte value, Span buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (byte)num2; buffer[startingIndex] = (byte)(num2 >> 8); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToCharsBuffer(byte value, Span buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (char)(num2 & 0xFFu); buffer[startingIndex] = (char)(num2 >> 8); } public static void EncodeToUtf16(ReadOnlySpan bytes, Span chars, Casing casing = Casing.Upper) { for (int i = 0; i < bytes.Length; i++) { ToCharsBuffer(bytes[i], chars, i * 2, casing); } } public static string ToString(ReadOnlySpan bytes, Casing casing = Casing.Upper) { Span span = default(Span); if (bytes.Length > 16) { char[] array = new char[bytes.Length * 2]; span = MemoryExtensions.AsSpan(array); } else { span = stackalloc char[bytes.Length * 2]; } int num = 0; ReadOnlySpan readOnlySpan = bytes; for (int i = 0; i < readOnlySpan.Length; i++) { byte value = readOnlySpan[i]; ToCharsBuffer(value, span, num, casing); num += 2; } return span.ToString(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharUpper(int value) { value &= 0xF; value += 48; if (value > 57) { value += 7; } return (char)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharLower(int value) { value &= 0xF; value += 48; if (value > 57) { value += 39; } return (char)value; } public static bool TryDecodeFromUtf16(ReadOnlySpan chars, Span bytes) { int charsProcessed; return TryDecodeFromUtf16(chars, bytes, out charsProcessed); } public static bool TryDecodeFromUtf16(ReadOnlySpan chars, Span bytes, out int charsProcessed) { int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; while (num2 < bytes.Length) { num3 = FromChar(chars[num + 1]); num4 = FromChar(chars[num]); if ((num3 | num4) == 255) { break; } bytes[num2++] = (byte)((num4 << 4) | num3); num += 2; } if (num3 == 255) { num++; } charsProcessed = num; return (num3 | num4) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromChar(int c) { if (c < CharToHexLookup.Length) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromUpperChar(int c) { if (c <= 71) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromLowerChar(int c) { switch (c) { case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return c - 48; case 97: case 98: case 99: case 100: case 101: case 102: return c - 97 + 10; default: return 255; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexChar(int c) { return FromChar(c) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexUpperChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 65) <= 5u; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexLowerChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 97) <= 5u; } return true; } } internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(FxResources.System.Text.Json.SR))); internal static string ArrayDepthTooLarge => GetResourceString("ArrayDepthTooLarge"); internal static string CallFlushToAvoidDataLoss => GetResourceString("CallFlushToAvoidDataLoss"); internal static string CannotReadIncompleteUTF16 => GetResourceString("CannotReadIncompleteUTF16"); internal static string CannotReadInvalidUTF16 => GetResourceString("CannotReadInvalidUTF16"); internal static string CannotStartObjectArrayAfterPrimitiveOrClose => GetResourceString("CannotStartObjectArrayAfterPrimitiveOrClose"); internal static string CannotStartObjectArrayWithoutProperty => GetResourceString("CannotStartObjectArrayWithoutProperty"); internal static string CannotTranscodeInvalidUtf8 => GetResourceString("CannotTranscodeInvalidUtf8"); internal static string CannotDecodeInvalidBase64 => GetResourceString("CannotDecodeInvalidBase64"); internal static string CannotTranscodeInvalidUtf16 => GetResourceString("CannotTranscodeInvalidUtf16"); internal static string CannotEncodeInvalidUTF16 => GetResourceString("CannotEncodeInvalidUTF16"); internal static string CannotEncodeInvalidUTF8 => GetResourceString("CannotEncodeInvalidUTF8"); internal static string CannotWritePropertyWithinArray => GetResourceString("CannotWritePropertyWithinArray"); internal static string CannotWritePropertyAfterProperty => GetResourceString("CannotWritePropertyAfterProperty"); internal static string CannotWriteValueAfterPrimitiveOrClose => GetResourceString("CannotWriteValueAfterPrimitiveOrClose"); internal static string CannotWriteValueWithinObject => GetResourceString("CannotWriteValueWithinObject"); internal static string DepthTooLarge => GetResourceString("DepthTooLarge"); internal static string EmptyJsonIsInvalid => GetResourceString("EmptyJsonIsInvalid"); internal static string EndOfCommentNotFound => GetResourceString("EndOfCommentNotFound"); internal static string EndOfStringNotFound => GetResourceString("EndOfStringNotFound"); internal static string ExpectedEndAfterSingleJson => GetResourceString("ExpectedEndAfterSingleJson"); internal static string ExpectedEndOfDigitNotFound => GetResourceString("ExpectedEndOfDigitNotFound"); internal static string ExpectedFalse => GetResourceString("ExpectedFalse"); internal static string ExpectedJsonTokens => GetResourceString("ExpectedJsonTokens"); internal static string ExpectedOneCompleteToken => GetResourceString("ExpectedOneCompleteToken"); internal static string ExpectedNextDigitEValueNotFound => GetResourceString("ExpectedNextDigitEValueNotFound"); internal static string ExpectedNull => GetResourceString("ExpectedNull"); internal static string ExpectedSeparatorAfterPropertyNameNotFound => GetResourceString("ExpectedSeparatorAfterPropertyNameNotFound"); internal static string ExpectedStartOfPropertyNotFound => GetResourceString("ExpectedStartOfPropertyNotFound"); internal static string ExpectedStartOfPropertyOrValueNotFound => GetResourceString("ExpectedStartOfPropertyOrValueNotFound"); internal static string ExpectedStartOfValueNotFound => GetResourceString("ExpectedStartOfValueNotFound"); internal static string ExpectedTrue => GetResourceString("ExpectedTrue"); internal static string ExpectedValueAfterPropertyNameNotFound => GetResourceString("ExpectedValueAfterPropertyNameNotFound"); internal static string FailedToGetLargerSpan => GetResourceString("FailedToGetLargerSpan"); internal static string FoundInvalidCharacter => GetResourceString("FoundInvalidCharacter"); internal static string InvalidCast => GetResourceString("InvalidCast"); internal static string InvalidCharacterAfterEscapeWithinString => GetResourceString("InvalidCharacterAfterEscapeWithinString"); internal static string InvalidCharacterWithinString => GetResourceString("InvalidCharacterWithinString"); internal static string InvalidEndOfJsonNonPrimitive => GetResourceString("InvalidEndOfJsonNonPrimitive"); internal static string InvalidHexCharacterWithinString => GetResourceString("InvalidHexCharacterWithinString"); internal static string JsonDocumentDoesNotSupportComments => GetResourceString("JsonDocumentDoesNotSupportComments"); internal static string JsonElementHasWrongType => GetResourceString("JsonElementHasWrongType"); internal static string MaxDepthMustBePositive => GetResourceString("MaxDepthMustBePositive"); internal static string CommentHandlingMustBeValid => GetResourceString("CommentHandlingMustBeValid"); internal static string MismatchedObjectArray => GetResourceString("MismatchedObjectArray"); internal static string CannotWriteEndAfterProperty => GetResourceString("CannotWriteEndAfterProperty"); internal static string ObjectDepthTooLarge => GetResourceString("ObjectDepthTooLarge"); internal static string PropertyNameTooLarge => GetResourceString("PropertyNameTooLarge"); internal static string FormatDecimal => GetResourceString("FormatDecimal"); internal static string FormatDouble => GetResourceString("FormatDouble"); internal static string FormatInt32 => GetResourceString("FormatInt32"); internal static string FormatInt64 => GetResourceString("FormatInt64"); internal static string FormatSingle => GetResourceString("FormatSingle"); internal static string FormatUInt32 => GetResourceString("FormatUInt32"); internal static string FormatUInt64 => GetResourceString("FormatUInt64"); internal static string RequiredDigitNotFoundAfterDecimal => GetResourceString("RequiredDigitNotFoundAfterDecimal"); internal static string RequiredDigitNotFoundAfterSign => GetResourceString("RequiredDigitNotFoundAfterSign"); internal static string RequiredDigitNotFoundEndOfData => GetResourceString("RequiredDigitNotFoundEndOfData"); internal static string SpecialNumberValuesNotSupported => GetResourceString("SpecialNumberValuesNotSupported"); internal static string ValueTooLarge => GetResourceString("ValueTooLarge"); internal static string ZeroDepthAtEnd => GetResourceString("ZeroDepthAtEnd"); internal static string DeserializeUnableToConvertValue => GetResourceString("DeserializeUnableToConvertValue"); internal static string DeserializeWrongType => GetResourceString("DeserializeWrongType"); internal static string SerializationInvalidBufferSize => GetResourceString("SerializationInvalidBufferSize"); internal static string BufferWriterAdvancedTooFar => GetResourceString("BufferWriterAdvancedTooFar"); internal static string InvalidComparison => GetResourceString("InvalidComparison"); internal static string FormatDateTime => GetResourceString("FormatDateTime"); internal static string FormatDateTimeOffset => GetResourceString("FormatDateTimeOffset"); internal static string FormatGuid => GetResourceString("FormatGuid"); internal static string ExpectedStartOfPropertyOrValueAfterComment => GetResourceString("ExpectedStartOfPropertyOrValueAfterComment"); internal static string TrailingCommaNotAllowedBeforeArrayEnd => GetResourceString("TrailingCommaNotAllowedBeforeArrayEnd"); internal static string TrailingCommaNotAllowedBeforeObjectEnd => GetResourceString("TrailingCommaNotAllowedBeforeObjectEnd"); internal static string SerializerOptionsImmutable => GetResourceString("SerializerOptionsImmutable"); internal static string StreamNotWritable => GetResourceString("StreamNotWritable"); internal static string CannotWriteCommentWithEmbeddedDelimiter => GetResourceString("CannotWriteCommentWithEmbeddedDelimiter"); internal static string SerializerPropertyNameConflict => GetResourceString("SerializerPropertyNameConflict"); internal static string SerializerPropertyNameNull => GetResourceString("SerializerPropertyNameNull"); internal static string DeserializeDuplicateKey => GetResourceString("DeserializeDuplicateKey"); internal static string SerializationDataExtensionPropertyInvalid => GetResourceString("SerializationDataExtensionPropertyInvalid"); internal static string SerializationDuplicateTypeAttribute => GetResourceString("SerializationDuplicateTypeAttribute"); internal static string SerializationNotSupportedType => GetResourceString("SerializationNotSupportedType"); internal static string InvalidCharacterAtStartOfComment => GetResourceString("InvalidCharacterAtStartOfComment"); internal static string UnexpectedEndOfDataWhileReadingComment => GetResourceString("UnexpectedEndOfDataWhileReadingComment"); internal static string CannotSkip => GetResourceString("CannotSkip"); internal static string NotEnoughData => GetResourceString("NotEnoughData"); internal static string UnexpectedEndOfLineSeparator => GetResourceString("UnexpectedEndOfLineSeparator"); internal static string JsonSerializerDoesNotSupportComments => GetResourceString("JsonSerializerDoesNotSupportComments"); internal static string DeserializeNoConstructor => GetResourceString("DeserializeNoConstructor"); internal static string DeserializePolymorphicInterface => GetResourceString("DeserializePolymorphicInterface"); internal static string SerializationConverterOnAttributeNotCompatible => GetResourceString("SerializationConverterOnAttributeNotCompatible"); internal static string SerializationConverterOnAttributeInvalid => GetResourceString("SerializationConverterOnAttributeInvalid"); internal static string SerializationConverterRead => GetResourceString("SerializationConverterRead"); internal static string SerializationConverterNotCompatible => GetResourceString("SerializationConverterNotCompatible"); internal static string SerializationConverterWrite => GetResourceString("SerializationConverterWrite"); internal static string NamingPolicyReturnNull => GetResourceString("NamingPolicyReturnNull"); internal static string SerializationDuplicateAttribute => GetResourceString("SerializationDuplicateAttribute"); internal static string SerializeUnableToSerialize => GetResourceString("SerializeUnableToSerialize"); internal static string FormatByte => GetResourceString("FormatByte"); internal static string FormatInt16 => GetResourceString("FormatInt16"); internal static string FormatSByte => GetResourceString("FormatSByte"); internal static string FormatUInt16 => GetResourceString("FormatUInt16"); internal static string SerializerCycleDetected => GetResourceString("SerializerCycleDetected"); internal static string EmptyStringToInitializeNumber => GetResourceString("EmptyStringToInitializeNumber"); internal static string JsonObjectDuplicateKey => GetResourceString("JsonObjectDuplicateKey"); internal static string PropertyNotFound => GetResourceString("PropertyNotFound"); internal static string PropertyTypeMismatch => GetResourceString("PropertyTypeMismatch"); internal static string InvalidDuplicatePropertyNameHandling => GetResourceString("InvalidDuplicatePropertyNameHandling"); internal static string InvalidLeadingZeroInNumber => GetResourceString("InvalidLeadingZeroInNumber"); internal static string ArrayModifiedDuringIteration => GetResourceString("ArrayModifiedDuringIteration"); internal static string NotNodeJsonElementParent => GetResourceString("NotNodeJsonElementParent"); internal static string MetadataCannotParsePreservedObjectToImmutable => GetResourceString("MetadataCannotParsePreservedObjectToImmutable"); internal static string MetadataDuplicateIdFound => GetResourceString("MetadataDuplicateIdFound"); internal static string MetadataIdIsNotFirstProperty => GetResourceString("MetadataIdIsNotFirstProperty"); internal static string MetadataInvalidReferenceToValueType => GetResourceString("MetadataInvalidReferenceToValueType"); internal static string MetadataInvalidTokenAfterValues => GetResourceString("MetadataInvalidTokenAfterValues"); internal static string MetadataPreservedArrayFailed => GetResourceString("MetadataPreservedArrayFailed"); internal static string MetadataPreservedArrayInvalidProperty => GetResourceString("MetadataPreservedArrayInvalidProperty"); internal static string MetadataPreservedArrayPropertyNotFound => GetResourceString("MetadataPreservedArrayPropertyNotFound"); internal static string MetadataReferenceCannotContainOtherProperties => GetResourceString("MetadataReferenceCannotContainOtherProperties"); internal static string MetadataReferenceNotFound => GetResourceString("MetadataReferenceNotFound"); internal static string MetadataValueWasNotString => GetResourceString("MetadataValueWasNotString"); internal static string MetadataInvalidPropertyWithLeadingDollarSign => GetResourceString("MetadataInvalidPropertyWithLeadingDollarSign"); internal static string MultipleMembersBindWithConstructorParameter => GetResourceString("MultipleMembersBindWithConstructorParameter"); internal static string ConstructorParamIncompleteBinding => GetResourceString("ConstructorParamIncompleteBinding"); internal static string ConstructorMaxOf64Parameters => GetResourceString("ConstructorMaxOf64Parameters"); internal static string ObjectWithParameterizedCtorRefMetadataNotHonored => GetResourceString("ObjectWithParameterizedCtorRefMetadataNotHonored"); internal static string SerializerConverterFactoryReturnsNull => GetResourceString("SerializerConverterFactoryReturnsNull"); internal static string SerializationNotSupportedParentType => GetResourceString("SerializationNotSupportedParentType"); internal static string ExtensionDataCannotBindToCtorParam => GetResourceString("ExtensionDataCannotBindToCtorParam"); internal static string BufferMaximumSizeExceeded => GetResourceString("BufferMaximumSizeExceeded"); internal static string CannotSerializeInvalidType => GetResourceString("CannotSerializeInvalidType"); internal static string SerializeTypeInstanceNotSupported => GetResourceString("SerializeTypeInstanceNotSupported"); internal static string JsonIncludeOnNonPublicInvalid => GetResourceString("JsonIncludeOnNonPublicInvalid"); internal static string CannotSerializeInvalidMember => GetResourceString("CannotSerializeInvalidMember"); internal static string CannotPopulateCollection => GetResourceString("CannotPopulateCollection"); internal static string DefaultIgnoreConditionAlreadySpecified => GetResourceString("DefaultIgnoreConditionAlreadySpecified"); internal static string DefaultIgnoreConditionInvalid => GetResourceString("DefaultIgnoreConditionInvalid"); internal static string FormatBoolean => GetResourceString("FormatBoolean"); internal static string DictionaryKeyTypeNotSupported => GetResourceString("DictionaryKeyTypeNotSupported"); internal static string IgnoreConditionOnValueTypeInvalid => GetResourceString("IgnoreConditionOnValueTypeInvalid"); internal static string NumberHandlingConverterMustBeBuiltIn => GetResourceString("NumberHandlingConverterMustBeBuiltIn"); internal static string NumberHandlingOnPropertyTypeMustBeNumberOrCollection => GetResourceString("NumberHandlingOnPropertyTypeMustBeNumberOrCollection"); internal static string ConverterCanConvertNullableRedundant => GetResourceString("ConverterCanConvertNullableRedundant"); internal static string MetadataReferenceOfTypeCannotBeAssignedToType => GetResourceString("MetadataReferenceOfTypeCannotBeAssignedToType"); internal static string DeserializeUnableToAssignValue => GetResourceString("DeserializeUnableToAssignValue"); internal static string DeserializeUnableToAssignNull => GetResourceString("DeserializeUnableToAssignNull"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey, string defaultString = null) { if (UsingResourceKeys()) { return defaultString ?? resourceKey; } string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text)) { return defaultString; } return text; } 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); } 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(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Collections.Generic { internal sealed class ReferenceEqualityComparer : IEqualityComparer, IEqualityComparer { public static ReferenceEqualityComparer Instance { get; } = new ReferenceEqualityComparer(); private ReferenceEqualityComparer() { } public new bool Equals(object x, object y) { return x == y; } public int GetHashCode(object obj) { return RuntimeHelpers.GetHashCode(obj); } } internal static class StackExtensions { public static bool TryPeek(this Stack stack, [MaybeNullWhen(false)] out T result) { if (stack.Count > 0) { result = stack.Peek(); return true; } result = default(T); return false; } public static bool TryPop(this Stack stack, [MaybeNullWhen(false)] out T result) { if (stack.Count > 0) { result = stack.Pop(); return true; } result = default(T); return false; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class DynamicDependencyAttribute : Attribute { public string MemberSignature { get; } public DynamicallyAccessedMemberTypes MemberTypes { get; } public Type Type { get; } public string TypeName { get; } public string AssemblyName { get; } public string Condition { get; set; } public DynamicDependencyAttribute(string memberSignature) { MemberSignature = memberSignature; } public DynamicDependencyAttribute(string memberSignature, Type type) { MemberSignature = memberSignature; Type = type; } public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName) { MemberSignature = memberSignature; TypeName = typeName; AssemblyName = assemblyName; } public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type) { MemberTypes = memberTypes; Type = type; } public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName) { MemberTypes = memberTypes; TypeName = typeName; AssemblyName = assemblyName; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] internal sealed class DynamicallyAccessedMembersAttribute : Attribute { public DynamicallyAccessedMemberTypes MemberTypes { get; } public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [Flags] internal enum DynamicallyAccessedMemberTypes { None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, All = -1 } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Buffers { internal sealed class ArrayBufferWriter : IBufferWriter { private T[] _buffer; private int _index; private const int DefaultInitialBufferSize = 256; public ReadOnlyMemory WrittenMemory => MemoryExtensions.AsMemory(_buffer, 0, _index); public ReadOnlySpan WrittenSpan => MemoryExtensions.AsSpan(_buffer, 0, _index); public int WrittenCount => _index; public int Capacity => _buffer.Length; public int FreeCapacity => _buffer.Length - _index; public ArrayBufferWriter() { _buffer = Array.Empty(); _index = 0; } public ArrayBufferWriter(int initialCapacity) { if (initialCapacity <= 0) { throw new ArgumentException(null, "initialCapacity"); } _buffer = new T[initialCapacity]; _index = 0; } public void Clear() { MemoryExtensions.AsSpan(_buffer, 0, _index).Clear(); _index = 0; } public void Advance(int count) { if (count < 0) { throw new ArgumentException(null, "count"); } if (_index > _buffer.Length - count) { ThrowInvalidOperationException_AdvancedTooFar(_buffer.Length); } _index += count; } public Memory GetMemory(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); return MemoryExtensions.AsMemory(_buffer, _index); } public Span GetSpan(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); return MemoryExtensions.AsSpan(_buffer, _index); } private void CheckAndResizeBuffer(int sizeHint) { if (sizeHint < 0) { throw new ArgumentException("sizeHint"); } if (sizeHint == 0) { sizeHint = 1; } if (sizeHint <= FreeCapacity) { return; } int num = _buffer.Length; int num2 = Math.Max(sizeHint, num); if (num == 0) { num2 = Math.Max(num2, 256); } int num3 = num + num2; if ((uint)num3 > 2147483647u) { num3 = num + sizeHint; if ((uint)num3 > 2147483647u) { ThrowOutOfMemoryException((uint)num3); } } Array.Resize(ref _buffer, num3); } private static void ThrowInvalidOperationException_AdvancedTooFar(int capacity) { throw new InvalidOperationException(System.SR.Format(System.SR.BufferWriterAdvancedTooFar, capacity)); } private static void ThrowOutOfMemoryException(uint capacity) { throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity)); } } } namespace System.Buffers.Text { internal enum SequenceValidity { Empty, WellFormed, Incomplete, Invalid } } namespace System.Text.Json { internal sealed class PooledByteBufferWriter : IBufferWriter, IDisposable { private byte[] _rentedBuffer; private int _index; private const int MinimumBufferSize = 256; public ReadOnlyMemory WrittenMemory => MemoryExtensions.AsMemory(_rentedBuffer, 0, _index); public int WrittenCount => _index; public int Capacity => _rentedBuffer.Length; public int FreeCapacity => _rentedBuffer.Length - _index; public PooledByteBufferWriter(int initialCapacity) { _rentedBuffer = ArrayPool.Shared.Rent(initialCapacity); _index = 0; } public void Clear() { ClearHelper(); } private void ClearHelper() { MemoryExtensions.AsSpan(_rentedBuffer, 0, _index).Clear(); _index = 0; } public void Dispose() { if (_rentedBuffer != null) { ClearHelper(); ArrayPool.Shared.Return(_rentedBuffer); _rentedBuffer = null; } } public void Advance(int count) { _index += count; } public Memory GetMemory(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); return MemoryExtensions.AsMemory(_rentedBuffer, _index); } public Span GetSpan(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); return MemoryExtensions.AsSpan(_rentedBuffer, _index); } internal Task WriteToStreamAsync(Stream destination, CancellationToken cancellationToken) { return destination.WriteAsync(_rentedBuffer, 0, _index, cancellationToken); } private void CheckAndResizeBuffer(int sizeHint) { if (sizeHint == 0) { sizeHint = 256; } int num = _rentedBuffer.Length - _index; if (sizeHint <= num) { return; } int num2 = _rentedBuffer.Length; int num3 = Math.Max(sizeHint, num2); int num4 = num2 + num3; if ((uint)num4 > 2147483647u) { num4 = num2 + sizeHint; if ((uint)num4 > 2147483647u) { ThrowHelper.ThrowOutOfMemoryException_BufferMaximumSizeExceeded((uint)num4); } } byte[] rentedBuffer = _rentedBuffer; _rentedBuffer = ArrayPool.Shared.Rent(num4); Span span = MemoryExtensions.AsSpan(rentedBuffer, 0, _index); span.CopyTo(_rentedBuffer); span.Clear(); ArrayPool.Shared.Return(rentedBuffer); } } internal static class ThrowHelper { public const string ExceptionSourceValueToRethrowAsJsonException = "System.Text.Json.Rethrowable"; [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowOutOfMemoryException_BufferMaximumSizeExceeded(uint capacity) { throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity)); } public static ArgumentOutOfRangeException GetArgumentOutOfRangeException_MaxDepthMustBePositive(string parameterName) { return GetArgumentOutOfRangeException(parameterName, System.SR.MaxDepthMustBePositive); } [MethodImpl(MethodImplOptions.NoInlining)] private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(string parameterName, string message) { return new ArgumentOutOfRangeException(parameterName, message); } public static ArgumentOutOfRangeException GetArgumentOutOfRangeException_CommentEnumMustBeInRange(string parameterName) { return GetArgumentOutOfRangeException(parameterName, System.SR.CommentHandlingMustBeValid); } [MethodImpl(MethodImplOptions.NoInlining)] private static ArgumentException GetArgumentException(string message) { return new ArgumentException(message); } [DoesNotReturn] public static void ThrowArgumentException(string message) { throw GetArgumentException(message); } public static InvalidOperationException GetInvalidOperationException_CallFlushFirst(int _buffered) { return GetInvalidOperationException(System.SR.Format(System.SR.CallFlushToAvoidDataLoss, _buffered)); } [DoesNotReturn] public static void ThrowArgumentException_PropertyNameTooLarge(int tokenLength) { throw GetArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, tokenLength)); } [DoesNotReturn] public static void ThrowArgumentException_ValueTooLarge(int tokenLength) { throw GetArgumentException(System.SR.Format(System.SR.ValueTooLarge, tokenLength)); } [DoesNotReturn] public static void ThrowArgumentException_ValueNotSupported() { throw GetArgumentException(System.SR.SpecialNumberValuesNotSupported); } [DoesNotReturn] public static void ThrowInvalidOperationException_NeedLargerSpan() { throw GetInvalidOperationException(System.SR.FailedToGetLargerSpan); } [DoesNotReturn] public static void ThrowArgumentException(ReadOnlySpan propertyName, ReadOnlySpan value) { if (propertyName.Length > 166666666) { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } else { ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); } } [DoesNotReturn] public static void ThrowArgumentException(ReadOnlySpan propertyName, ReadOnlySpan value) { if (propertyName.Length > 166666666) { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } else { ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); } } [DoesNotReturn] public static void ThrowArgumentException(ReadOnlySpan propertyName, ReadOnlySpan value) { if (propertyName.Length > 166666666) { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } else { ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); } } [DoesNotReturn] public static void ThrowArgumentException(ReadOnlySpan propertyName, ReadOnlySpan value) { if (propertyName.Length > 166666666) { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } else { ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); } } [DoesNotReturn] public static void ThrowInvalidOperationOrArgumentException(ReadOnlySpan propertyName, int currentDepth) { currentDepth &= 0x7FFFFFFF; if (currentDepth >= 1000) { ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, 1000)); } else { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } } [DoesNotReturn] public static void ThrowInvalidOperationException(int currentDepth) { currentDepth &= 0x7FFFFFFF; ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, 1000)); } [DoesNotReturn] public static void ThrowInvalidOperationException(string message) { throw GetInvalidOperationException(message); } [MethodImpl(MethodImplOptions.NoInlining)] private static InvalidOperationException GetInvalidOperationException(string message) { InvalidOperationException ex = new InvalidOperationException(message); ex.Source = "System.Text.Json.Rethrowable"; return ex; } [DoesNotReturn] public static void ThrowInvalidOperationException_DepthNonZeroOrEmptyJson(int currentDepth) { throw GetInvalidOperationException(currentDepth); } [MethodImpl(MethodImplOptions.NoInlining)] private static InvalidOperationException GetInvalidOperationException(int currentDepth) { currentDepth &= 0x7FFFFFFF; if (currentDepth != 0) { return GetInvalidOperationException(System.SR.Format(System.SR.ZeroDepthAtEnd, currentDepth)); } return GetInvalidOperationException(System.SR.EmptyJsonIsInvalid); } [DoesNotReturn] public static void ThrowInvalidOperationOrArgumentException(ReadOnlySpan propertyName, int currentDepth) { currentDepth &= 0x7FFFFFFF; if (currentDepth >= 1000) { ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, 1000)); } else { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } } public static InvalidOperationException GetInvalidOperationException_ExpectedNumber(JsonTokenType tokenType) { return GetInvalidOperationException("number", tokenType); } public static InvalidOperationException GetInvalidOperationException_ExpectedBoolean(JsonTokenType tokenType) { return GetInvalidOperationException("boolean", tokenType); } public static InvalidOperationException GetInvalidOperationException_ExpectedString(JsonTokenType tokenType) { return GetInvalidOperationException("string", tokenType); } public static InvalidOperationException GetInvalidOperationException_ExpectedStringComparison(JsonTokenType tokenType) { return GetInvalidOperationException(tokenType); } public static InvalidOperationException GetInvalidOperationException_ExpectedComment(JsonTokenType tokenType) { return GetInvalidOperationException("comment", tokenType); } [MethodImpl(MethodImplOptions.NoInlining)] public static InvalidOperationException GetInvalidOperationException_CannotSkipOnPartial() { return GetInvalidOperationException(System.SR.CannotSkip); } [MethodImpl(MethodImplOptions.NoInlining)] private static InvalidOperationException GetInvalidOperationException(string message, JsonTokenType tokenType) { return GetInvalidOperationException(System.SR.Format(System.SR.InvalidCast, tokenType, message)); } [MethodImpl(MethodImplOptions.NoInlining)] private static InvalidOperationException GetInvalidOperationException(JsonTokenType tokenType) { return GetInvalidOperationException(System.SR.Format(System.SR.InvalidComparison, tokenType)); } [MethodImpl(MethodImplOptions.NoInlining)] internal static InvalidOperationException GetJsonElementWrongTypeException(JsonTokenType expectedType, JsonTokenType actualType) { return GetJsonElementWrongTypeException(expectedType.ToValueKind(), actualType.ToValueKind()); } [MethodImpl(MethodImplOptions.NoInlining)] internal static InvalidOperationException GetJsonElementWrongTypeException(string expectedTypeName, JsonTokenType actualType) { return GetJsonElementWrongTypeException(expectedTypeName, actualType.ToValueKind()); } [MethodImpl(MethodImplOptions.NoInlining)] internal static InvalidOperationException GetJsonElementWrongTypeException(JsonValueKind expectedType, JsonValueKind actualType) { return GetInvalidOperationException(System.SR.Format(System.SR.JsonElementHasWrongType, expectedType, actualType)); } [MethodImpl(MethodImplOptions.NoInlining)] internal static InvalidOperationException GetJsonElementWrongTypeException(string expectedTypeName, JsonValueKind actualType) { return GetInvalidOperationException(System.SR.Format(System.SR.JsonElementHasWrongType, expectedTypeName, actualType)); } [DoesNotReturn] public static void ThrowJsonReaderException(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte = 0, ReadOnlySpan bytes = default(ReadOnlySpan)) { throw GetJsonReaderException(ref json, resource, nextByte, bytes); } [MethodImpl(MethodImplOptions.NoInlining)] public static JsonException GetJsonReaderException(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte, ReadOnlySpan bytes) { string resourceString = GetResourceString(ref json, resource, nextByte, JsonHelpers.Utf8GetString(bytes)); long lineNumber = json.CurrentState._lineNumber; long bytePositionInLine = json.CurrentState._bytePositionInLine; resourceString += $" LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}."; return new JsonReaderException(resourceString, lineNumber, bytePositionInLine); } private static bool IsPrintable(byte value) { if (value >= 32) { return value < 127; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static string GetPrintableString(byte value) { if (!IsPrintable(value)) { return $"0x{value:X2}"; } char c = (char)value; return c.ToString(); } [MethodImpl(MethodImplOptions.NoInlining)] private static string GetResourceString(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte, string characters) { string printableString = GetPrintableString(nextByte); string result = ""; switch (resource) { case ExceptionResource.ArrayDepthTooLarge: result = System.SR.Format(System.SR.ArrayDepthTooLarge, json.CurrentState.Options.MaxDepth); break; case ExceptionResource.MismatchedObjectArray: result = System.SR.Format(System.SR.MismatchedObjectArray, printableString); break; case ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd: result = System.SR.TrailingCommaNotAllowedBeforeArrayEnd; break; case ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd: result = System.SR.TrailingCommaNotAllowedBeforeObjectEnd; break; case ExceptionResource.EndOfStringNotFound: result = System.SR.EndOfStringNotFound; break; case ExceptionResource.RequiredDigitNotFoundAfterSign: result = System.SR.Format(System.SR.RequiredDigitNotFoundAfterSign, printableString); break; case ExceptionResource.RequiredDigitNotFoundAfterDecimal: result = System.SR.Format(System.SR.RequiredDigitNotFoundAfterDecimal, printableString); break; case ExceptionResource.RequiredDigitNotFoundEndOfData: result = System.SR.RequiredDigitNotFoundEndOfData; break; case ExceptionResource.ExpectedEndAfterSingleJson: result = System.SR.Format(System.SR.ExpectedEndAfterSingleJson, printableString); break; case ExceptionResource.ExpectedEndOfDigitNotFound: result = System.SR.Format(System.SR.ExpectedEndOfDigitNotFound, printableString); break; case ExceptionResource.ExpectedNextDigitEValueNotFound: result = System.SR.Format(System.SR.ExpectedNextDigitEValueNotFound, printableString); break; case ExceptionResource.ExpectedSeparatorAfterPropertyNameNotFound: result = System.SR.Format(System.SR.ExpectedSeparatorAfterPropertyNameNotFound, printableString); break; case ExceptionResource.ExpectedStartOfPropertyNotFound: result = System.SR.Format(System.SR.ExpectedStartOfPropertyNotFound, printableString); break; case ExceptionResource.ExpectedStartOfPropertyOrValueNotFound: result = System.SR.ExpectedStartOfPropertyOrValueNotFound; break; case ExceptionResource.ExpectedStartOfPropertyOrValueAfterComment: result = System.SR.Format(System.SR.ExpectedStartOfPropertyOrValueAfterComment, printableString); break; case ExceptionResource.ExpectedStartOfValueNotFound: result = System.SR.Format(System.SR.ExpectedStartOfValueNotFound, printableString); break; case ExceptionResource.ExpectedValueAfterPropertyNameNotFound: result = System.SR.ExpectedValueAfterPropertyNameNotFound; break; case ExceptionResource.FoundInvalidCharacter: result = System.SR.Format(System.SR.FoundInvalidCharacter, printableString); break; case ExceptionResource.InvalidEndOfJsonNonPrimitive: result = System.SR.Format(System.SR.InvalidEndOfJsonNonPrimitive, json.TokenType); break; case ExceptionResource.ObjectDepthTooLarge: result = System.SR.Format(System.SR.ObjectDepthTooLarge, json.CurrentState.Options.MaxDepth); break; case ExceptionResource.ExpectedFalse: result = System.SR.Format(System.SR.ExpectedFalse, characters); break; case ExceptionResource.ExpectedNull: result = System.SR.Format(System.SR.ExpectedNull, characters); break; case ExceptionResource.ExpectedTrue: result = System.SR.Format(System.SR.ExpectedTrue, characters); break; case ExceptionResource.InvalidCharacterWithinString: result = System.SR.Format(System.SR.InvalidCharacterWithinString, printableString); break; case ExceptionResource.InvalidCharacterAfterEscapeWithinString: result = System.SR.Format(System.SR.InvalidCharacterAfterEscapeWithinString, printableString); break; case ExceptionResource.InvalidHexCharacterWithinString: result = System.SR.Format(System.SR.InvalidHexCharacterWithinString, printableString); break; case ExceptionResource.EndOfCommentNotFound: result = System.SR.EndOfCommentNotFound; break; case ExceptionResource.ZeroDepthAtEnd: result = System.SR.Format(System.SR.ZeroDepthAtEnd); break; case ExceptionResource.ExpectedJsonTokens: result = System.SR.ExpectedJsonTokens; break; case ExceptionResource.NotEnoughData: result = System.SR.NotEnoughData; break; case ExceptionResource.ExpectedOneCompleteToken: result = System.SR.ExpectedOneCompleteToken; break; case ExceptionResource.InvalidCharacterAtStartOfComment: result = System.SR.Format(System.SR.InvalidCharacterAtStartOfComment, printableString); break; case ExceptionResource.UnexpectedEndOfDataWhileReadingComment: result = System.SR.Format(System.SR.UnexpectedEndOfDataWhileReadingComment); break; case ExceptionResource.UnexpectedEndOfLineSeparator: result = System.SR.Format(System.SR.UnexpectedEndOfLineSeparator); break; case ExceptionResource.InvalidLeadingZeroInNumber: result = System.SR.Format(System.SR.InvalidLeadingZeroInNumber, printableString); break; } return result; } [DoesNotReturn] public static void ThrowInvalidOperationException(ExceptionResource resource, int currentDepth, byte token, JsonTokenType tokenType) { throw GetInvalidOperationException(resource, currentDepth, token, tokenType); } [DoesNotReturn] public static void ThrowArgumentException_InvalidCommentValue() { throw new ArgumentException(System.SR.CannotWriteCommentWithEmbeddedDelimiter); } [DoesNotReturn] public static void ThrowArgumentException_InvalidUTF8(ReadOnlySpan value) { StringBuilder stringBuilder = new StringBuilder(); int num = Math.Min(value.Length, 10); for (int i = 0; i < num; i++) { byte b = value[i]; if (IsPrintable(b)) { stringBuilder.Append((char)b); } else { stringBuilder.Append($"0x{b:X2}"); } } if (num < value.Length) { stringBuilder.Append("..."); } throw new ArgumentException(System.SR.Format(System.SR.CannotEncodeInvalidUTF8, stringBuilder)); } [DoesNotReturn] public static void ThrowArgumentException_InvalidUTF16(int charAsInt) { throw new ArgumentException(System.SR.Format(System.SR.CannotEncodeInvalidUTF16, $"0x{charAsInt:X2}")); } [DoesNotReturn] public static void ThrowInvalidOperationException_ReadInvalidUTF16(int charAsInt) { throw GetInvalidOperationException(System.SR.Format(System.SR.CannotReadInvalidUTF16, $"0x{charAsInt:X2}")); } [DoesNotReturn] public static void ThrowInvalidOperationException_ReadInvalidUTF16() { throw GetInvalidOperationException(System.SR.CannotReadIncompleteUTF16); } public static InvalidOperationException GetInvalidOperationException_ReadInvalidUTF8(DecoderFallbackException innerException) { return GetInvalidOperationException(System.SR.CannotTranscodeInvalidUtf8, innerException); } public static ArgumentException GetArgumentException_ReadInvalidUTF16(EncoderFallbackException innerException) { return new ArgumentException(System.SR.CannotTranscodeInvalidUtf16, innerException); } public static InvalidOperationException GetInvalidOperationException(string message, Exception innerException) { InvalidOperationException ex = new InvalidOperationException(message, innerException); ex.Source = "System.Text.Json.Rethrowable"; return ex; } [MethodImpl(MethodImplOptions.NoInlining)] public static InvalidOperationException GetInvalidOperationException(ExceptionResource resource, int currentDepth, byte token, JsonTokenType tokenType) { string resourceString = GetResourceString(resource, currentDepth, token, tokenType); InvalidOperationException invalidOperationException = GetInvalidOperationException(resourceString); invalidOperationException.Source = "System.Text.Json.Rethrowable"; return invalidOperationException; } [MethodImpl(MethodImplOptions.NoInlining)] private static string GetResourceString(ExceptionResource resource, int currentDepth, byte token, JsonTokenType tokenType) { string result = ""; switch (resource) { case ExceptionResource.MismatchedObjectArray: result = ((tokenType == JsonTokenType.PropertyName) ? System.SR.Format(System.SR.CannotWriteEndAfterProperty, (char)token) : System.SR.Format(System.SR.MismatchedObjectArray, (char)token)); break; case ExceptionResource.DepthTooLarge: result = System.SR.Format(System.SR.DepthTooLarge, currentDepth & 0x7FFFFFFF, 1000); break; case ExceptionResource.CannotStartObjectArrayWithoutProperty: result = System.SR.Format(System.SR.CannotStartObjectArrayWithoutProperty, tokenType); break; case ExceptionResource.CannotStartObjectArrayAfterPrimitiveOrClose: result = System.SR.Format(System.SR.CannotStartObjectArrayAfterPrimitiveOrClose, tokenType); break; case ExceptionResource.CannotWriteValueWithinObject: result = System.SR.Format(System.SR.CannotWriteValueWithinObject, tokenType); break; case ExceptionResource.CannotWritePropertyWithinArray: result = ((tokenType == JsonTokenType.PropertyName) ? System.SR.Format(System.SR.CannotWritePropertyAfterProperty) : System.SR.Format(System.SR.CannotWritePropertyWithinArray, tokenType)); break; case ExceptionResource.CannotWriteValueAfterPrimitiveOrClose: result = System.SR.Format(System.SR.CannotWriteValueAfterPrimitiveOrClose, tokenType); break; } return result; } public static FormatException GetFormatException() { FormatException ex = new FormatException(); ex.Source = "System.Text.Json.Rethrowable"; return ex; } [MethodImpl(MethodImplOptions.NoInlining)] public static FormatException GetFormatException(NumericType numericType) { string message = ""; switch (numericType) { case NumericType.Byte: message = System.SR.FormatByte; break; case NumericType.SByte: message = System.SR.FormatSByte; break; case NumericType.Int16: message = System.SR.FormatInt16; break; case NumericType.Int32: message = System.SR.FormatInt32; break; case NumericType.Int64: message = System.SR.FormatInt64; break; case NumericType.UInt16: message = System.SR.FormatUInt16; break; case NumericType.UInt32: message = System.SR.FormatUInt32; break; case NumericType.UInt64: message = System.SR.FormatUInt64; break; case NumericType.Single: message = System.SR.FormatSingle; break; case NumericType.Double: message = System.SR.FormatDouble; break; case NumericType.Decimal: message = System.SR.FormatDecimal; break; } FormatException ex = new FormatException(message); ex.Source = "System.Text.Json.Rethrowable"; return ex; } [MethodImpl(MethodImplOptions.NoInlining)] public static FormatException GetFormatException(DataType dateType) { string message = ""; switch (dateType) { case DataType.Boolean: message = System.SR.FormatBoolean; break; case DataType.DateTime: message = System.SR.FormatDateTime; break; case DataType.DateTimeOffset: message = System.SR.FormatDateTimeOffset; break; case DataType.Base64String: message = System.SR.CannotDecodeInvalidBase64; break; case DataType.Guid: message = System.SR.FormatGuid; break; } FormatException ex = new FormatException(message); ex.Source = "System.Text.Json.Rethrowable"; return ex; } public static InvalidOperationException GetInvalidOperationException_ExpectedChar(JsonTokenType tokenType) { return GetInvalidOperationException("char", tokenType); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowArgumentException_DeserializeWrongType(Type type, object value) { throw new ArgumentException(System.SR.Format(System.SR.DeserializeWrongType, type, value.GetType())); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowNotSupportedException_SerializationNotSupported(Type propertyType) { throw new NotSupportedException(System.SR.Format(System.SR.SerializationNotSupportedType, propertyType)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowNotSupportedException_ConstructorMaxOf64Parameters(ConstructorInfo constructorInfo, Type type) { throw new NotSupportedException(System.SR.Format(System.SR.ConstructorMaxOf64Parameters, constructorInfo, type)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowNotSupportedException_DictionaryKeyTypeNotSupported(Type keyType) { throw new NotSupportedException(System.SR.Format(System.SR.DictionaryKeyTypeNotSupported, keyType)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType) { JsonException ex = new JsonException(System.SR.Format(System.SR.DeserializeUnableToConvertValue, propertyType)); ex.AppendPathInformation = true; throw ex; } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidCastException_DeserializeUnableToAssignValue(Type typeOfValue, Type declaredType) { throw new InvalidCastException(System.SR.Format(System.SR.DeserializeUnableToAssignValue, typeOfValue, declaredType)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_DeserializeUnableToAssignNull(Type declaredType) { throw new InvalidOperationException(System.SR.Format(System.SR.DeserializeUnableToAssignNull, declaredType)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_SerializationConverterRead(JsonConverter converter) { JsonException ex = new JsonException(System.SR.Format(System.SR.SerializationConverterRead, converter)); ex.AppendPathInformation = true; throw ex; } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_SerializationConverterWrite(JsonConverter converter) { JsonException ex = new JsonException(System.SR.Format(System.SR.SerializationConverterWrite, converter)); ex.AppendPathInformation = true; throw ex; } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_SerializerCycleDetected(int maxDepth) { throw new JsonException(System.SR.Format(System.SR.SerializerCycleDetected, maxDepth)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException(string message = null) { JsonException ex; if (string.IsNullOrEmpty(message)) { ex = new JsonException(); } else { ex = new JsonException(message); ex.AppendPathInformation = true; } throw ex; } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_CannotSerializeInvalidType(Type type, Type parentClassType, MemberInfo memberInfo) { if (parentClassType == null) { throw new InvalidOperationException(System.SR.Format(System.SR.CannotSerializeInvalidType, type)); } throw new InvalidOperationException(System.SR.Format(System.SR.CannotSerializeInvalidMember, type, memberInfo.Name, parentClassType)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterNotCompatible(Type converterType, Type type) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterNotCompatible, converterType, type)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(Type classType, MemberInfo memberInfo) { string text = classType.ToString(); if (memberInfo != null) { text = text + "." + memberInfo.Name; } throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterOnAttributeInvalid, text)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(Type classTypeAttributeIsOn, MemberInfo memberInfo, Type typeToConvert) { string text = classTypeAttributeIsOn.ToString(); if (memberInfo != null) { text = text + "." + memberInfo.Name; } throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterOnAttributeNotCompatible, text, typeToConvert)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerOptionsImmutable() { throw new InvalidOperationException(System.SR.SerializerOptionsImmutable); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerPropertyNameConflict(Type type, JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializerPropertyNameConflict, type, jsonPropertyInfo.MemberInfo?.Name)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerPropertyNameNull(Type parentType, JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializerPropertyNameNull, parentType, jsonPropertyInfo.MemberInfo?.Name)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_NamingPolicyReturnNull(JsonNamingPolicy namingPolicy) { throw new InvalidOperationException(System.SR.Format(System.SR.NamingPolicyReturnNull, namingPolicy)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerConverterFactoryReturnsNull(Type converterType) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializerConverterFactoryReturnsNull, converterType)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_MultiplePropertiesBindToConstructorParameters(Type parentType, string parameterName, string firstMatchName, string secondMatchName, ConstructorInfo constructorInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.MultipleMembersBindWithConstructorParameter, firstMatchName, secondMatchName, parentType, parameterName, constructorInfo)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(ConstructorInfo constructorInfo, Type parentType) { throw new InvalidOperationException(System.SR.Format(System.SR.ConstructorParamIncompleteBinding, constructorInfo, parentType)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_ExtensionDataCannotBindToCtorParam(MemberInfo memberInfo, Type classType, ConstructorInfo constructorInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.ExtensionDataCannotBindToCtorParam, memberInfo, classType, constructorInfo)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_JsonIncludeOnNonPublicInvalid(MemberInfo memberInfo, Type parentType) { throw new InvalidOperationException(System.SR.Format(System.SR.JsonIncludeOnNonPublicInvalid, memberInfo.Name, parentType)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_IgnoreConditionOnValueTypeInvalid(JsonPropertyInfo jsonPropertyInfo) { MemberInfo memberInfo = jsonPropertyInfo.MemberInfo; throw new InvalidOperationException(System.SR.Format(System.SR.IgnoreConditionOnValueTypeInvalid, memberInfo.Name, memberInfo.DeclaringType)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_NumberHandlingOnPropertyInvalid(JsonPropertyInfo jsonPropertyInfo) { MemberInfo memberInfo = jsonPropertyInfo.MemberInfo; if (!jsonPropertyInfo.ConverterBase.IsInternalConverter) { throw new InvalidOperationException(System.SR.Format(System.SR.NumberHandlingConverterMustBeBuiltIn, jsonPropertyInfo.ConverterBase.GetType(), jsonPropertyInfo.IsForClassInfo ? jsonPropertyInfo.DeclaredPropertyType : memberInfo.DeclaringType)); } throw new InvalidOperationException(System.SR.Format(System.SR.NumberHandlingOnPropertyTypeMustBeNumberOrCollection, memberInfo.Name, memberInfo.DeclaringType)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_ConverterCanConvertNullableRedundant(Type runtimePropertyType, JsonConverter jsonConverter) { throw new InvalidOperationException(System.SR.Format(System.SR.ConverterCanConvertNullableRedundant, jsonConverter.GetType(), jsonConverter.TypeToConvert, runtimePropertyType)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotHonored(ReadOnlySpan propertyName, ref Utf8JsonReader reader, ref ReadStack state) { state.Current.JsonPropertyName = propertyName.ToArray(); NotSupportedException ex = new NotSupportedException(System.SR.Format(System.SR.ObjectWithParameterizedCtorRefMetadataNotHonored, state.Current.JsonClassInfo.Type)); ThrowNotSupportedException(in state, in reader, ex); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ReThrowWithPath(in ReadStack state, JsonReaderException ex) { string text = state.JsonPath(); string message = ex.Message; int num = message.LastIndexOf(" LineNumber: ", StringComparison.InvariantCulture); message = ((num < 0) ? (message + " Path: " + text + ".") : (message.Substring(0, num) + " Path: " + text + " |" + message.Substring(num))); throw new JsonException(message, text, ex.LineNumber, ex.BytePositionInLine, ex); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ReThrowWithPath(in ReadStack state, in Utf8JsonReader reader, Exception ex) { JsonException ex2 = new JsonException(null, ex); AddJsonExceptionInformation(in state, in reader, ex2); throw ex2; } public static void AddJsonExceptionInformation(in ReadStack state, in Utf8JsonReader reader, JsonException ex) { long lineNumber = reader.CurrentState._lineNumber; ex.LineNumber = lineNumber; long bytePositionInLine = reader.CurrentState._bytePositionInLine; ex.BytePositionInLine = bytePositionInLine; string arg = (ex.Path = state.JsonPath()); string text2 = ex._message; if (string.IsNullOrEmpty(text2)) { Type type = state.Current.JsonPropertyInfo?.RuntimePropertyType; if (type == null) { type = state.Current.JsonClassInfo?.Type; } text2 = System.SR.Format(System.SR.DeserializeUnableToConvertValue, type); ex.AppendPathInformation = true; } if (ex.AppendPathInformation) { text2 += $" Path: {arg} | LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}."; ex.SetMessage(text2); } } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ReThrowWithPath(in WriteStack state, Exception ex) { JsonException ex2 = new JsonException(null, ex); AddJsonExceptionInformation(in state, ex2); throw ex2; } public static void AddJsonExceptionInformation(in WriteStack state, JsonException ex) { string text2 = (ex.Path = state.PropertyPath()); string text3 = ex._message; if (string.IsNullOrEmpty(text3)) { text3 = System.SR.Format(System.SR.SerializeUnableToSerialize); ex.AppendPathInformation = true; } if (ex.AppendPathInformation) { text3 = text3 + " Path: " + text2 + "."; ex.SetMessage(text3); } } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationDuplicateAttribute(Type attribute, Type classType, MemberInfo memberInfo) { string text = classType.ToString(); if (memberInfo != null) { text = text + "." + memberInfo.Name; } throw new InvalidOperationException(System.SR.Format(System.SR.SerializationDuplicateAttribute, attribute, text)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(Type classType, Type attribute) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializationDuplicateTypeAttribute, classType, attribute)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(Type classType) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializationDuplicateTypeAttribute, classType, typeof(Attribute))); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationDataExtensionPropertyInvalid(Type type, JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializationDataExtensionPropertyInvalid, type, jsonPropertyInfo.MemberInfo?.Name)); } [DoesNotReturn] public static void ThrowNotSupportedException(in ReadStack state, in Utf8JsonReader reader, NotSupportedException ex) { string text = ex.Message; Type type = state.Current.JsonPropertyInfo?.RuntimePropertyType; if (type == null) { type = state.Current.JsonClassInfo.Type; } if (!text.Contains(type.ToString())) { if (text.Length > 0) { text += " "; } text += System.SR.Format(System.SR.SerializationNotSupportedParentType, type); } long lineNumber = reader.CurrentState._lineNumber; long bytePositionInLine = reader.CurrentState._bytePositionInLine; text += $" Path: {state.JsonPath()} | LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}."; throw new NotSupportedException(text, ex); } [DoesNotReturn] public static void ThrowNotSupportedException(in WriteStack state, NotSupportedException ex) { string text = ex.Message; Type type = state.Current.DeclaredJsonPropertyInfo?.RuntimePropertyType; if (type == null) { type = state.Current.JsonClassInfo.Type; } if (!text.Contains(type.ToString())) { if (text.Length > 0) { text += " "; } text += System.SR.Format(System.SR.SerializationNotSupportedParentType, type); } text = text + " Path: " + state.PropertyPath() + "."; throw new NotSupportedException(text, ex); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowNotSupportedException_DeserializeNoConstructor(Type type, ref Utf8JsonReader reader, ref ReadStack state) { string message = ((!type.IsInterface) ? System.SR.Format(System.SR.DeserializeNoConstructor, "JsonConstructorAttribute", type) : System.SR.Format(System.SR.DeserializePolymorphicInterface, type)); ThrowNotSupportedException(in state, in reader, new NotSupportedException(message)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowNotSupportedException_CannotPopulateCollection(Type type, ref Utf8JsonReader reader, ref ReadStack state) { ThrowNotSupportedException(in state, in reader, new NotSupportedException(System.SR.Format(System.SR.CannotPopulateCollection, type))); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_MetadataValuesInvalidToken(JsonTokenType tokenType) { ThrowJsonException(System.SR.Format(System.SR.MetadataInvalidTokenAfterValues, tokenType)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_MetadataReferenceNotFound(string id) { ThrowJsonException(System.SR.Format(System.SR.MetadataReferenceNotFound, id)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_MetadataValueWasNotString(JsonTokenType tokenType) { ThrowJsonException(System.SR.Format(System.SR.MetadataValueWasNotString, tokenType)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_MetadataValueWasNotString(JsonValueKind valueKind) { ThrowJsonException(System.SR.Format(System.SR.MetadataValueWasNotString, valueKind)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(ReadOnlySpan propertyName, ref ReadStack state) { state.Current.JsonPropertyName = propertyName.ToArray(); ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties() { ThrowJsonException(System.SR.MetadataReferenceCannotContainOtherProperties); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_MetadataIdIsNotFirstProperty(ReadOnlySpan propertyName, ref ReadStack state) { state.Current.JsonPropertyName = propertyName.ToArray(); ThrowJsonException(System.SR.MetadataIdIsNotFirstProperty); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_MetadataMissingIdBeforeValues(ref ReadStack state, ReadOnlySpan propertyName) { state.Current.JsonPropertyName = propertyName.ToArray(); ThrowJsonException(System.SR.MetadataPreservedArrayPropertyNotFound); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_MetadataInvalidPropertyWithLeadingDollarSign(ReadOnlySpan propertyName, ref ReadStack state, in Utf8JsonReader reader) { if (state.Current.IsProcessingDictionary()) { state.Current.JsonPropertyNameAsString = reader.GetString(); } else { state.Current.JsonPropertyName = propertyName.ToArray(); } ThrowJsonException(System.SR.MetadataInvalidPropertyWithLeadingDollarSign); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_MetadataDuplicateIdFound(string id) { ThrowJsonException(System.SR.Format(System.SR.MetadataDuplicateIdFound, id)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_MetadataInvalidReferenceToValueType(Type propertyType) { ThrowJsonException(System.SR.Format(System.SR.MetadataInvalidReferenceToValueType, propertyType)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_MetadataPreservedArrayInvalidProperty(ref ReadStack state, Type propertyType, in Utf8JsonReader reader) { ref ReadStackFrame current = ref state.Current; byte[] jsonPropertyName; if (!reader.HasValueSequence) { jsonPropertyName = reader.ValueSpan.ToArray(); } else { ReadOnlySequence sequence = reader.ValueSequence; jsonPropertyName = BuffersExtensions.ToArray(in sequence); } current.JsonPropertyName = jsonPropertyName; string @string = reader.GetString(); ThrowJsonException(System.SR.Format(System.SR.MetadataPreservedArrayFailed, System.SR.Format(System.SR.MetadataPreservedArrayInvalidProperty, @string), System.SR.Format(System.SR.DeserializeUnableToConvertValue, propertyType))); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_MetadataPreservedArrayValuesNotFound(ref ReadStack state, Type propertyType) { state.Current.JsonPropertyName = null; ThrowJsonException(System.SR.Format(System.SR.MetadataPreservedArrayFailed, System.SR.MetadataPreservedArrayPropertyNotFound, System.SR.Format(System.SR.DeserializeUnableToConvertValue, propertyType))); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowJsonException_MetadataCannotParsePreservedObjectIntoImmutable(Type propertyType) { ThrowJsonException(System.SR.Format(System.SR.MetadataCannotParsePreservedObjectToImmutable, propertyType)); } [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowInvalidOperationException_MetadataReferenceOfTypeCannotBeAssignedToType(string referenceId, Type currentType, Type typeToConvert) { throw new InvalidOperationException(System.SR.Format(System.SR.MetadataReferenceOfTypeCannotBeAssignedToType, referenceId, currentType, typeToConvert)); } [DoesNotReturn] internal static void ThrowUnexpectedMetadataException(ReadOnlySpan propertyName, ref Utf8JsonReader reader, ref ReadStack state) { if (state.Current.JsonClassInfo.PropertyInfoForClassInfo.ConverterBase.ConstructorIsParameterized) { ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotHonored(propertyName, ref reader, ref state); } switch (JsonSerializer.GetMetadataPropertyName(propertyName)) { case MetadataPropertyName.Id: ThrowJsonException_MetadataIdIsNotFirstProperty(propertyName, ref state); break; case MetadataPropertyName.Ref: ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(propertyName, ref state); break; default: ThrowJsonException_MetadataInvalidPropertyWithLeadingDollarSign(propertyName, ref state, in reader); break; } } } internal struct BitStack { private const int AllocationFreeMaxDepth = 64; private const int DefaultInitialArraySize = 2; private int[] _array; private ulong _allocationFreeContainer; private int _currentDepth; public int CurrentDepth => _currentDepth; [MethodImpl(MethodImplOptions.AggressiveInlining)] public void PushTrue() { if (_currentDepth < 64) { _allocationFreeContainer = (_allocationFreeContainer << 1) | 1; } else { PushToArray(value: true); } _currentDepth++; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void PushFalse() { if (_currentDepth < 64) { _allocationFreeContainer <<= 1; } else { PushToArray(value: false); } _currentDepth++; } [MethodImpl(MethodImplOptions.NoInlining)] private void PushToArray(bool value) { if (_array == null) { _array = new int[2]; } int number = _currentDepth - 64; int remainder; int num = Div32Rem(number, out remainder); if (num >= _array.Length) { DoubleArray(num); } int num2 = _array[num]; num2 = ((!value) ? (num2 & ~(1 << remainder)) : (num2 | (1 << remainder))); _array[num] = num2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Pop() { _currentDepth--; bool flag = false; if (_currentDepth < 64) { _allocationFreeContainer >>= 1; return (_allocationFreeContainer & 1) != 0; } if (_currentDepth == 64) { return (_allocationFreeContainer & 1) != 0; } return PopFromArray(); } [MethodImpl(MethodImplOptions.NoInlining)] private bool PopFromArray() { int number = _currentDepth - 64 - 1; int remainder; int num = Div32Rem(number, out remainder); return (_array[num] & (1 << remainder)) != 0; } private void DoubleArray(int minSize) { int newSize = Math.Max(minSize + 1, _array.Length * 2); Array.Resize(ref _array, newSize); } public void SetFirstBit() { _currentDepth++; _allocationFreeContainer = 1uL; } public void ResetFirstBit() { _currentDepth++; _allocationFreeContainer = 0uL; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int Div32Rem(int number, out int remainder) { uint result = (uint)number / 32u; remainder = number & 0x1F; return (int)result; } } internal sealed class JsonDocument : IDisposable { internal readonly struct DbRow { internal const int Size = 12; private readonly int _location; private readonly int _sizeOrLengthUnion; private readonly int _numberOfRowsAndTypeUnion; internal const int UnknownSize = -1; internal int Location => _location; internal int SizeOrLength => _sizeOrLengthUnion & 0x7FFFFFFF; internal bool IsUnknownSize => _sizeOrLengthUnion == -1; internal bool HasComplexChildren => _sizeOrLengthUnion < 0; internal int NumberOfRows => _numberOfRowsAndTypeUnion & 0xFFFFFFF; internal JsonTokenType TokenType => (JsonTokenType)((uint)_numberOfRowsAndTypeUnion >> 28); internal bool IsSimpleValue => (int)TokenType >= 5; internal DbRow(JsonTokenType jsonTokenType, int location, int sizeOrLength) { _location = location; _sizeOrLengthUnion = sizeOrLength; _numberOfRowsAndTypeUnion = (int)((uint)jsonTokenType << 28); } } private struct MetadataDb : IDisposable { private const int SizeOrLengthOffset = 4; private const int NumberOfRowsOffset = 8; private byte[] _data; internal int Length { get; private set; } internal MetadataDb(byte[] completeDb) { _data = completeDb; Length = completeDb.Length; } internal MetadataDb(int payloadLength) { int num = 12 + payloadLength; if (num > 1048576 && num <= 4194304) { num = 1048576; } _data = ArrayPool.Shared.Rent(num); Length = 0; } internal MetadataDb(MetadataDb source, bool useArrayPools) { Length = source.Length; if (useArrayPools) { _data = ArrayPool.Shared.Rent(Length); MemoryExtensions.AsSpan(source._data, 0, Length).CopyTo(_data); } else { _data = MemoryExtensions.AsSpan(source._data, 0, Length).ToArray(); } } public void Dispose() { byte[] array = Interlocked.Exchange(ref _data, null); if (array != null) { ArrayPool.Shared.Return(array); Length = 0; } } internal void TrimExcess() { if (Length <= _data.Length / 2) { byte[] array = ArrayPool.Shared.Rent(Length); byte[] array2 = array; if (array.Length < _data.Length) { Buffer.BlockCopy(_data, 0, array, 0, Length); array2 = _data; _data = array; } ArrayPool.Shared.Return(array2); } } internal void Append(JsonTokenType tokenType, int startLocation, int length) { if (Length >= _data.Length - 12) { Enlarge(); } DbRow value = new DbRow(tokenType, startLocation, length); MemoryMarshal.Write(MemoryExtensions.AsSpan(_data, Length), ref value); Length += 12; } private void Enlarge() { byte[] data = _data; _data = ArrayPool.Shared.Rent(data.Length * 2); Buffer.BlockCopy(data, 0, _data, 0, data.Length); ArrayPool.Shared.Return(data); } [Conditional("DEBUG")] private void AssertValidIndex(int index) { } internal void SetLength(int index, int length) { Span destination = MemoryExtensions.AsSpan(_data, index + 4); MemoryMarshal.Write(destination, ref length); } internal void SetNumberOfRows(int index, int numberOfRows) { Span span = MemoryExtensions.AsSpan(_data, index + 8); int num = MemoryMarshal.Read(span); int value = (num & -268435456) | numberOfRows; MemoryMarshal.Write(span, ref value); } internal void SetHasComplexChildren(int index) { Span span = MemoryExtensions.AsSpan(_data, index + 4); int num = MemoryMarshal.Read(span); int value = num | int.MinValue; MemoryMarshal.Write(span, ref value); } internal int FindIndexOfFirstUnsetSizeOrLength(JsonTokenType lookupType) { return FindOpenElement(lookupType); } private int FindOpenElement(JsonTokenType lookupType) { Span span = MemoryExtensions.AsSpan(_data, 0, Length); for (int num = Length - 12; num >= 0; num -= 12) { DbRow dbRow = MemoryMarshal.Read(span.Slice(num)); if (dbRow.IsUnknownSize && dbRow.TokenType == lookupType) { return num; } } return -1; } internal DbRow Get(int index) { return MemoryMarshal.Read(MemoryExtensions.AsSpan(_data, index)); } internal JsonTokenType GetJsonTokenType(int index) { uint num = MemoryMarshal.Read(MemoryExtensions.AsSpan(_data, index + 8)); return (JsonTokenType)(num >> 28); } internal MetadataDb CopySegment(int startIndex, int endIndex) { DbRow dbRow = Get(startIndex); int num = endIndex - startIndex; byte[] array = new byte[num]; MemoryExtensions.AsSpan(_data, startIndex, num).CopyTo(array); Span span = MemoryMarshal.Cast(array); int num2 = span[0]; if (dbRow.TokenType == JsonTokenType.String) { num2--; } for (int num3 = (num - 12) / 4; num3 >= 0; num3 -= 3) { span[num3] -= num2; } return new MetadataDb(array); } } private struct StackRow { internal const int Size = 8; internal int SizeOrLength; internal int NumberOfRows; internal StackRow(int sizeOrLength = 0, int numberOfRows = -1) { SizeOrLength = sizeOrLength; NumberOfRows = numberOfRows; } } private struct StackRowStack : IDisposable { private byte[] _rentedBuffer; private int _topOfStack; internal StackRowStack(int initialSize) { _rentedBuffer = ArrayPool.Shared.Rent(initialSize); _topOfStack = _rentedBuffer.Length; } public void Dispose() { byte[] rentedBuffer = _rentedBuffer; _rentedBuffer = null; _topOfStack = 0; if (rentedBuffer != null) { ArrayPool.Shared.Return(rentedBuffer); } } internal void Push(StackRow row) { if (_topOfStack < 8) { Enlarge(); } _topOfStack -= 8; MemoryMarshal.Write(MemoryExtensions.AsSpan(_rentedBuffer, _topOfStack), ref row); } internal StackRow Pop() { StackRow result = MemoryMarshal.Read(MemoryExtensions.AsSpan(_rentedBuffer, _topOfStack)); _topOfStack += 8; return result; } private void Enlarge() { byte[] rentedBuffer = _rentedBuffer; _rentedBuffer = ArrayPool.Shared.Rent(rentedBuffer.Length * 2); Buffer.BlockCopy(rentedBuffer, _topOfStack, _rentedBuffer, _rentedBuffer.Length - rentedBuffer.Length + _topOfStack, rentedBuffer.Length - _topOfStack); _topOfStack += _rentedBuffer.Length - rentedBuffer.Length; ArrayPool.Shared.Return(rentedBuffer); } } private ReadOnlyMemory _utf8Json; private MetadataDb _parsedData; private byte[] _extraRentedBytes; private (int, string) _lastIndexAndString = (-1, null); private const int UnseekableStreamInitialRentSize = 4096; internal bool IsDisposable { get; } public JsonElement RootElement => new JsonElement(this, 0); private JsonDocument(ReadOnlyMemory utf8Json, MetadataDb parsedData, byte[] extraRentedBytes, bool isDisposable = true) { _utf8Json = utf8Json; _parsedData = parsedData; _extraRentedBytes = extraRentedBytes; IsDisposable = isDisposable; } public void Dispose() { int length = _utf8Json.Length; if (length != 0 && IsDisposable) { _parsedData.Dispose(); _utf8Json = ReadOnlyMemory.Empty; byte[] array = Interlocked.Exchange(ref _extraRentedBytes, null); if (array != null) { MemoryExtensions.AsSpan(array, 0, length).Clear(); ArrayPool.Shared.Return(array); } } } public void WriteTo(Utf8JsonWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } RootElement.WriteTo(writer); } internal JsonTokenType GetJsonTokenType(int index) { CheckNotDisposed(); return _parsedData.GetJsonTokenType(index); } internal int GetArrayLength(int index) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.StartArray, dbRow.TokenType); return dbRow.SizeOrLength; } internal JsonElement GetArrayIndexElement(int currentIndex, int arrayIndex) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(currentIndex); CheckExpectedType(JsonTokenType.StartArray, dbRow.TokenType); int sizeOrLength = dbRow.SizeOrLength; if ((uint)arrayIndex >= (uint)sizeOrLength) { throw new IndexOutOfRangeException(); } if (!dbRow.HasComplexChildren) { return new JsonElement(this, currentIndex + (arrayIndex + 1) * 12); } int num = 0; for (int i = currentIndex + 12; i < _parsedData.Length; i += 12) { if (arrayIndex == num) { return new JsonElement(this, i); } dbRow = _parsedData.Get(i); if (!dbRow.IsSimpleValue) { i += 12 * dbRow.NumberOfRows; } num++; } throw new IndexOutOfRangeException(); } internal int GetEndIndex(int index, bool includeEndElement) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); if (dbRow.IsSimpleValue) { return index + 12; } int num = index + 12 * dbRow.NumberOfRows; if (includeEndElement) { num += 12; } return num; } private ReadOnlyMemory GetRawValue(int index, bool includeQuotes) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); if (dbRow.IsSimpleValue) { if (includeQuotes && dbRow.TokenType == JsonTokenType.String) { return _utf8Json.Slice(dbRow.Location - 1, dbRow.SizeOrLength + 2); } return _utf8Json.Slice(dbRow.Location, dbRow.SizeOrLength); } int endIndex = GetEndIndex(index, includeEndElement: false); int location = dbRow.Location; dbRow = _parsedData.Get(endIndex); return _utf8Json.Slice(location, dbRow.Location - location + dbRow.SizeOrLength); } private ReadOnlyMemory GetPropertyRawValue(int valueIndex) { CheckNotDisposed(); int num = _parsedData.Get(valueIndex - 12).Location - 1; DbRow dbRow = _parsedData.Get(valueIndex); int num2; if (dbRow.IsSimpleValue) { num2 = dbRow.Location + dbRow.SizeOrLength; if (dbRow.TokenType == JsonTokenType.String) { num2++; } return _utf8Json.Slice(num, num2 - num); } int endIndex = GetEndIndex(valueIndex, includeEndElement: false); dbRow = _parsedData.Get(endIndex); num2 = dbRow.Location + dbRow.SizeOrLength; return _utf8Json.Slice(num, num2 - num); } internal string GetString(int index, JsonTokenType expectedType) { CheckNotDisposed(); int num; string result; (num, result) = _lastIndexAndString; if (num == index) { return result; } DbRow dbRow = _parsedData.Get(index); JsonTokenType tokenType = dbRow.TokenType; if (tokenType == JsonTokenType.Null) { return null; } CheckExpectedType(expectedType, tokenType); ReadOnlySpan readOnlySpan = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); if (dbRow.HasComplexChildren) { int idx = readOnlySpan.IndexOf(92); result = JsonReaderHelper.GetUnescapedString(readOnlySpan, idx); } else { result = JsonReaderHelper.TranscodeHelper(readOnlySpan); } _lastIndexAndString = (index, result); return result; } internal bool TextEquals(int index, ReadOnlySpan otherText, bool isPropertyName) { CheckNotDisposed(); int num = (isPropertyName ? (index - 12) : index); var (num2, text) = _lastIndexAndString; if (num2 == num) { return otherText.SequenceEqual(MemoryExtensions.AsSpan(text)); } byte[] array = null; int num3 = checked(otherText.Length * 3); Span span = ((num3 > 256) ? ((Span)(array = ArrayPool.Shared.Rent(num3))) : stackalloc byte[256]); Span utf8Destination = span; ReadOnlySpan utf16Source = MemoryMarshal.AsBytes(otherText); int bytesConsumed; int bytesWritten; OperationStatus operationStatus = JsonWriterHelper.ToUtf8(utf16Source, utf8Destination, out bytesConsumed, out bytesWritten); bool result = operationStatus <= OperationStatus.DestinationTooSmall && TextEquals(index, utf8Destination.Slice(0, bytesWritten), isPropertyName, shouldUnescape: true); if (array != null) { utf8Destination.Slice(0, bytesWritten).Clear(); ArrayPool.Shared.Return(array); } return result; } internal bool TextEquals(int index, ReadOnlySpan otherUtf8Text, bool isPropertyName, bool shouldUnescape) { CheckNotDisposed(); int index2 = (isPropertyName ? (index - 12) : index); DbRow dbRow = _parsedData.Get(index2); CheckExpectedType(isPropertyName ? JsonTokenType.PropertyName : JsonTokenType.String, dbRow.TokenType); ReadOnlySpan span = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); if (otherUtf8Text.Length > span.Length || (!shouldUnescape && otherUtf8Text.Length != span.Length)) { return false; } if (dbRow.HasComplexChildren && shouldUnescape) { if (otherUtf8Text.Length < span.Length / 6) { return false; } int num = span.IndexOf(92); if (!otherUtf8Text.StartsWith(span.Slice(0, num))) { return false; } return JsonReaderHelper.UnescapeAndCompare(span.Slice(num), otherUtf8Text.Slice(num)); } return span.SequenceEqual(otherUtf8Text); } internal string GetNameOfPropertyValue(int index) { return GetString(index - 12, JsonTokenType.PropertyName); } internal bool TryGetValue(int index, [NotNullWhen(true)] out byte[] value) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.String, dbRow.TokenType); ReadOnlySpan readOnlySpan = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); if (dbRow.HasComplexChildren) { int idx = readOnlySpan.IndexOf(92); return JsonReaderHelper.TryGetUnescapedBase64Bytes(readOnlySpan, idx, out value); } return JsonReaderHelper.TryDecodeBase64(readOnlySpan, out value); } internal bool TryGetValue(int index, out sbyte value) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); if (Utf8Parser.TryParse(source, out sbyte value2, out int bytesConsumed, '\0') && bytesConsumed == source.Length) { value = value2; return true; } value = 0; return false; } internal bool TryGetValue(int index, out byte value) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); if (Utf8Parser.TryParse(source, out byte value2, out int bytesConsumed, '\0') && bytesConsumed == source.Length) { value = value2; return true; } value = 0; return false; } internal bool TryGetValue(int index, out short value) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); if (Utf8Parser.TryParse(source, out short value2, out int bytesConsumed, '\0') && bytesConsumed == source.Length) { value = value2; return true; } value = 0; return false; } internal bool TryGetValue(int index, out ushort value) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); if (Utf8Parser.TryParse(source, out ushort value2, out int bytesConsumed, '\0') && bytesConsumed == source.Length) { value = value2; return true; } value = 0; return false; } internal bool TryGetValue(int index, out int value) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); if (Utf8Parser.TryParse(source, out int value2, out int bytesConsumed, '\0') && bytesConsumed == source.Length) { value = value2; return true; } value = 0; return false; } internal bool TryGetValue(int index, out uint value) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); if (Utf8Parser.TryParse(source, out uint value2, out int bytesConsumed, '\0') && bytesConsumed == source.Length) { value = value2; return true; } value = 0u; return false; } internal bool TryGetValue(int index, out long value) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); if (Utf8Parser.TryParse(source, out long value2, out int bytesConsumed, '\0') && bytesConsumed == source.Length) { value = value2; return true; } value = 0L; return false; } internal bool TryGetValue(int index, out ulong value) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); if (Utf8Parser.TryParse(source, out ulong value2, out int bytesConsumed, '\0') && bytesConsumed == source.Length) { value = value2; return true; } value = 0uL; return false; } internal bool TryGetValue(int index, out double value) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); char standardFormat = (dbRow.HasComplexChildren ? 'e' : '\0'); if (Utf8Parser.TryParse(source, out double value2, out int bytesConsumed, standardFormat) && source.Length == bytesConsumed) { value = value2; return true; } value = 0.0; return false; } internal bool TryGetValue(int index, out float value) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); char standardFormat = (dbRow.HasComplexChildren ? 'e' : '\0'); if (Utf8Parser.TryParse(source, out float value2, out int bytesConsumed, standardFormat) && source.Length == bytesConsumed) { value = value2; return true; } value = 0f; return false; } internal bool TryGetValue(int index, out decimal value) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.Number, dbRow.TokenType); ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); char standardFormat = (dbRow.HasComplexChildren ? 'e' : '\0'); if (Utf8Parser.TryParse(source, out decimal value2, out int bytesConsumed, standardFormat) && source.Length == bytesConsumed) { value = value2; return true; } value = default(decimal); return false; } internal bool TryGetValue(int index, out DateTime value) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.String, dbRow.TokenType); ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); if (!JsonHelpers.IsValidDateTimeOffsetParseLength(source.Length)) { value = default(DateTime); return false; } if (dbRow.HasComplexChildren) { return JsonReaderHelper.TryGetEscapedDateTime(source, out value); } if (JsonHelpers.TryParseAsISO(source, out DateTime value2)) { value = value2; return true; } value = default(DateTime); return false; } internal bool TryGetValue(int index, out DateTimeOffset value) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.String, dbRow.TokenType); ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); if (!JsonHelpers.IsValidDateTimeOffsetParseLength(source.Length)) { value = default(DateTimeOffset); return false; } if (dbRow.HasComplexChildren) { return JsonReaderHelper.TryGetEscapedDateTimeOffset(source, out value); } if (JsonHelpers.TryParseAsISO(source, out DateTimeOffset value2)) { value = value2; return true; } value = default(DateTimeOffset); return false; } internal bool TryGetValue(int index, out Guid value) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.String, dbRow.TokenType); ReadOnlySpan source = _utf8Json.Span.Slice(dbRow.Location, dbRow.SizeOrLength); if (source.Length > 216) { value = default(Guid); return false; } if (dbRow.HasComplexChildren) { return JsonReaderHelper.TryGetEscapedGuid(source, out value); } if (source.Length == 36 && Utf8Parser.TryParse(source, out Guid value2, out int _, 'D')) { value = value2; return true; } value = default(Guid); return false; } internal string GetRawValueAsString(int index) { return JsonReaderHelper.TranscodeHelper(GetRawValue(index, includeQuotes: true).Span); } internal string GetPropertyRawValueAsString(int valueIndex) { return JsonReaderHelper.TranscodeHelper(GetPropertyRawValue(valueIndex).Span); } internal JsonElement CloneElement(int index) { int endIndex = GetEndIndex(index, includeEndElement: true); MetadataDb parsedData = _parsedData.CopySegment(index, endIndex); ReadOnlyMemory utf8Json = GetRawValue(index, includeQuotes: true).ToArray(); JsonDocument jsonDocument = new JsonDocument(utf8Json, parsedData, null, isDisposable: false); return jsonDocument.RootElement; } internal void WriteElementTo(int index, Utf8JsonWriter writer) { CheckNotDisposed(); DbRow row = _parsedData.Get(index); switch (row.TokenType) { case JsonTokenType.StartObject: writer.WriteStartObject(); WriteComplexElement(index, writer); break; case JsonTokenType.StartArray: writer.WriteStartArray(); WriteComplexElement(index, writer); break; case JsonTokenType.String: WriteString(in row, writer); break; case JsonTokenType.Number: writer.WriteNumberValue(_utf8Json.Slice(row.Location, row.SizeOrLength).Span); break; case JsonTokenType.True: writer.WriteBooleanValue(value: true); break; case JsonTokenType.False: writer.WriteBooleanValue(value: false); break; case JsonTokenType.Null: writer.WriteNullValue(); break; case JsonTokenType.EndObject: case JsonTokenType.EndArray: case JsonTokenType.PropertyName: case JsonTokenType.Comment: break; } } private void WriteComplexElement(int index, Utf8JsonWriter writer) { int endIndex = GetEndIndex(index, includeEndElement: true); for (int i = index + 12; i < endIndex; i += 12) { DbRow row = _parsedData.Get(i); switch (row.TokenType) { case JsonTokenType.String: WriteString(in row, writer); break; case JsonTokenType.Number: writer.WriteNumberValue(_utf8Json.Slice(row.Location, row.SizeOrLength).Span); break; case JsonTokenType.True: writer.WriteBooleanValue(value: true); break; case JsonTokenType.False: writer.WriteBooleanValue(value: false); break; case JsonTokenType.Null: writer.WriteNullValue(); break; case JsonTokenType.StartObject: writer.WriteStartObject(); break; case JsonTokenType.EndObject: writer.WriteEndObject(); break; case JsonTokenType.StartArray: writer.WriteStartArray(); break; case JsonTokenType.EndArray: writer.WriteEndArray(); break; case JsonTokenType.PropertyName: WritePropertyName(in row, writer); break; } } } private ReadOnlySpan UnescapeString(in DbRow row, out ArraySegment rented) { int location = row.Location; int sizeOrLength = row.SizeOrLength; ReadOnlySpan span = _utf8Json.Slice(location, sizeOrLength).Span; if (!row.HasComplexChildren) { rented = default(ArraySegment); return span; } int num = span.IndexOf(92); byte[] array = ArrayPool.Shared.Rent(sizeOrLength); span.Slice(0, num).CopyTo(array); JsonReaderHelper.Unescape(span, array, num, out var written); rented = new ArraySegment(array, 0, written); return MemoryExtensions.AsSpan(rented); } private static void ClearAndReturn(ArraySegment rented) { if (rented.Array != null) { MemoryExtensions.AsSpan(rented).Clear(); ArrayPool.Shared.Return(rented.Array); } } private void WritePropertyName(in DbRow row, Utf8JsonWriter writer) { ArraySegment rented = default(ArraySegment); try { writer.WritePropertyName(UnescapeString(in row, out rented)); } finally { ClearAndReturn(rented); } } private void WriteString(in DbRow row, Utf8JsonWriter writer) { ArraySegment rented = default(ArraySegment); try { writer.WriteStringValue(UnescapeString(in row, out rented)); } finally { ClearAndReturn(rented); } } private static void Parse(ReadOnlySpan utf8JsonSpan, JsonReaderOptions readerOptions, ref MetadataDb database, ref StackRowStack stack) { bool flag = false; int num = 0; int num2 = 0; int num3 = 0; Utf8JsonReader utf8JsonReader = new Utf8JsonReader(utf8JsonSpan, isFinalBlock: true, new JsonReaderState(readerOptions)); while (utf8JsonReader.Read()) { JsonTokenType tokenType = utf8JsonReader.TokenType; int num4 = (int)utf8JsonReader.TokenStartIndex; switch (tokenType) { case JsonTokenType.StartObject: { if (flag) { num++; } num3++; database.Append(tokenType, num4, -1); StackRow row = new StackRow(num2 + 1); stack.Push(row); num2 = 0; break; } case JsonTokenType.EndObject: { int index = database.FindIndexOfFirstUnsetSizeOrLength(JsonTokenType.StartObject); num3++; num2++; database.SetLength(index, num2); int length = database.Length; database.Append(tokenType, num4, utf8JsonReader.ValueSpan.Length); database.SetNumberOfRows(index, num2); database.SetNumberOfRows(length, num2); num2 += stack.Pop().SizeOrLength; break; } case JsonTokenType.StartArray: { if (flag) { num++; } num2++; database.Append(tokenType, num4, -1); StackRow row2 = new StackRow(num, num3 + 1); stack.Push(row2); num = 0; num3 = 0; break; } case JsonTokenType.EndArray: { int num5 = database.FindIndexOfFirstUnsetSizeOrLength(JsonTokenType.StartArray); num3++; num2++; database.SetLength(num5, num); database.SetNumberOfRows(num5, num3); if (num + 1 != num3) { database.SetHasComplexChildren(num5); } int length2 = database.Length; database.Append(tokenType, num4, utf8JsonReader.ValueSpan.Length); database.SetNumberOfRows(length2, num3); StackRow stackRow = stack.Pop(); num = stackRow.SizeOrLength; num3 += stackRow.NumberOfRows; break; } case JsonTokenType.PropertyName: num3++; num2++; database.Append(tokenType, num4 + 1, utf8JsonReader.ValueSpan.Length); if (utf8JsonReader._stringHasEscaping) { database.SetHasComplexChildren(database.Length - 12); } break; default: num3++; num2++; if (flag) { num++; } if (tokenType == JsonTokenType.String) { database.Append(tokenType, num4 + 1, utf8JsonReader.ValueSpan.Length); if (utf8JsonReader._stringHasEscaping) { database.SetHasComplexChildren(database.Length - 12); } break; } database.Append(tokenType, num4, utf8JsonReader.ValueSpan.Length); if (tokenType == JsonTokenType.Number) { char numberFormat = utf8JsonReader._numberFormat; if (numberFormat == 'e') { database.SetHasComplexChildren(database.Length - 12); } } break; } flag = utf8JsonReader.IsInArray; } database.TrimExcess(); } private void CheckNotDisposed() { if (_utf8Json.IsEmpty) { throw new ObjectDisposedException("JsonDocument"); } } private void CheckExpectedType(JsonTokenType expected, JsonTokenType actual) { if (expected != actual) { throw ThrowHelper.GetJsonElementWrongTypeException(expected, actual); } } private static void CheckSupportedOptions(JsonReaderOptions readerOptions, string paramName) { if (readerOptions.CommentHandling == JsonCommentHandling.Allow) { throw new ArgumentException(System.SR.JsonDocumentDoesNotSupportComments, paramName); } } public static JsonDocument Parse(ReadOnlyMemory utf8Json, JsonDocumentOptions options = default(JsonDocumentOptions)) { return Parse(utf8Json, options.GetReaderOptions(), null); } public static JsonDocument Parse(ReadOnlySequence utf8Json, JsonDocumentOptions options = default(JsonDocumentOptions)) { JsonReaderOptions readerOptions = options.GetReaderOptions(); if (utf8Json.IsSingleSegment) { return Parse(utf8Json.First, readerOptions, null); } int num = checked((int)utf8Json.Length); byte[] array = ArrayPool.Shared.Rent(num); try { utf8Json.CopyTo(MemoryExtensions.AsSpan(array)); return Parse(MemoryExtensions.AsMemory(array, 0, num), readerOptions, array); } catch { MemoryExtensions.AsSpan(array, 0, num).Clear(); ArrayPool.Shared.Return(array); throw; } } public static JsonDocument Parse(Stream utf8Json, JsonDocumentOptions options = default(JsonDocumentOptions)) { if (utf8Json == null) { throw new ArgumentNullException("utf8Json"); } ArraySegment segment = ReadToEnd(utf8Json); try { return Parse(MemoryExtensions.AsMemory(segment), options.GetReaderOptions(), segment.Array); } catch { MemoryExtensions.AsSpan(segment).Clear(); ArrayPool.Shared.Return(segment.Array); throw; } } public static Task ParseAsync(Stream utf8Json, JsonDocumentOptions options = default(JsonDocumentOptions), CancellationToken cancellationToken = default(CancellationToken)) { if (utf8Json == null) { throw new ArgumentNullException("utf8Json"); } return ParseAsyncCore(utf8Json, options, cancellationToken); } private static async Task ParseAsyncCore(Stream utf8Json, JsonDocumentOptions options = default(JsonDocumentOptions), CancellationToken cancellationToken = default(CancellationToken)) { ArraySegment segment = await ReadToEndAsync(utf8Json, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); try { return Parse(MemoryExtensions.AsMemory(segment), options.GetReaderOptions(), segment.Array); } catch { MemoryExtensions.AsSpan(segment).Clear(); ArrayPool.Shared.Return(segment.Array); throw; } } public static JsonDocument Parse(ReadOnlyMemory json, JsonDocumentOptions options = default(JsonDocumentOptions)) { ReadOnlySpan span = json.Span; int utf8ByteCount = JsonReaderHelper.GetUtf8ByteCount(span); byte[] array = ArrayPool.Shared.Rent(utf8ByteCount); try { int utf8FromText = JsonReaderHelper.GetUtf8FromText(span, array); return Parse(MemoryExtensions.AsMemory(array, 0, utf8FromText), options.GetReaderOptions(), array); } catch { MemoryExtensions.AsSpan(array, 0, utf8ByteCount).Clear(); ArrayPool.Shared.Return(array); throw; } } public static JsonDocument Parse(string json, JsonDocumentOptions options = default(JsonDocumentOptions)) { if (json == null) { throw new ArgumentNullException("json"); } return Parse(MemoryExtensions.AsMemory(json), options); } public static bool TryParseValue(ref Utf8JsonReader reader, [NotNullWhen(true)] out JsonDocument? document) { return TryParseValue(ref reader, out document, shouldThrow: false); } public static JsonDocument ParseValue(ref Utf8JsonReader reader) { JsonDocument document; bool flag = TryParseValue(ref reader, out document, shouldThrow: true); return document; } private static bool TryParseValue(ref Utf8JsonReader reader, [NotNullWhen(true)] out JsonDocument document, bool shouldThrow) { JsonReaderState currentState = reader.CurrentState; CheckSupportedOptions(currentState.Options, "reader"); Utf8JsonReader utf8JsonReader = reader; ReadOnlySpan readOnlySpan = default(ReadOnlySpan); ReadOnlySequence source = default(ReadOnlySequence); try { JsonTokenType tokenType = reader.TokenType; ReadOnlySpan bytes; if ((tokenType == JsonTokenType.None || tokenType == JsonTokenType.PropertyName) && !reader.Read()) { if (shouldThrow) { bytes = default(ReadOnlySpan); ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.ExpectedJsonTokens, 0, bytes); } reader = utf8JsonReader; document = null; return false; } switch (reader.TokenType) { case JsonTokenType.StartObject: case JsonTokenType.StartArray: { long tokenStartIndex = reader.TokenStartIndex; if (!reader.TrySkip()) { if (shouldThrow) { bytes = default(ReadOnlySpan); ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.ExpectedJsonTokens, 0, bytes); } reader = utf8JsonReader; document = null; return false; } long num = reader.BytesConsumed - tokenStartIndex; ReadOnlySequence originalSequence = reader.OriginalSequence; if (originalSequence.IsEmpty) { bytes = reader.OriginalSpan; readOnlySpan = checked(bytes.Slice((int)tokenStartIndex, (int)num)); } else { source = originalSequence.Slice(tokenStartIndex, num); } break; } case JsonTokenType.Number: case JsonTokenType.True: case JsonTokenType.False: case JsonTokenType.Null: if (reader.HasValueSequence) { source = reader.ValueSequence; } else { readOnlySpan = reader.ValueSpan; } break; case JsonTokenType.String: { ReadOnlySequence originalSequence2 = reader.OriginalSequence; if (originalSequence2.IsEmpty) { bytes = reader.ValueSpan; int length = bytes.Length + 2; readOnlySpan = reader.OriginalSpan.Slice((int)reader.TokenStartIndex, length); break; } long num2 = 2L; if (reader.HasValueSequence) { num2 += reader.ValueSequence.Length; } else { long num3 = num2; bytes = reader.ValueSpan; num2 = num3 + bytes.Length; } source = originalSequence2.Slice(reader.TokenStartIndex, num2); break; } default: if (shouldThrow) { bytes = reader.ValueSpan; byte nextByte = bytes[0]; bytes = default(ReadOnlySpan); ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.ExpectedStartOfValueNotFound, nextByte, bytes); } reader = utf8JsonReader; document = null; return false; } } catch { reader = utf8JsonReader; throw; } int num4 = (readOnlySpan.IsEmpty ? checked((int)source.Length) : readOnlySpan.Length); byte[] array = ArrayPool.Shared.Rent(num4); Span destination = MemoryExtensions.AsSpan(array, 0, num4); try { if (readOnlySpan.IsEmpty) { source.CopyTo(destination); } else { readOnlySpan.CopyTo(destination); } document = Parse(MemoryExtensions.AsMemory(array, 0, num4), currentState.Options, array); return true; } catch { destination.Clear(); ArrayPool.Shared.Return(array); throw; } } private static JsonDocument Parse(ReadOnlyMemory utf8Json, JsonReaderOptions readerOptions, byte[] extraRentedBytes) { ReadOnlySpan span = utf8Json.Span; MetadataDb database = new MetadataDb(utf8Json.Length); StackRowStack stack = new StackRowStack(512); try { Parse(span, readerOptions, ref database, ref stack); } catch { database.Dispose(); throw; } finally { stack.Dispose(); } return new JsonDocument(utf8Json, database, extraRentedBytes); } private static ArraySegment ReadToEnd(Stream stream) { int num = 0; byte[] array = null; ReadOnlySpan utf8Bom = JsonConstants.Utf8Bom; try { if (stream.CanSeek) { long num2 = Math.Max(utf8Bom.Length, stream.Length - stream.Position) + 1; array = ArrayPool.Shared.Rent(checked((int)num2)); } else { array = ArrayPool.Shared.Rent(4096); } int num3; do { num3 = stream.Read(array, num, utf8Bom.Length - num); num += num3; } while (num3 > 0 && num < utf8Bom.Length); if (num == utf8Bom.Length && utf8Bom.SequenceEqual(MemoryExtensions.AsSpan(array, 0, utf8Bom.Length))) { num = 0; } do { if (array.Length == num) { byte[] array2 = array; array = ArrayPool.Shared.Rent(checked(array2.Length * 2)); Buffer.BlockCopy(array2, 0, array, 0, array2.Length); ArrayPool.Shared.Return(array2, clearArray: true); } num3 = stream.Read(array, num, array.Length - num); num += num3; } while (num3 > 0); return new ArraySegment(array, 0, num); } catch { if (array != null) { MemoryExtensions.AsSpan(array, 0, num).Clear(); ArrayPool.Shared.Return(array); } throw; } } private static async Task> ReadToEndAsync(Stream stream, CancellationToken cancellationToken) { int written = 0; byte[] rented = null; try { int utf8BomLength = JsonConstants.Utf8Bom.Length; if (stream.CanSeek) { long num = Math.Max(utf8BomLength, stream.Length - stream.Position) + 1; rented = ArrayPool.Shared.Rent(checked((int)num)); } else { rented = ArrayPool.Shared.Rent(4096); } int num2; do { num2 = await stream.ReadAsync(rented, written, utf8BomLength - written, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); written += num2; } while (num2 > 0 && written < utf8BomLength); if (written == utf8BomLength && JsonConstants.Utf8Bom.SequenceEqual(MemoryExtensions.AsSpan(rented, 0, utf8BomLength))) { written = 0; } do { if (rented.Length == written) { byte[] array = rented; rented = ArrayPool.Shared.Rent(array.Length * 2); Buffer.BlockCopy(array, 0, rented, 0, array.Length); ArrayPool.Shared.Return(array, clearArray: true); } num2 = await stream.ReadAsync(rented, written, rented.Length - written, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); written += num2; } while (num2 > 0); return new ArraySegment(rented, 0, written); } catch { if (rented != null) { MemoryExtensions.AsSpan(rented, 0, written).Clear(); ArrayPool.Shared.Return(rented); } throw; } } internal bool TryGetNamedPropertyValue(int index, ReadOnlySpan propertyName, out JsonElement value) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.StartObject, dbRow.TokenType); if (dbRow.NumberOfRows == 1) { value = default(JsonElement); return false; } int maxByteCount = JsonReaderHelper.s_utf8Encoding.GetMaxByteCount(propertyName.Length); int startIndex = index + 12; int num = checked(dbRow.NumberOfRows * 12 + index); if (maxByteCount < 256) { Span span = stackalloc byte[256]; span = span[..JsonReaderHelper.GetUtf8FromText(propertyName, span)]; return TryGetNamedPropertyValue(startIndex, num, span, out value); } int length = propertyName.Length; int num2; for (num2 = num - 12; num2 > index; num2 -= 12) { int num3 = num2; dbRow = _parsedData.Get(num2); num2 = ((!dbRow.IsSimpleValue) ? (num2 - 12 * (dbRow.NumberOfRows + 1)) : (num2 - 12)); if (_parsedData.Get(num2).SizeOrLength >= length) { byte[] array = ArrayPool.Shared.Rent(maxByteCount); Span span2 = default(Span); try { int utf8FromText = JsonReaderHelper.GetUtf8FromText(propertyName, array); span2 = MemoryExtensions.AsSpan(array, 0, utf8FromText); return TryGetNamedPropertyValue(startIndex, num3 + 12, span2, out value); } finally { span2.Clear(); ArrayPool.Shared.Return(array); } } } value = default(JsonElement); return false; } internal bool TryGetNamedPropertyValue(int index, ReadOnlySpan propertyName, out JsonElement value) { CheckNotDisposed(); DbRow dbRow = _parsedData.Get(index); CheckExpectedType(JsonTokenType.StartObject, dbRow.TokenType); if (dbRow.NumberOfRows == 1) { value = default(JsonElement); return false; } int endIndex = checked(dbRow.NumberOfRows * 12 + index); return TryGetNamedPropertyValue(index + 12, endIndex, propertyName, out value); } private bool TryGetNamedPropertyValue(int startIndex, int endIndex, ReadOnlySpan propertyName, out JsonElement value) { ReadOnlySpan span = _utf8Json.Span; Span span2 = stackalloc byte[256]; int num; for (num = endIndex - 12; num > startIndex; num -= 12) { DbRow dbRow = _parsedData.Get(num); num = ((!dbRow.IsSimpleValue) ? (num - 12 * (dbRow.NumberOfRows + 1)) : (num - 12)); dbRow = _parsedData.Get(num); ReadOnlySpan span3 = span.Slice(dbRow.Location, dbRow.SizeOrLength); if (dbRow.HasComplexChildren) { if (span3.Length > propertyName.Length) { int num2 = span3.IndexOf(92); if (propertyName.Length > num2 && span3.Slice(0, num2).SequenceEqual(propertyName.Slice(0, num2))) { int num3 = span3.Length - num2; int written = 0; byte[] array = null; try { Span destination = ((num3 <= span2.Length) ? span2 : ((Span)(array = ArrayPool.Shared.Rent(num3)))); JsonReaderHelper.Unescape(span3.Slice(num2), destination, 0, out written); if (destination.Slice(0, written).SequenceEqual(propertyName.Slice(num2))) { value = new JsonElement(this, num + 12); return true; } } finally { if (array != null) { MemoryExtensions.AsSpan(array, 0, written).Clear(); ArrayPool.Shared.Return(array); } } } } } else if (span3.SequenceEqual(propertyName)) { value = new JsonElement(this, num + 12); return true; } } value = default(JsonElement); return false; } } internal struct JsonDocumentOptions { internal const int DefaultMaxDepth = 64; private int _maxDepth; private JsonCommentHandling _commentHandling; public JsonCommentHandling CommentHandling { readonly get { return _commentHandling; } set { if ((int)value > 1) { throw new ArgumentOutOfRangeException("value", System.SR.JsonDocumentDoesNotSupportComments); } _commentHandling = value; } } public int MaxDepth { readonly get { return _maxDepth; } set { if (value < 0) { throw ThrowHelper.GetArgumentOutOfRangeException_MaxDepthMustBePositive("value"); } _maxDepth = value; } } public bool AllowTrailingCommas { get; set; } internal JsonReaderOptions GetReaderOptions() { JsonReaderOptions result = default(JsonReaderOptions); result.AllowTrailingCommas = AllowTrailingCommas; result.CommentHandling = CommentHandling; result.MaxDepth = MaxDepth; return result; } } [DebuggerDisplay("{DebuggerDisplay,nq}")] internal readonly struct JsonElement { [DebuggerDisplay("{Current,nq}")] public struct ArrayEnumerator : IEnumerable, IEnumerable, IEnumerator, IEnumerator, IDisposable { private readonly JsonElement _target; private int _curIdx; private readonly int _endIdxOrVersion; public JsonElement Current { get { if (_curIdx < 0) { return default(JsonElement); } return new JsonElement(_target._parent, _curIdx); } } object IEnumerator.Current => Current; internal ArrayEnumerator(JsonElement target) { _target = target; _curIdx = -1; _endIdxOrVersion = target._parent.GetEndIndex(_target._idx, includeEndElement: false); } public ArrayEnumerator GetEnumerator() { ArrayEnumerator result = this; result._curIdx = -1; return result; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Dispose() { _curIdx = _endIdxOrVersion; } public void Reset() { _curIdx = -1; } public bool MoveNext() { if (_curIdx >= _endIdxOrVersion) { return false; } if (_curIdx < 0) { _curIdx = _target._idx + 12; } else { _curIdx = _target._parent.GetEndIndex(_curIdx, includeEndElement: true); } return _curIdx < _endIdxOrVersion; } } [DebuggerDisplay("{Current,nq}")] public struct ObjectEnumerator : IEnumerable, IEnumerable, IEnumerator, IEnumerator, IDisposable { private readonly JsonElement _target; private int _curIdx; private readonly int _endIdxOrVersion; public JsonProperty Current { get { if (_curIdx < 0) { return default(JsonProperty); } return new JsonProperty(new JsonElement(_target._parent, _curIdx)); } } object IEnumerator.Current => Current; internal ObjectEnumerator(JsonElement target) { _target = target; _curIdx = -1; _endIdxOrVersion = target._parent.GetEndIndex(_target._idx, includeEndElement: false); } public ObjectEnumerator GetEnumerator() { ObjectEnumerator result = this; result._curIdx = -1; return result; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Dispose() { _curIdx = _endIdxOrVersion; } public void Reset() { _curIdx = -1; } public bool MoveNext() { if (_curIdx >= _endIdxOrVersion) { return false; } if (_curIdx < 0) { _curIdx = _target._idx + 12; } else { _curIdx = _target._parent.GetEndIndex(_curIdx, includeEndElement: true); } _curIdx += 12; return _curIdx < _endIdxOrVersion; } } private readonly JsonDocument _parent; private readonly int _idx; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private JsonTokenType TokenType => _parent?.GetJsonTokenType(_idx) ?? JsonTokenType.None; public JsonValueKind ValueKind => TokenType.ToValueKind(); public JsonElement this[int index] { get { CheckValidInstance(); return _parent.GetArrayIndexElement(_idx, index); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay => $"ValueKind = {ValueKind} : \"{ToString()}\""; internal JsonElement(JsonDocument parent, int idx) { _parent = parent; _idx = idx; } public int GetArrayLength() { CheckValidInstance(); return _parent.GetArrayLength(_idx); } public JsonElement GetProperty(string propertyName) { if (propertyName == null) { throw new ArgumentNullException("propertyName"); } if (TryGetProperty(propertyName, out var value)) { return value; } throw new KeyNotFoundException(); } public JsonElement GetProperty(ReadOnlySpan propertyName) { if (TryGetProperty(propertyName, out var value)) { return value; } throw new KeyNotFoundException(); } public JsonElement GetProperty(ReadOnlySpan utf8PropertyName) { if (TryGetProperty(utf8PropertyName, out var value)) { return value; } throw new KeyNotFoundException(); } public bool TryGetProperty(string propertyName, out JsonElement value) { if (propertyName == null) { throw new ArgumentNullException("propertyName"); } return TryGetProperty(MemoryExtensions.AsSpan(propertyName), out value); } public bool TryGetProperty(ReadOnlySpan propertyName, out JsonElement value) { CheckValidInstance(); return _parent.TryGetNamedPropertyValue(_idx, propertyName, out value); } public bool TryGetProperty(ReadOnlySpan utf8PropertyName, out JsonElement value) { CheckValidInstance(); return _parent.TryGetNamedPropertyValue(_idx, utf8PropertyName, out value); } public bool GetBoolean() { JsonTokenType tokenType = TokenType; return tokenType switch { JsonTokenType.False => false, JsonTokenType.True => true, _ => throw ThrowHelper.GetJsonElementWrongTypeException("Boolean", tokenType), }; } public string? GetString() { CheckValidInstance(); return _parent.GetString(_idx, JsonTokenType.String); } public bool TryGetBytesFromBase64([NotNullWhen(true)] out byte[]? value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } public byte[] GetBytesFromBase64() { if (TryGetBytesFromBase64(out byte[] value)) { return value; } throw ThrowHelper.GetFormatException(); } [CLSCompliant(false)] public bool TryGetSByte(out sbyte value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } [CLSCompliant(false)] public sbyte GetSByte() { if (TryGetSByte(out var value)) { return value; } throw new FormatException(); } public bool TryGetByte(out byte value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } public byte GetByte() { if (TryGetByte(out var value)) { return value; } throw new FormatException(); } public bool TryGetInt16(out short value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } public short GetInt16() { if (TryGetInt16(out var value)) { return value; } throw new FormatException(); } [CLSCompliant(false)] public bool TryGetUInt16(out ushort value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } [CLSCompliant(false)] public ushort GetUInt16() { if (TryGetUInt16(out var value)) { return value; } throw new FormatException(); } public bool TryGetInt32(out int value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } public int GetInt32() { if (TryGetInt32(out var value)) { return value; } throw ThrowHelper.GetFormatException(); } [CLSCompliant(false)] public bool TryGetUInt32(out uint value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } [CLSCompliant(false)] public uint GetUInt32() { if (TryGetUInt32(out var value)) { return value; } throw ThrowHelper.GetFormatException(); } public bool TryGetInt64(out long value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } public long GetInt64() { if (TryGetInt64(out var value)) { return value; } throw ThrowHelper.GetFormatException(); } [CLSCompliant(false)] public bool TryGetUInt64(out ulong value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } [CLSCompliant(false)] public ulong GetUInt64() { if (TryGetUInt64(out var value)) { return value; } throw ThrowHelper.GetFormatException(); } public bool TryGetDouble(out double value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } public double GetDouble() { if (TryGetDouble(out var value)) { return value; } throw ThrowHelper.GetFormatException(); } public bool TryGetSingle(out float value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } public float GetSingle() { if (TryGetSingle(out var value)) { return value; } throw ThrowHelper.GetFormatException(); } public bool TryGetDecimal(out decimal value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } public decimal GetDecimal() { if (TryGetDecimal(out var value)) { return value; } throw ThrowHelper.GetFormatException(); } public bool TryGetDateTime(out DateTime value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } public DateTime GetDateTime() { if (TryGetDateTime(out var value)) { return value; } throw ThrowHelper.GetFormatException(); } public bool TryGetDateTimeOffset(out DateTimeOffset value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } public DateTimeOffset GetDateTimeOffset() { if (TryGetDateTimeOffset(out var value)) { return value; } throw ThrowHelper.GetFormatException(); } public bool TryGetGuid(out Guid value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } public Guid GetGuid() { if (TryGetGuid(out var value)) { return value; } throw ThrowHelper.GetFormatException(); } internal string GetPropertyName() { CheckValidInstance(); return _parent.GetNameOfPropertyValue(_idx); } public string GetRawText() { CheckValidInstance(); return _parent.GetRawValueAsString(_idx); } internal string GetPropertyRawText() { CheckValidInstance(); return _parent.GetPropertyRawValueAsString(_idx); } public bool ValueEquals(string? text) { if (TokenType == JsonTokenType.Null) { return text == null; } return TextEqualsHelper(MemoryExtensions.AsSpan(text), isPropertyName: false); } public bool ValueEquals(ReadOnlySpan utf8Text) { if (TokenType == JsonTokenType.Null) { return utf8Text == default(ReadOnlySpan); } return TextEqualsHelper(utf8Text, isPropertyName: false, shouldUnescape: true); } public bool ValueEquals(ReadOnlySpan text) { if (TokenType == JsonTokenType.Null) { return text == default(ReadOnlySpan); } return TextEqualsHelper(text, isPropertyName: false); } internal bool TextEqualsHelper(ReadOnlySpan utf8Text, bool isPropertyName, bool shouldUnescape) { CheckValidInstance(); return _parent.TextEquals(_idx, utf8Text, isPropertyName, shouldUnescape); } internal bool TextEqualsHelper(ReadOnlySpan text, bool isPropertyName) { CheckValidInstance(); return _parent.TextEquals(_idx, text, isPropertyName); } public void WriteTo(Utf8JsonWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } CheckValidInstance(); _parent.WriteElementTo(_idx, writer); } public ArrayEnumerator EnumerateArray() { CheckValidInstance(); JsonTokenType tokenType = TokenType; if (tokenType != JsonTokenType.StartArray) { throw ThrowHelper.GetJsonElementWrongTypeException(JsonTokenType.StartArray, tokenType); } return new ArrayEnumerator(this); } public ObjectEnumerator EnumerateObject() { CheckValidInstance(); JsonTokenType tokenType = TokenType; if (tokenType != JsonTokenType.StartObject) { throw ThrowHelper.GetJsonElementWrongTypeException(JsonTokenType.StartObject, tokenType); } return new ObjectEnumerator(this); } public override string? ToString() { switch (TokenType) { case JsonTokenType.None: case JsonTokenType.Null: return string.Empty; case JsonTokenType.True: return bool.TrueString; case JsonTokenType.False: return bool.FalseString; case JsonTokenType.StartObject: case JsonTokenType.StartArray: case JsonTokenType.Number: return _parent.GetRawValueAsString(_idx); case JsonTokenType.String: return GetString(); default: return string.Empty; } } public JsonElement Clone() { CheckValidInstance(); if (!_parent.IsDisposable) { return this; } return _parent.CloneElement(_idx); } private void CheckValidInstance() { if (_parent == null) { throw new InvalidOperationException(); } } } [DebuggerDisplay("{DebuggerDisplay,nq}")] internal readonly struct JsonProperty { public JsonElement Value { get; } private string? _name { get; } public string Name => _name ?? Value.GetPropertyName(); private string DebuggerDisplay { get { if (Value.ValueKind != 0) { return "\"" + ToString() + "\""; } return ""; } } internal JsonProperty(JsonElement value, string name = null) { Value = value; _name = name; } public bool NameEquals(string? text) { return NameEquals(MemoryExtensions.AsSpan(text)); } public bool NameEquals(ReadOnlySpan utf8Text) { return Value.TextEqualsHelper(utf8Text, isPropertyName: true, shouldUnescape: true); } public bool NameEquals(ReadOnlySpan text) { return Value.TextEqualsHelper(text, isPropertyName: true); } internal bool EscapedNameEquals(ReadOnlySpan utf8Text) { return Value.TextEqualsHelper(utf8Text, isPropertyName: true, shouldUnescape: false); } public void WriteTo(Utf8JsonWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } writer.WritePropertyName(Name); Value.WriteTo(writer); } public override string ToString() { return Value.GetPropertyRawText(); } } internal enum JsonValueKind : byte { Undefined, Object, Array, String, Number, True, False, Null } internal enum JsonCommentHandling : byte { Disallow, Skip, Allow } internal static class JsonConstants { public const byte OpenBrace = 123; public const byte CloseBrace = 125; public const byte OpenBracket = 91; public const byte CloseBracket = 93; public const byte Space = 32; public const byte CarriageReturn = 13; public const byte LineFeed = 10; public const byte Tab = 9; public const byte ListSeparator = 44; public const byte KeyValueSeperator = 58; public const byte Quote = 34; public const byte BackSlash = 92; public const byte Slash = 47; public const byte BackSpace = 8; public const byte FormFeed = 12; public const byte Asterisk = 42; public const byte Colon = 58; public const byte Period = 46; public const byte Plus = 43; public const byte Hyphen = 45; public const byte UtcOffsetToken = 90; public const byte TimePrefix = 84; public const byte StartingByteOfNonStandardSeparator = 226; public const int SpacesPerIndent = 2; public const int MaxWriterDepth = 1000; public const int RemoveFlagsBitMask = int.MaxValue; public const int StackallocThreshold = 256; public const int MaxExpansionFactorWhileEscaping = 6; public const int MaxExpansionFactorWhileTranscoding = 3; public const int MaxEscapedTokenSize = 1000000000; public const int MaxUnescapedTokenSize = 166666666; public const int MaxBase64ValueTokenSize = 125000000; public const int MaxCharacterTokenSize = 166666666; public const int MaximumFormatBooleanLength = 5; public const int MaximumFormatInt64Length = 20; public const int MaximumFormatUInt64Length = 20; public const int MaximumFormatDoubleLength = 128; public const int MaximumFormatSingleLength = 128; public const int MaximumFormatDecimalLength = 31; public const int MaximumFormatGuidLength = 36; public const int MaximumEscapedGuidLength = 216; public const int MaximumFormatDateTimeLength = 27; public const int MaximumFormatDateTimeOffsetLength = 33; public const int MaxDateTimeUtcOffsetHours = 14; public const int DateTimeNumFractionDigits = 7; public const int MaxDateTimeFraction = 9999999; public const int DateTimeParseNumFractionDigits = 16; public const int MaximumDateTimeOffsetParseLength = 42; public const int MinimumDateTimeParseLength = 10; public const int MaximumEscapedDateTimeOffsetParseLength = 252; internal const char ScientificNotationFormat = 'e'; public const char HighSurrogateStart = '\ud800'; public const char HighSurrogateEnd = '\udbff'; public const char LowSurrogateStart = '\udc00'; public const char LowSurrogateEnd = '\udfff'; public const int UnicodePlane01StartValue = 65536; public const int HighSurrogateStartValue = 55296; public const int HighSurrogateEndValue = 56319; public const int LowSurrogateStartValue = 56320; public const int LowSurrogateEndValue = 57343; public const int BitShiftBy10 = 1024; public const int UnboxedParameterCountThreshold = 4; public const int MaxParameterCount = 64; public static ReadOnlySpan Utf8Bom => "\ufeff"u8; public static ReadOnlySpan TrueValue => "true"u8; public static ReadOnlySpan FalseValue => "false"u8; public static ReadOnlySpan NullValue => "null"u8; public static ReadOnlySpan NaNValue => "NaN"u8; public static ReadOnlySpan PositiveInfinityValue => "Infinity"u8; public static ReadOnlySpan NegativeInfinityValue => "-Infinity"u8; public static ReadOnlySpan Delimiters => ",}] \n\r\t/"u8; public static ReadOnlySpan EscapableChars => "\"nrt/ubf"u8; } internal readonly struct JsonEncodedText : IEquatable { private readonly byte[] _utf8Value; private readonly string _value; public ReadOnlySpan EncodedUtf8Bytes => _utf8Value; private JsonEncodedText(byte[] utf8Value) { _value = JsonReaderHelper.GetTextFromUtf8(utf8Value); _utf8Value = utf8Value; } public static JsonEncodedText Encode(string value, JavaScriptEncoder? encoder = null) { if (value == null) { throw new ArgumentNullException("value"); } return Encode(MemoryExtensions.AsSpan(value), encoder); } public static JsonEncodedText Encode(ReadOnlySpan value, JavaScriptEncoder? encoder = null) { if (value.Length == 0) { return new JsonEncodedText(Array.Empty()); } return TranscodeAndEncode(value, encoder); } private static JsonEncodedText TranscodeAndEncode(ReadOnlySpan value, JavaScriptEncoder encoder) { JsonWriterHelper.ValidateValue(value); int utf8ByteCount = JsonReaderHelper.GetUtf8ByteCount(value); byte[] array = ArrayPool.Shared.Rent(utf8ByteCount); int utf8FromText = JsonReaderHelper.GetUtf8FromText(value, array); JsonEncodedText result = EncodeHelper(MemoryExtensions.AsSpan(array, 0, utf8FromText), encoder); MemoryExtensions.AsSpan(array, 0, utf8ByteCount).Clear(); ArrayPool.Shared.Return(array); return result; } public static JsonEncodedText Encode(ReadOnlySpan utf8Value, JavaScriptEncoder? encoder = null) { if (utf8Value.Length == 0) { return new JsonEncodedText(Array.Empty()); } JsonWriterHelper.ValidateValue(utf8Value); return EncodeHelper(utf8Value, encoder); } private static JsonEncodedText EncodeHelper(ReadOnlySpan utf8Value, JavaScriptEncoder encoder) { int num = JsonWriterHelper.NeedsEscaping(utf8Value, encoder); if (num != -1) { return new JsonEncodedText(JsonHelpers.EscapeValue(utf8Value, num, encoder)); } return new JsonEncodedText(utf8Value.ToArray()); } public bool Equals(JsonEncodedText other) { if (_value == null) { return other._value == null; } return _value.Equals(other._value); } public override bool Equals(object? obj) { if (obj is JsonEncodedText other) { return Equals(other); } return false; } public override string ToString() { return _value ?? string.Empty; } public override int GetHashCode() { if (_value != null) { return _value.GetHashCode(); } return 0; } } [Serializable] internal class JsonException : Exception { internal string? _message; internal bool AppendPathInformation { get; set; } public long? LineNumber { get; internal set; } public long? BytePositionInLine { get; internal set; } public string? Path { get; internal set; } public override string Message => _message ?? base.Message; public JsonException(string? message, string? path, long? lineNumber, long? bytePositionInLine, Exception? innerException) : base(message, innerException) { _message = message; LineNumber = lineNumber; BytePositionInLine = bytePositionInLine; Path = path; } public JsonException(string? message, string? path, long? lineNumber, long? bytePositionInLine) : base(message) { _message = message; LineNumber = lineNumber; BytePositionInLine = bytePositionInLine; Path = path; } public JsonException(string? message, Exception? innerException) : base(message, innerException) { _message = message; } public JsonException(string? message) : base(message) { _message = message; } public JsonException() { } protected JsonException(SerializationInfo info, StreamingContext context) : base(info, context) { LineNumber = (long?)info.GetValue("LineNumber", typeof(long?)); BytePositionInLine = (long?)info.GetValue("BytePositionInLine", typeof(long?)); Path = info.GetString("Path"); SetMessage(info.GetString("ActualMessage")); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("LineNumber", LineNumber, typeof(long?)); info.AddValue("BytePositionInLine", BytePositionInLine, typeof(long?)); info.AddValue("Path", Path, typeof(string)); info.AddValue("ActualMessage", Message, typeof(string)); } internal void SetMessage(string? message) { _message = message; } } internal static class JsonHelpers { private struct DateTimeParseData { public int Year; public int Month; public int Day; public int Hour; public int Minute; public int Second; public int Fraction; public int OffsetHours; public int OffsetMinutes; public byte OffsetToken; public bool OffsetNegative => OffsetToken == 45; } private static readonly int[] s_daysToMonth365 = new int[13] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; private static readonly int[] s_daysToMonth366 = new int[13] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan GetSpan(this ref Utf8JsonReader reader) { if (!reader.HasValueSequence) { return reader.ValueSpan; } ReadOnlySequence sequence = reader.ValueSequence; return BuffersExtensions.ToArray(in sequence); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsValidUnicodeScalar(uint value) { return IsInRangeInclusive(value ^ 0xD800u, 2048u, 1114111u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInRangeInclusive(uint value, uint lowerBound, uint upperBound) { return value - lowerBound <= upperBound - lowerBound; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInRangeInclusive(int value, int lowerBound, int upperBound) { return (uint)(value - lowerBound) <= (uint)(upperBound - lowerBound); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInRangeInclusive(long value, long lowerBound, long upperBound) { return (ulong)(value - lowerBound) <= (ulong)(upperBound - lowerBound); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInRangeInclusive(JsonTokenType value, JsonTokenType lowerBound, JsonTokenType upperBound) { return value - lowerBound <= upperBound - lowerBound; } public static bool IsDigit(byte value) { return (uint)(value - 48) <= 9u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ReadWithVerify(this ref Utf8JsonReader reader) { bool flag = reader.Read(); } public static string Utf8GetString(ReadOnlySpan bytes) { return Encoding.UTF8.GetString(bytes.ToArray()); } public static bool TryAdd(Dictionary dictionary, in TKey key, in TValue value) { if (!dictionary.ContainsKey(key)) { dictionary[key] = value; return true; } return false; } public static bool IsFinite(double value) { if (!double.IsNaN(value)) { return !double.IsInfinity(value); } return false; } public static bool IsFinite(float value) { if (!float.IsNaN(value)) { return !float.IsInfinity(value); } return false; } public static string FormatDateTimeOffset(DateTimeOffset value) { Span buffer = stackalloc byte[33]; JsonWriterHelper.WriteDateTimeOffsetTrimmed(buffer, value, out var bytesWritten); return JsonReaderHelper.GetTextFromUtf8(buffer.Slice(0, bytesWritten)); } public static string FormatDateTime(DateTime value) { Span buffer = stackalloc byte[33]; JsonWriterHelper.WriteDateTimeTrimmed(buffer, value, out var bytesWritten); return JsonReaderHelper.GetTextFromUtf8(buffer.Slice(0, bytesWritten)); } public static bool TryParseAsISO(ReadOnlySpan source, out DateTime value) { if (!IsValidDateTimeOffsetParseLength(source.Length)) { value = default(DateTime); return false; } int num = checked(source.Length * 3); Span span = ((num > 256) ? ((Span)new byte[num]) : stackalloc byte[256]); Span span2 = span; span2 = span2[..JsonReaderHelper.GetUtf8FromText(source, span2)]; if (span2.IndexOf(92) != -1) { return JsonReaderHelper.TryGetEscapedDateTime(span2, out value); } if (TryParseAsISO((ReadOnlySpan)span2, out DateTime value2)) { value = value2; return true; } value = default(DateTime); return false; } public static bool TryParseAsISO(ReadOnlySpan source, out DateTimeOffset value) { if (!IsValidDateTimeOffsetParseLength(source.Length)) { value = default(DateTimeOffset); return false; } int num = checked(source.Length * 3); Span span = ((num > 256) ? ((Span)new byte[num]) : stackalloc byte[256]); Span span2 = span; span2 = span2[..JsonReaderHelper.GetUtf8FromText(source, span2)]; if (span2.IndexOf(92) != -1) { return JsonReaderHelper.TryGetEscapedDateTimeOffset(span2, out value); } if (TryParseAsISO((ReadOnlySpan)span2, out DateTimeOffset value2)) { value = value2; return true; } value = default(DateTimeOffset); return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsValidDateTimeOffsetParseLength(int length) { return IsInRangeInclusive(length, 10, 252); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsValidDateTimeOffsetParseLength(long length) { return IsInRangeInclusive(length, 10L, 252L); } public static bool TryParseAsISO(ReadOnlySpan source, out DateTime value) { if (!TryParseDateTimeOffset(source, out var parseData)) { value = default(DateTime); return false; } if (parseData.OffsetToken == 90) { return TryCreateDateTime(parseData, DateTimeKind.Utc, out value); } if (parseData.OffsetToken == 43 || parseData.OffsetToken == 45) { if (!TryCreateDateTimeOffset(ref parseData, out var value2)) { value = default(DateTime); return false; } value = value2.LocalDateTime; return true; } return TryCreateDateTime(parseData, DateTimeKind.Unspecified, out value); } public static bool TryParseAsISO(ReadOnlySpan source, out DateTimeOffset value) { if (!TryParseDateTimeOffset(source, out var parseData)) { value = default(DateTimeOffset); return false; } if (parseData.OffsetToken == 90 || parseData.OffsetToken == 43 || parseData.OffsetToken == 45) { return TryCreateDateTimeOffset(ref parseData, out value); } return TryCreateDateTimeOffsetInterpretingDataAsLocalTime(parseData, out value); } private static bool TryParseDateTimeOffset(ReadOnlySpan source, out DateTimeParseData parseData) { parseData = default(DateTimeParseData); uint num = (uint)(source[0] - 48); uint num2 = (uint)(source[1] - 48); uint num3 = (uint)(source[2] - 48); uint num4 = (uint)(source[3] - 48); if (num > 9 || num2 > 9 || num3 > 9 || num4 > 9) { return false; } parseData.Year = (int)(num * 1000 + num2 * 100 + num3 * 10 + num4); if (source[4] != 45 || !TryGetNextTwoDigits(source.Slice(5, 2), ref parseData.Month) || source[7] != 45 || !TryGetNextTwoDigits(source.Slice(8, 2), ref parseData.Day)) { return false; } if (source.Length == 10) { return true; } if (source.Length < 16) { return false; } if (source[10] != 84 || source[13] != 58 || !TryGetNextTwoDigits(source.Slice(11, 2), ref parseData.Hour) || !TryGetNextTwoDigits(source.Slice(14, 2), ref parseData.Minute)) { return false; } if (source.Length == 16) { return true; } byte b = source[16]; int num5 = 17; switch (b) { case 90: parseData.OffsetToken = 90; return num5 == source.Length; case 43: case 45: parseData.OffsetToken = b; return ParseOffset(ref parseData, source.Slice(num5)); default: return false; case 58: if (source.Length < 19 || !TryGetNextTwoDigits(source.Slice(17, 2), ref parseData.Second)) { return false; } if (source.Length == 19) { return true; } b = source[19]; num5 = 20; switch (b) { case 90: parseData.OffsetToken = 90; return num5 == source.Length; case 43: case 45: parseData.OffsetToken = b; return ParseOffset(ref parseData, source.Slice(num5)); default: return false; case 46: { if (source.Length < 21) { return false; } int i = 0; for (int num6 = Math.Min(num5 + 16, source.Length); num5 < num6; num5++) { if (!IsDigit(b = source[num5])) { break; } if (i < 7) { parseData.Fraction = parseData.Fraction * 10 + (b - 48); i++; } } if (parseData.Fraction != 0) { for (; i < 7; i++) { parseData.Fraction *= 10; } } if (num5 == source.Length) { return true; } b = source[num5++]; switch (b) { case 90: parseData.OffsetToken = 90; return num5 == source.Length; case 43: case 45: parseData.OffsetToken = b; return ParseOffset(ref parseData, source.Slice(num5)); default: return false; } } } } static bool ParseOffset(ref DateTimeParseData parseData, ReadOnlySpan offsetData) { if (offsetData.Length < 2 || !TryGetNextTwoDigits(offsetData.Slice(0, 2), ref parseData.OffsetHours)) { return false; } if (offsetData.Length == 2) { return true; } if (offsetData.Length != 5 || offsetData[2] != 58 || !TryGetNextTwoDigits(offsetData.Slice(3), ref parseData.OffsetMinutes)) { return false; } return true; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryGetNextTwoDigits(ReadOnlySpan source, ref int value) { uint num = (uint)(source[0] - 48); uint num2 = (uint)(source[1] - 48); if (num > 9 || num2 > 9) { value = 0; return false; } value = (int)(num * 10 + num2); return true; } private static bool TryCreateDateTimeOffset(DateTime dateTime, ref DateTimeParseData parseData, out DateTimeOffset value) { if ((uint)parseData.OffsetHours > 14u) { value = default(DateTimeOffset); return false; } if ((uint)parseData.OffsetMinutes > 59u) { value = default(DateTimeOffset); return false; } if (parseData.OffsetHours == 14 && parseData.OffsetMinutes != 0) { value = default(DateTimeOffset); return false; } long num = ((long)parseData.OffsetHours * 3600L + (long)parseData.OffsetMinutes * 60L) * 10000000; if (parseData.OffsetNegative) { num = -num; } try { value = new DateTimeOffset(dateTime.Ticks, new TimeSpan(num)); } catch (ArgumentOutOfRangeException) { value = default(DateTimeOffset); return false; } return true; } private static bool TryCreateDateTimeOffset(ref DateTimeParseData parseData, out DateTimeOffset value) { if (!TryCreateDateTime(parseData, DateTimeKind.Unspecified, out var value2)) { value = default(DateTimeOffset); return false; } if (!TryCreateDateTimeOffset(value2, ref parseData, out value)) { value = default(DateTimeOffset); return false; } return true; } private static bool TryCreateDateTimeOffsetInterpretingDataAsLocalTime(DateTimeParseData parseData, out DateTimeOffset value) { if (!TryCreateDateTime(parseData, DateTimeKind.Local, out var value2)) { value = default(DateTimeOffset); return false; } try { value = new DateTimeOffset(value2); } catch (ArgumentOutOfRangeException) { value = default(DateTimeOffset); return false; } return true; } private static bool TryCreateDateTime(DateTimeParseData parseData, DateTimeKind kind, out DateTime value) { if (parseData.Year == 0) { value = default(DateTime); return false; } if ((uint)(parseData.Month - 1) >= 12u) { value = default(DateTime); return false; } uint num = (uint)(parseData.Day - 1); if (num >= 28 && num >= DateTime.DaysInMonth(parseData.Year, parseData.Month)) { value = default(DateTime); return false; } if ((uint)parseData.Hour > 23u) { value = default(DateTime); return false; } if ((uint)parseData.Minute > 59u) { value = default(DateTime); return false; } if ((uint)parseData.Second > 59u) { value = default(DateTime); return false; } int[] array = (DateTime.IsLeapYear(parseData.Year) ? s_daysToMonth366 : s_daysToMonth365); int num2 = parseData.Year - 1; int num3 = num2 * 365 + num2 / 4 - num2 / 100 + num2 / 400 + array[parseData.Month - 1] + parseData.Day - 1; long num4 = num3 * 864000000000L; int num5 = parseData.Hour * 3600 + parseData.Minute * 60 + parseData.Second; num4 += (long)num5 * 10000000L; num4 += parseData.Fraction; value = new DateTime(num4, kind); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte[] GetEscapedPropertyNameSection(ReadOnlySpan utf8Value, JavaScriptEncoder encoder) { int num = JsonWriterHelper.NeedsEscaping(utf8Value, encoder); if (num != -1) { return GetEscapedPropertyNameSection(utf8Value, num, encoder); } return GetPropertyNameSection(utf8Value); } public static byte[] EscapeValue(ReadOnlySpan utf8Value, int firstEscapeIndexVal, JavaScriptEncoder encoder) { byte[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8Value.Length, firstEscapeIndexVal); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(utf8Value, destination, firstEscapeIndexVal, encoder, out var written); byte[] result = destination.Slice(0, written).ToArray(); if (array != null) { ArrayPool.Shared.Return(array); } return result; } private static byte[] GetEscapedPropertyNameSection(ReadOnlySpan utf8Value, int firstEscapeIndexVal, JavaScriptEncoder encoder) { byte[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8Value.Length, firstEscapeIndexVal); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(utf8Value, destination, firstEscapeIndexVal, encoder, out var written); byte[] propertyNameSection = GetPropertyNameSection(destination.Slice(0, written)); if (array != null) { ArrayPool.Shared.Return(array); } return propertyNameSection; } private static byte[] GetPropertyNameSection(ReadOnlySpan utf8Value) { int length = utf8Value.Length; byte[] array = new byte[length + 3]; array[0] = 34; utf8Value.CopyTo(MemoryExtensions.AsSpan(array, 1, length)); array[++length] = 34; array[++length] = 58; return array; } } internal enum JsonTokenType : byte { None, StartObject, EndObject, StartArray, EndArray, PropertyName, Comment, String, Number, True, False, Null } internal enum ConsumeNumberResult : byte { Success, OperationIncomplete, NeedMoreData } internal enum ConsumeTokenResult : byte { Success, NotEnoughDataRollBackState, IncompleteNoRollBackNecessary } [Serializable] internal sealed class JsonReaderException : JsonException { public JsonReaderException(string message, long lineNumber, long bytePositionInLine) : base(message, null, lineNumber, bytePositionInLine) { } private JsonReaderException(SerializationInfo info, StreamingContext context) : base(info, context) { } } internal static class JsonReaderHelper { private const ulong XorPowerOfTwoToHighByte = 283686952306184uL; public static readonly UTF8Encoding s_utf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); public static (int, int) CountNewLines(ReadOnlySpan data) { int item = -1; int num = 0; for (int i = 0; i < data.Length; i++) { if (data[i] == 10) { item = i; num++; } } return (num, item); } internal static JsonValueKind ToValueKind(this JsonTokenType tokenType) { switch (tokenType) { case JsonTokenType.None: return JsonValueKind.Undefined; case JsonTokenType.StartArray: return JsonValueKind.Array; case JsonTokenType.StartObject: return JsonValueKind.Object; case JsonTokenType.String: case JsonTokenType.Number: case JsonTokenType.True: case JsonTokenType.False: case JsonTokenType.Null: return (JsonValueKind)(tokenType - 4); default: return JsonValueKind.Undefined; } } public static bool IsTokenTypePrimitive(JsonTokenType tokenType) { return (int)(tokenType - 7) <= 4; } public static bool IsHexDigit(byte nextByte) { return System.HexConverter.IsHexChar(nextByte); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfQuoteOrAnyControlOrBackSlash(this ReadOnlySpan span) { return IndexOfOrLessThan(ref MemoryMarshal.GetReference(span), 34, 92, 32, span.Length); } private unsafe static int IndexOfOrLessThan(ref byte searchSpace, byte value0, byte value1, byte lessThan, int length) { IntPtr intPtr = (IntPtr)0; IntPtr intPtr2 = (IntPtr)length; if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector.Count - 1); intPtr2 = (IntPtr)((Vector.Count - num) & (Vector.Count - 1)); } while (true) { if ((nuint)(void*)intPtr2 >= (nuint)8u) { intPtr2 -= 8; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 == num2 || value1 == num2 || lessThan > num2) { goto IL_0393; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); if (value0 == num2 || value1 == num2 || lessThan > num2) { goto IL_039b; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); if (value0 == num2 || value1 == num2 || lessThan > num2) { goto IL_03a9; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); if (value0 != num2 && value1 != num2 && lessThan <= num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 4); if (value0 != num2 && value1 != num2 && lessThan <= num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 5); if (value0 != num2 && value1 != num2 && lessThan <= num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 6); if (value0 != num2 && value1 != num2 && lessThan <= num2) { num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 7); if (value0 == num2 || value1 == num2 || lessThan > num2) { break; } intPtr += 8; continue; } return (int)(void*)(intPtr + 6); } return (int)(void*)(intPtr + 5); } return (int)(void*)(intPtr + 4); } goto IL_03b7; } if ((nuint)(void*)intPtr2 >= (nuint)4u) { intPtr2 -= 4; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 == num2 || value1 == num2 || lessThan > num2) { goto IL_0393; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 1); if (value0 == num2 || value1 == num2 || lessThan > num2) { goto IL_039b; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 2); if (value0 == num2 || value1 == num2 || lessThan > num2) { goto IL_03a9; } num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr + 3); if (value0 == num2 || value1 == num2 || lessThan > num2) { goto IL_03b7; } intPtr += 4; } while ((void*)intPtr2 != null) { intPtr2 -= 1; uint num2 = Unsafe.AddByteOffset(ref searchSpace, intPtr); if (value0 != num2 && value1 != num2 && lessThan <= num2) { intPtr += 1; continue; } goto IL_0393; } if (Vector.IsHardwareAccelerated && (int)(void*)intPtr < length) { intPtr2 = (IntPtr)((length - (int)(void*)intPtr) & ~(Vector.Count - 1)); Vector right = new Vector(value0); Vector right2 = new Vector(value1); Vector right3 = new Vector(lessThan); for (; (void*)intPtr2 > (void*)intPtr; intPtr += Vector.Count) { Vector left = Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref searchSpace, intPtr)); Vector vector = Vector.BitwiseOr(Vector.BitwiseOr(Vector.Equals(left, right), Vector.Equals(left, right2)), Vector.LessThan(left, right3)); if (!Vector.Zero.Equals(vector)) { return (int)(void*)intPtr + LocateFirstFoundByte(vector); } } if ((int)(void*)intPtr < length) { intPtr2 = (IntPtr)(length - (int)(void*)intPtr); continue; } } return -1; IL_0393: return (int)(void*)intPtr; IL_039b: return (int)(void*)(intPtr + 1); IL_03b7: return (int)(void*)(intPtr + 3); IL_03a9: return (int)(void*)(intPtr + 2); } return (int)(void*)(intPtr + 7); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateFirstFoundByte(Vector match) { Vector vector = Vector.AsVectorUInt64(match); ulong num = 0uL; int i; for (i = 0; i < Vector.Count; i++) { num = vector[i]; if (num != 0L) { break; } } return i * 8 + LocateFirstFoundByte(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateFirstFoundByte(ulong match) { ulong num = match ^ (match - 1); return (int)(num * 283686952306184L >> 57); } public static bool TryGetEscapedDateTime(ReadOnlySpan source, out DateTime value) { int idx = source.IndexOf(92); Span span = stackalloc byte[source.Length]; Unescape(source, span, idx, out var written); span = span.Slice(0, written); if (span.Length <= 42 && JsonHelpers.TryParseAsISO((ReadOnlySpan)span, out DateTime value2)) { value = value2; return true; } value = default(DateTime); return false; } public static bool TryGetEscapedDateTimeOffset(ReadOnlySpan source, out DateTimeOffset value) { int idx = source.IndexOf(92); Span span = stackalloc byte[source.Length]; Unescape(source, span, idx, out var written); span = span.Slice(0, written); if (span.Length <= 42 && JsonHelpers.TryParseAsISO((ReadOnlySpan)span, out DateTimeOffset value2)) { value = value2; return true; } value = default(DateTimeOffset); return false; } public static bool TryGetEscapedGuid(ReadOnlySpan source, out Guid value) { int idx = source.IndexOf(92); Span span = stackalloc byte[source.Length]; Unescape(source, span, idx, out var written); span = span.Slice(0, written); if (span.Length == 36 && Utf8Parser.TryParse((ReadOnlySpan)span, out Guid value2, out int _, 'D')) { value = value2; return true; } value = default(Guid); return false; } public static char GetFloatingPointStandardParseFormat(ReadOnlySpan span) { int num = span.Length - 1; for (int num2 = num; num2 >= 0; num2--) { byte b = span[num2]; if (b == 69 || b == 101) { return 'e'; } } return '\0'; } public static bool TryGetFloatingPointConstant(ReadOnlySpan span, out float value) { if (span.Length == 3) { if (span.SequenceEqual(JsonConstants.NaNValue)) { value = float.NaN; return true; } } else if (span.Length == 8) { if (span.SequenceEqual(JsonConstants.PositiveInfinityValue)) { value = float.PositiveInfinity; return true; } } else if (span.Length == 9 && span.SequenceEqual(JsonConstants.NegativeInfinityValue)) { value = float.NegativeInfinity; return true; } value = 0f; return false; } public static bool TryGetFloatingPointConstant(ReadOnlySpan span, out double value) { if (span.Length == 3) { if (span.SequenceEqual(JsonConstants.NaNValue)) { value = double.NaN; return true; } } else if (span.Length == 8) { if (span.SequenceEqual(JsonConstants.PositiveInfinityValue)) { value = double.PositiveInfinity; return true; } } else if (span.Length == 9 && span.SequenceEqual(JsonConstants.NegativeInfinityValue)) { value = double.NegativeInfinity; return true; } value = 0.0; return false; } public static bool TryGetUnescapedBase64Bytes(ReadOnlySpan utf8Source, int idx, [NotNullWhen(true)] out byte[] bytes) { byte[] array = null; Span span = ((utf8Source.Length > 256) ? ((Span)(array = ArrayPool.Shared.Rent(utf8Source.Length))) : stackalloc byte[utf8Source.Length]); Span span2 = span; Unescape(utf8Source, span2, idx, out var written); span2 = span2.Slice(0, written); bool result = TryDecodeBase64InPlace(span2, out bytes); if (array != null) { span2.Clear(); ArrayPool.Shared.Return(array); } return result; } public static string GetUnescapedString(ReadOnlySpan utf8Source, int idx) { int length = utf8Source.Length; byte[] array = null; Span span = ((length > 256) ? ((Span)(array = ArrayPool.Shared.Rent(length))) : stackalloc byte[length]); Span span2 = span; Unescape(utf8Source, span2, idx, out var written); span2 = span2.Slice(0, written); string result = TranscodeHelper(span2); if (array != null) { span2.Clear(); ArrayPool.Shared.Return(array); } return result; } public static ReadOnlySpan GetUnescapedSpan(ReadOnlySpan utf8Source, int idx) { int length = utf8Source.Length; byte[] array = null; Span span = ((length > 256) ? ((Span)(array = ArrayPool.Shared.Rent(length))) : stackalloc byte[length]); Span destination = span; Unescape(utf8Source, destination, idx, out var written); ReadOnlySpan result = destination.Slice(0, written).ToArray(); if (array != null) { new Span(array, 0, written).Clear(); ArrayPool.Shared.Return(array); } return result; } public static bool UnescapeAndCompare(ReadOnlySpan utf8Source, ReadOnlySpan other) { byte[] array = null; Span span = ((utf8Source.Length > 256) ? ((Span)(array = ArrayPool.Shared.Rent(utf8Source.Length))) : stackalloc byte[utf8Source.Length]); Span span2 = span; Unescape(utf8Source, span2, 0, out var written); span2 = span2.Slice(0, written); bool result = other.SequenceEqual(span2); if (array != null) { span2.Clear(); ArrayPool.Shared.Return(array); } return result; } public static bool UnescapeAndCompare(ReadOnlySequence utf8Source, ReadOnlySpan other) { byte[] array = null; byte[] array2 = null; int num = checked((int)utf8Source.Length); Span span = ((num > 256) ? ((Span)(array2 = ArrayPool.Shared.Rent(num))) : stackalloc byte[num]); Span span2 = span; Span span3 = ((num > 256) ? ((Span)(array = ArrayPool.Shared.Rent(num))) : stackalloc byte[num]); Span span4 = span3; utf8Source.CopyTo(span4); span4 = span4.Slice(0, num); Unescape(span4, span2, 0, out var written); span2 = span2.Slice(0, written); bool result = other.SequenceEqual(span2); if (array2 != null) { span2.Clear(); ArrayPool.Shared.Return(array2); span4.Clear(); ArrayPool.Shared.Return(array); } return result; } public static bool TryDecodeBase64InPlace(Span utf8Unescaped, [NotNullWhen(true)] out byte[] bytes) { if (Base64.DecodeFromUtf8InPlace(utf8Unescaped, out var bytesWritten) != 0) { bytes = null; return false; } bytes = utf8Unescaped.Slice(0, bytesWritten).ToArray(); return true; } public static bool TryDecodeBase64(ReadOnlySpan utf8Unescaped, [NotNullWhen(true)] out byte[] bytes) { byte[] array = null; Span span = ((utf8Unescaped.Length > 256) ? ((Span)(array = ArrayPool.Shared.Rent(utf8Unescaped.Length))) : stackalloc byte[utf8Unescaped.Length]); Span bytes2 = span; if (Base64.DecodeFromUtf8(utf8Unescaped, bytes2, out var _, out var bytesWritten) != 0) { bytes = null; if (array != null) { bytes2.Clear(); ArrayPool.Shared.Return(array); } return false; } bytes = bytes2.Slice(0, bytesWritten).ToArray(); if (array != null) { bytes2.Clear(); ArrayPool.Shared.Return(array); } return true; } public unsafe static string TranscodeHelper(ReadOnlySpan utf8Unescaped) { try { if (utf8Unescaped.IsEmpty) { return string.Empty; } fixed (byte* bytes = utf8Unescaped) { return s_utf8Encoding.GetString(bytes, utf8Unescaped.Length); } } catch (DecoderFallbackException innerException) { throw ThrowHelper.GetInvalidOperationException_ReadInvalidUTF8(innerException); } } internal unsafe static int GetUtf8ByteCount(ReadOnlySpan text) { try { if (text.IsEmpty) { return 0; } fixed (char* chars = text) { return s_utf8Encoding.GetByteCount(chars, text.Length); } } catch (EncoderFallbackException innerException) { throw ThrowHelper.GetArgumentException_ReadInvalidUTF16(innerException); } } internal unsafe static int GetUtf8FromText(ReadOnlySpan text, Span dest) { try { if (text.IsEmpty) { return 0; } fixed (char* chars = text) { fixed (byte* bytes = dest) { return s_utf8Encoding.GetBytes(chars, text.Length, bytes, dest.Length); } } } catch (EncoderFallbackException innerException) { throw ThrowHelper.GetArgumentException_ReadInvalidUTF16(innerException); } } internal unsafe static string GetTextFromUtf8(ReadOnlySpan utf8Text) { if (utf8Text.IsEmpty) { return string.Empty; } fixed (byte* bytes = utf8Text) { return s_utf8Encoding.GetString(bytes, utf8Text.Length); } } internal static void Unescape(ReadOnlySpan source, Span destination, int idx, out int written) { source.Slice(0, idx).CopyTo(destination); written = idx; while (idx < source.Length) { byte b = source[idx]; if (b == 92) { idx++; switch (source[idx]) { case 34: destination[written++] = 34; break; case 110: destination[written++] = 10; break; case 114: destination[written++] = 13; break; case 92: destination[written++] = 92; break; case 47: destination[written++] = 47; break; case 116: destination[written++] = 9; break; case 98: destination[written++] = 8; break; case 102: destination[written++] = 12; break; case 117: { bool flag = Utf8Parser.TryParse(source.Slice(idx + 1, 4), out int value, out int bytesConsumed, 'x'); idx += bytesConsumed; if (JsonHelpers.IsInRangeInclusive((uint)value, 55296u, 57343u)) { if (value >= 56320) { ThrowHelper.ThrowInvalidOperationException_ReadInvalidUTF16(value); } idx += 3; if (source.Length < idx + 4 || source[idx - 2] != 92 || source[idx - 1] != 117) { ThrowHelper.ThrowInvalidOperationException_ReadInvalidUTF16(); } flag = Utf8Parser.TryParse(source.Slice(idx, 4), out int value2, out bytesConsumed, 'x'); if (!JsonHelpers.IsInRangeInclusive((uint)value2, 56320u, 57343u)) { ThrowHelper.ThrowInvalidOperationException_ReadInvalidUTF16(value2); } idx += bytesConsumed - 1; value = 1024 * (value - 55296) + (value2 - 56320) + 65536; } EncodeToUtf8Bytes((uint)value, destination.Slice(written), out var bytesWritten); written += bytesWritten; break; } } } else { destination[written++] = b; } idx++; } } private static void EncodeToUtf8Bytes(uint scalar, Span utf8Destination, out int bytesWritten) { if (scalar < 128) { utf8Destination[0] = (byte)scalar; bytesWritten = 1; } else if (scalar < 2048) { utf8Destination[0] = (byte)(0xC0u | (scalar >> 6)); utf8Destination[1] = (byte)(0x80u | (scalar & 0x3Fu)); bytesWritten = 2; } else if (scalar < 65536) { utf8Destination[0] = (byte)(0xE0u | (scalar >> 12)); utf8Destination[1] = (byte)(0x80u | ((scalar >> 6) & 0x3Fu)); utf8Destination[2] = (byte)(0x80u | (scalar & 0x3Fu)); bytesWritten = 3; } else { utf8Destination[0] = (byte)(0xF0u | (scalar >> 18)); utf8Destination[1] = (byte)(0x80u | ((scalar >> 12) & 0x3Fu)); utf8Destination[2] = (byte)(0x80u | ((scalar >> 6) & 0x3Fu)); utf8Destination[3] = (byte)(0x80u | (scalar & 0x3Fu)); bytesWritten = 4; } } } internal struct JsonReaderOptions { internal const int DefaultMaxDepth = 64; private int _maxDepth; private JsonCommentHandling _commentHandling; public JsonCommentHandling CommentHandling { readonly get { return _commentHandling; } set { if ((int)value > 2) { throw ThrowHelper.GetArgumentOutOfRangeException_CommentEnumMustBeInRange("value"); } _commentHandling = value; } } public int MaxDepth { readonly get { return _maxDepth; } set { if (value < 0) { throw ThrowHelper.GetArgumentOutOfRangeException_MaxDepthMustBePositive("value"); } _maxDepth = value; } } public bool AllowTrailingCommas { get; set; } } internal struct JsonReaderState { internal long _lineNumber; internal long _bytePositionInLine; internal bool _inObject; internal bool _isNotPrimitive; internal char _numberFormat; internal bool _stringHasEscaping; internal bool _trailingCommaBeforeComment; internal JsonTokenType _tokenType; internal JsonTokenType _previousTokenType; internal JsonReaderOptions _readerOptions; internal BitStack _bitStack; public JsonReaderOptions Options => _readerOptions; public JsonReaderState(JsonReaderOptions options = default(JsonReaderOptions)) { _lineNumber = 0L; _bytePositionInLine = 0L; _inObject = false; _isNotPrimitive = false; _numberFormat = '\0'; _stringHasEscaping = false; _trailingCommaBeforeComment = false; _tokenType = JsonTokenType.None; _previousTokenType = JsonTokenType.None; _readerOptions = options; _bitStack = default(BitStack); } } [DebuggerDisplay("{DebuggerDisplay,nq}")] internal ref struct Utf8JsonReader { private readonly struct PartialStateForRollback { public readonly long _prevTotalConsumed; public readonly long _prevBytePositionInLine; public readonly int _prevConsumed; public readonly SequencePosition _prevCurrentPosition; public PartialStateForRollback(long totalConsumed, long bytePositionInLine, int consumed, SequencePosition currentPosition) { _prevTotalConsumed = totalConsumed; _prevBytePositionInLine = bytePositionInLine; _prevConsumed = consumed; _prevCurrentPosition = currentPosition; } public SequencePosition GetStartPosition(int offset = 0) { return new SequencePosition(_prevCurrentPosition.GetObject(), _prevCurrentPosition.GetInteger() + _prevConsumed + offset); } } private ReadOnlySpan _buffer; private readonly bool _isFinalBlock; private readonly bool _isInputSequence; private long _lineNumber; private long _bytePositionInLine; private int _consumed; private bool _inObject; private bool _isNotPrimitive; internal char _numberFormat; private JsonTokenType _tokenType; private JsonTokenType _previousTokenType; private JsonReaderOptions _readerOptions; private BitStack _bitStack; private long _totalConsumed; private bool _isLastSegment; internal bool _stringHasEscaping; private readonly bool _isMultiSegment; private bool _trailingCommaBeforeComment; private SequencePosition _nextPosition; private SequencePosition _currentPosition; private readonly ReadOnlySequence _sequence; private bool IsLastSpan { get { if (_isFinalBlock) { if (_isMultiSegment) { return _isLastSegment; } return true; } return false; } } internal ReadOnlySequence OriginalSequence => _sequence; internal ReadOnlySpan OriginalSpan { get { if (!_sequence.IsEmpty) { return default(ReadOnlySpan); } return _buffer; } } public ReadOnlySpan ValueSpan { get; private set; } public long BytesConsumed => _totalConsumed + _consumed; public long TokenStartIndex { get; private set; } public int CurrentDepth { get { int num = _bitStack.CurrentDepth; if (TokenType == JsonTokenType.StartArray || TokenType == JsonTokenType.StartObject) { num--; } return num; } } internal bool IsInArray => !_inObject; public JsonTokenType TokenType => _tokenType; public bool HasValueSequence { get; private set; } public bool IsFinalBlock => _isFinalBlock; public ReadOnlySequence ValueSequence { get; private set; } public SequencePosition Position { get { if (_isInputSequence) { return _sequence.GetPosition(_consumed, _currentPosition); } return default(SequencePosition); } } public JsonReaderState CurrentState { get { JsonReaderState result = default(JsonReaderState); result._lineNumber = _lineNumber; result._bytePositionInLine = _bytePositionInLine; result._inObject = _inObject; result._isNotPrimitive = _isNotPrimitive; result._numberFormat = _numberFormat; result._stringHasEscaping = _stringHasEscaping; result._trailingCommaBeforeComment = _trailingCommaBeforeComment; result._tokenType = _tokenType; result._previousTokenType = _previousTokenType; result._readerOptions = _readerOptions; result._bitStack = _bitStack; return result; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay => $"TokenType = {DebugTokenType} (TokenStartIndex = {TokenStartIndex}) Consumed = {BytesConsumed}"; private string DebugTokenType => TokenType switch { JsonTokenType.Comment => "Comment", JsonTokenType.EndArray => "EndArray", JsonTokenType.EndObject => "EndObject", JsonTokenType.False => "False", JsonTokenType.None => "None", JsonTokenType.Null => "Null", JsonTokenType.Number => "Number", JsonTokenType.PropertyName => "PropertyName", JsonTokenType.StartArray => "StartArray", JsonTokenType.StartObject => "StartObject", JsonTokenType.String => "String", JsonTokenType.True => "True", _ => ((byte)TokenType).ToString(), }; public Utf8JsonReader(ReadOnlySpan jsonData, bool isFinalBlock, JsonReaderState state) { _buffer = jsonData; _isFinalBlock = isFinalBlock; _isInputSequence = false; _lineNumber = state._lineNumber; _bytePositionInLine = state._bytePositionInLine; _inObject = state._inObject; _isNotPrimitive = state._isNotPrimitive; _numberFormat = state._numberFormat; _stringHasEscaping = state._stringHasEscaping; _trailingCommaBeforeComment = state._trailingCommaBeforeComment; _tokenType = state._tokenType; _previousTokenType = state._previousTokenType; _readerOptions = state._readerOptions; if (_readerOptions.MaxDepth == 0) { _readerOptions.MaxDepth = 64; } _bitStack = state._bitStack; _consumed = 0; TokenStartIndex = 0L; _totalConsumed = 0L; _isLastSegment = _isFinalBlock; _isMultiSegment = false; ValueSpan = ReadOnlySpan.Empty; _currentPosition = default(SequencePosition); _nextPosition = default(SequencePosition); _sequence = default(ReadOnlySequence); HasValueSequence = false; ValueSequence = ReadOnlySequence.Empty; } public Utf8JsonReader(ReadOnlySpan jsonData, JsonReaderOptions options = default(JsonReaderOptions)) : this(jsonData, isFinalBlock: true, new JsonReaderState(options)) { } public bool Read() { bool flag = (_isMultiSegment ? ReadMultiSegment() : ReadSingleSegment()); if (!flag && _isFinalBlock && TokenType == JsonTokenType.None) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedJsonTokens, 0); } return flag; } public void Skip() { if (!_isFinalBlock) { throw ThrowHelper.GetInvalidOperationException_CannotSkipOnPartial(); } SkipHelper(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void SkipHelper() { if (TokenType == JsonTokenType.PropertyName) { bool flag = Read(); } if (TokenType == JsonTokenType.StartObject || TokenType == JsonTokenType.StartArray) { int currentDepth = CurrentDepth; do { bool flag2 = Read(); } while (currentDepth < CurrentDepth); } } public bool TrySkip() { if (_isFinalBlock) { SkipHelper(); return true; } return TrySkipHelper(); } private bool TrySkipHelper() { Utf8JsonReader utf8JsonReader = this; if (TokenType != JsonTokenType.PropertyName || Read()) { if (TokenType != JsonTokenType.StartObject && TokenType != JsonTokenType.StartArray) { goto IL_0042; } int currentDepth = CurrentDepth; while (Read()) { if (currentDepth < CurrentDepth) { continue; } goto IL_0042; } } this = utf8JsonReader; return false; IL_0042: return true; } public bool ValueTextEquals(ReadOnlySpan utf8Text) { if (!IsTokenTypeString(TokenType)) { throw ThrowHelper.GetInvalidOperationException_ExpectedStringComparison(TokenType); } return TextEqualsHelper(utf8Text); } public bool ValueTextEquals(string? text) { return ValueTextEquals(MemoryExtensions.AsSpan(text)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool TextEqualsHelper(ReadOnlySpan otherUtf8Text) { if (HasValueSequence) { return CompareToSequence(otherUtf8Text); } if (_stringHasEscaping) { return UnescapeAndCompare(otherUtf8Text); } return otherUtf8Text.SequenceEqual(ValueSpan); } public unsafe bool ValueTextEquals(ReadOnlySpan text) { if (!IsTokenTypeString(TokenType)) { throw ThrowHelper.GetInvalidOperationException_ExpectedStringComparison(TokenType); } if (MatchNotPossible(text.Length)) { return false; } byte[] array = null; int num = checked(text.Length * 3); Span utf8Destination; if (num > 256) { array = ArrayPool.Shared.Rent(num); utf8Destination = array; } else { byte* pointer = stackalloc byte[256]; utf8Destination = new Span(pointer, 256); } ReadOnlySpan utf16Source = MemoryMarshal.AsBytes(text); int bytesConsumed; int bytesWritten; OperationStatus operationStatus = JsonWriterHelper.ToUtf8(utf16Source, utf8Destination, out bytesConsumed, out bytesWritten); bool result = operationStatus <= OperationStatus.DestinationTooSmall && TextEqualsHelper(utf8Destination.Slice(0, bytesWritten)); if (array != null) { utf8Destination.Slice(0, bytesWritten).Clear(); ArrayPool.Shared.Return(array); } return result; } private bool CompareToSequence(ReadOnlySpan other) { if (_stringHasEscaping) { return UnescapeSequenceAndCompare(other); } ReadOnlySequence valueSequence = ValueSequence; if (valueSequence.Length != other.Length) { return false; } int num = 0; ReadOnlySequence.Enumerator enumerator = valueSequence.GetEnumerator(); while (enumerator.MoveNext()) { ReadOnlySpan span = enumerator.Current.Span; if (other.Slice(num).StartsWith(span)) { num += span.Length; continue; } return false; } return true; } private bool UnescapeAndCompare(ReadOnlySpan other) { ReadOnlySpan valueSpan = ValueSpan; if (valueSpan.Length < other.Length || valueSpan.Length / 6 > other.Length) { return false; } int num = valueSpan.IndexOf(92); if (!other.StartsWith(valueSpan.Slice(0, num))) { return false; } return JsonReaderHelper.UnescapeAndCompare(valueSpan.Slice(num), other.Slice(num)); } private bool UnescapeSequenceAndCompare(ReadOnlySpan other) { ReadOnlySequence valueSequence = ValueSequence; long length = valueSequence.Length; if (length < other.Length || length / 6 > other.Length) { return false; } int num = 0; bool result = false; ReadOnlySequence.Enumerator enumerator = valueSequence.GetEnumerator(); while (enumerator.MoveNext()) { ReadOnlySpan span = enumerator.Current.Span; int num2 = span.IndexOf(92); if (num2 != -1) { if (other.Slice(num).StartsWith(span.Slice(0, num2))) { num += num2; other = other.Slice(num); valueSequence = valueSequence.Slice(num); result = ((!valueSequence.IsSingleSegment) ? JsonReaderHelper.UnescapeAndCompare(valueSequence, other) : JsonReaderHelper.UnescapeAndCompare(valueSequence.First.Span, other)); } break; } if (!other.Slice(num).StartsWith(span)) { break; } num += span.Length; } return result; } private static bool IsTokenTypeString(JsonTokenType tokenType) { if (tokenType != JsonTokenType.PropertyName) { return tokenType == JsonTokenType.String; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool MatchNotPossible(int charTextLength) { if (HasValueSequence) { return MatchNotPossibleSequence(charTextLength); } int length = ValueSpan.Length; if (length < charTextLength || length / (_stringHasEscaping ? 6 : 3) > charTextLength) { return true; } return false; } [MethodImpl(MethodImplOptions.NoInlining)] private bool MatchNotPossibleSequence(int charTextLength) { long length = ValueSequence.Length; if (length < charTextLength || length / (_stringHasEscaping ? 6 : 3) > charTextLength) { return true; } return false; } private void StartObject() { if (_bitStack.CurrentDepth >= _readerOptions.MaxDepth) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ObjectDepthTooLarge, 0); } _bitStack.PushTrue(); ValueSpan = _buffer.Slice(_consumed, 1); _consumed++; _bytePositionInLine++; _tokenType = JsonTokenType.StartObject; _inObject = true; } private void EndObject() { if (!_inObject || _bitStack.CurrentDepth <= 0) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.MismatchedObjectArray, 125); } if (_trailingCommaBeforeComment) { if (!_readerOptions.AllowTrailingCommas) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd, 0); } _trailingCommaBeforeComment = false; } _tokenType = JsonTokenType.EndObject; ValueSpan = _buffer.Slice(_consumed, 1); UpdateBitStackOnEndToken(); } private void StartArray() { if (_bitStack.CurrentDepth >= _readerOptions.MaxDepth) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ArrayDepthTooLarge, 0); } _bitStack.PushFalse(); ValueSpan = _buffer.Slice(_consumed, 1); _consumed++; _bytePositionInLine++; _tokenType = JsonTokenType.StartArray; _inObject = false; } private void EndArray() { if (_inObject || _bitStack.CurrentDepth <= 0) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.MismatchedObjectArray, 93); } if (_trailingCommaBeforeComment) { if (!_readerOptions.AllowTrailingCommas) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd, 0); } _trailingCommaBeforeComment = false; } _tokenType = JsonTokenType.EndArray; ValueSpan = _buffer.Slice(_consumed, 1); UpdateBitStackOnEndToken(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void UpdateBitStackOnEndToken() { _consumed++; _bytePositionInLine++; _inObject = _bitStack.Pop(); } private bool ReadSingleSegment() { bool flag = false; ValueSpan = default(ReadOnlySpan); if (HasMoreData()) { byte b = _buffer[_consumed]; if (b <= 32) { SkipWhiteSpace(); if (!HasMoreData()) { goto IL_0132; } b = _buffer[_consumed]; } TokenStartIndex = _consumed; if (_tokenType != 0) { if (b == 47) { flag = ConsumeNextTokenOrRollback(b); } else if (_tokenType == JsonTokenType.StartObject) { if (b == 125) { EndObject(); goto IL_0130; } if (b != 34) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); } int consumed = _consumed; long bytePositionInLine = _bytePositionInLine; long lineNumber = _lineNumber; flag = ConsumePropertyName(); if (!flag) { _consumed = consumed; _tokenType = JsonTokenType.StartObject; _bytePositionInLine = bytePositionInLine; _lineNumber = lineNumber; } } else if (_tokenType != JsonTokenType.StartArray) { flag = ((_tokenType != JsonTokenType.PropertyName) ? ConsumeNextTokenOrRollback(b) : ConsumeValue(b)); } else { if (b == 93) { EndArray(); goto IL_0130; } flag = ConsumeValue(b); } } else { flag = ReadFirstToken(b); } } goto IL_0132; IL_0130: flag = true; goto IL_0132; IL_0132: return flag; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool HasMoreData() { if (_consumed >= (uint)_buffer.Length) { if (_isNotPrimitive && IsLastSpan) { if (_bitStack.CurrentDepth != 0) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ZeroDepthAtEnd, 0); } if (_readerOptions.CommentHandling == JsonCommentHandling.Allow && _tokenType == JsonTokenType.Comment) { return false; } if (_tokenType != JsonTokenType.EndArray && _tokenType != JsonTokenType.EndObject) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidEndOfJsonNonPrimitive, 0); } } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool HasMoreData(ExceptionResource resource) { if (_consumed >= (uint)_buffer.Length) { if (IsLastSpan) { ThrowHelper.ThrowJsonReaderException(ref this, resource, 0); } return false; } return true; } private bool ReadFirstToken(byte first) { switch (first) { case 123: _bitStack.SetFirstBit(); _tokenType = JsonTokenType.StartObject; ValueSpan = _buffer.Slice(_consumed, 1); _consumed++; _bytePositionInLine++; _inObject = true; _isNotPrimitive = true; break; case 91: _bitStack.ResetFirstBit(); _tokenType = JsonTokenType.StartArray; ValueSpan = _buffer.Slice(_consumed, 1); _consumed++; _bytePositionInLine++; _isNotPrimitive = true; break; default: { ReadOnlySpan buffer = _buffer; if (JsonHelpers.IsDigit(first) || first == 45) { if (!TryGetNumber(buffer.Slice(_consumed), out var consumed)) { return false; } _tokenType = JsonTokenType.Number; _consumed += consumed; _bytePositionInLine += consumed; return true; } if (!ConsumeValue(first)) { return false; } if (_tokenType == JsonTokenType.StartObject || _tokenType == JsonTokenType.StartArray) { _isNotPrimitive = true; } break; } } return true; } private void SkipWhiteSpace() { ReadOnlySpan buffer = _buffer; while (_consumed < buffer.Length) { byte b = buffer[_consumed]; if (b == 32 || b == 13 || b == 10 || b == 9) { if (b == 10) { _lineNumber++; _bytePositionInLine = 0L; } else { _bytePositionInLine++; } _consumed++; continue; } break; } } private bool ConsumeValue(byte marker) { while (true) { _trailingCommaBeforeComment = false; switch (marker) { case 34: return ConsumeString(); case 123: StartObject(); break; case 91: StartArray(); break; default: if (JsonHelpers.IsDigit(marker) || marker == 45) { return ConsumeNumber(); } switch (marker) { case 102: return ConsumeLiteral(JsonConstants.FalseValue, JsonTokenType.False); case 116: return ConsumeLiteral(JsonConstants.TrueValue, JsonTokenType.True); case 110: return ConsumeLiteral(JsonConstants.NullValue, JsonTokenType.Null); } switch (_readerOptions.CommentHandling) { case JsonCommentHandling.Allow: if (marker == 47) { return ConsumeComment(); } break; default: if (marker != 47) { break; } if (SkipComment()) { if (_consumed >= (uint)_buffer.Length) { if (_isNotPrimitive && IsLastSpan && _tokenType != JsonTokenType.EndArray && _tokenType != JsonTokenType.EndObject) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidEndOfJsonNonPrimitive, 0); } return false; } marker = _buffer[_consumed]; if (marker <= 32) { SkipWhiteSpace(); if (!HasMoreData()) { return false; } marker = _buffer[_consumed]; } goto IL_0140; } return false; case JsonCommentHandling.Disallow: break; } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfValueNotFound, marker); break; } break; IL_0140: TokenStartIndex = _consumed; } return true; } private bool ConsumeLiteral(ReadOnlySpan literal, JsonTokenType tokenType) { ReadOnlySpan span = _buffer.Slice(_consumed); if (!span.StartsWith(literal)) { return CheckLiteral(span, literal); } ValueSpan = span.Slice(0, literal.Length); _tokenType = tokenType; _consumed += literal.Length; _bytePositionInLine += literal.Length; return true; } private bool CheckLiteral(ReadOnlySpan span, ReadOnlySpan literal) { int num = 0; for (int i = 1; i < literal.Length; i++) { if (span.Length > i) { if (span[i] != literal[i]) { _bytePositionInLine += i; ThrowInvalidLiteral(span); } continue; } num = i; break; } if (IsLastSpan) { _bytePositionInLine += num; ThrowInvalidLiteral(span); } return false; } private void ThrowInvalidLiteral(ReadOnlySpan span) { ThrowHelper.ThrowJsonReaderException(ref this, span[0] switch { 116 => ExceptionResource.ExpectedTrue, 102 => ExceptionResource.ExpectedFalse, _ => ExceptionResource.ExpectedNull, }, 0, span); } private bool ConsumeNumber() { if (!TryGetNumber(_buffer.Slice(_consumed), out var consumed)) { return false; } _tokenType = JsonTokenType.Number; _consumed += consumed; _bytePositionInLine += consumed; if (_consumed >= (uint)_buffer.Length && _isNotPrimitive) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndOfDigitNotFound, _buffer[_consumed - 1]); } return true; } private bool ConsumePropertyName() { _trailingCommaBeforeComment = false; if (!ConsumeString()) { return false; } if (!HasMoreData(ExceptionResource.ExpectedValueAfterPropertyNameNotFound)) { return false; } byte b = _buffer[_consumed]; if (b <= 32) { SkipWhiteSpace(); if (!HasMoreData(ExceptionResource.ExpectedValueAfterPropertyNameNotFound)) { return false; } b = _buffer[_consumed]; } if (b != 58) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedSeparatorAfterPropertyNameNotFound, b); } _consumed++; _bytePositionInLine++; _tokenType = JsonTokenType.PropertyName; return true; } private bool ConsumeString() { ReadOnlySpan readOnlySpan = _buffer.Slice(_consumed + 1); int num = readOnlySpan.IndexOfQuoteOrAnyControlOrBackSlash(); if (num >= 0) { byte b = readOnlySpan[num]; if (b == 34) { _bytePositionInLine += num + 2; ValueSpan = readOnlySpan.Slice(0, num); _stringHasEscaping = false; _tokenType = JsonTokenType.String; _consumed += num + 2; return true; } return ConsumeStringAndValidate(readOnlySpan, num); } if (IsLastSpan) { _bytePositionInLine += readOnlySpan.Length + 1; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound, 0); } return false; } private bool ConsumeStringAndValidate(ReadOnlySpan data, int idx) { long bytePositionInLine = _bytePositionInLine; long lineNumber = _lineNumber; _bytePositionInLine += idx + 1; bool flag = false; while (true) { if (idx < data.Length) { byte b = data[idx]; if (b == 34) { if (!flag) { break; } flag = false; } else if (b == 92) { flag = !flag; } else if (flag) { int num = JsonConstants.EscapableChars.IndexOf(b); if (num == -1) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterAfterEscapeWithinString, b); } if (b == 117) { _bytePositionInLine++; if (!ValidateHexDigits(data, idx + 1)) { idx = data.Length; goto IL_00e5; } idx += 4; } flag = false; } else if (b < 32) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterWithinString, b); } _bytePositionInLine++; idx++; continue; } goto IL_00e5; IL_00e5: if (idx < data.Length) { break; } if (IsLastSpan) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound, 0); } _lineNumber = lineNumber; _bytePositionInLine = bytePositionInLine; return false; } _bytePositionInLine++; ValueSpan = data.Slice(0, idx); _stringHasEscaping = true; _tokenType = JsonTokenType.String; _consumed += idx + 2; return true; } private bool ValidateHexDigits(ReadOnlySpan data, int idx) { for (int i = idx; i < data.Length; i++) { byte nextByte = data[i]; if (!JsonReaderHelper.IsHexDigit(nextByte)) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidHexCharacterWithinString, nextByte); } if (i - idx >= 3) { return true; } _bytePositionInLine++; } return false; } private bool TryGetNumber(ReadOnlySpan data, out int consumed) { _numberFormat = '\0'; consumed = 0; int i = 0; ConsumeNumberResult consumeNumberResult = ConsumeNegativeSign(ref data, ref i); if (consumeNumberResult == ConsumeNumberResult.NeedMoreData) { return false; } byte b = data[i]; if (b == 48) { ConsumeNumberResult consumeNumberResult2 = ConsumeZero(ref data, ref i); if (consumeNumberResult2 == ConsumeNumberResult.NeedMoreData) { return false; } if (consumeNumberResult2 != 0) { b = data[i]; goto IL_00aa; } } else { i++; ConsumeNumberResult consumeNumberResult3 = ConsumeIntegerDigits(ref data, ref i); if (consumeNumberResult3 == ConsumeNumberResult.NeedMoreData) { return false; } if (consumeNumberResult3 != 0) { b = data[i]; if (b != 46 && b != 69 && b != 101) { _bytePositionInLine += i; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndOfDigitNotFound, b); } goto IL_00aa; } } goto IL_0161; IL_00aa: if (b == 46) { i++; ConsumeNumberResult consumeNumberResult4 = ConsumeDecimalDigits(ref data, ref i); if (consumeNumberResult4 == ConsumeNumberResult.NeedMoreData) { return false; } if (consumeNumberResult4 == ConsumeNumberResult.Success) { goto IL_0161; } b = data[i]; if (b != 69 && b != 101) { _bytePositionInLine += i; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedNextDigitEValueNotFound, b); } } i++; _numberFormat = 'e'; consumeNumberResult = ConsumeSign(ref data, ref i); if (consumeNumberResult == ConsumeNumberResult.NeedMoreData) { return false; } i++; switch (ConsumeIntegerDigits(ref data, ref i)) { case ConsumeNumberResult.NeedMoreData: return false; default: _bytePositionInLine += i; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndOfDigitNotFound, data[i]); break; case ConsumeNumberResult.Success: break; } goto IL_0161; IL_0161: ValueSpan = data.Slice(0, i); consumed = i; return true; } private ConsumeNumberResult ConsumeNegativeSign(ref ReadOnlySpan data, ref int i) { byte b = data[i]; if (b == 45) { i++; if (i >= data.Length) { if (IsLastSpan) { _bytePositionInLine += i; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); } return ConsumeNumberResult.NeedMoreData; } b = data[i]; if (!JsonHelpers.IsDigit(b)) { _bytePositionInLine += i; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundAfterSign, b); } } return ConsumeNumberResult.OperationIncomplete; } private ConsumeNumberResult ConsumeZero(ref ReadOnlySpan data, ref int i) { i++; byte b = 0; if (i < data.Length) { b = data[i]; if (JsonConstants.Delimiters.IndexOf(b) >= 0) { return ConsumeNumberResult.Success; } b = data[i]; if (b != 46 && b != 69 && b != 101) { _bytePositionInLine += i; ThrowHelper.ThrowJsonReaderException(ref this, JsonHelpers.IsInRangeInclusive(b, 48, 57) ? ExceptionResource.InvalidLeadingZeroInNumber : ExceptionResource.ExpectedEndOfDigitNotFound, b); } return ConsumeNumberResult.OperationIncomplete; } if (IsLastSpan) { return ConsumeNumberResult.Success; } return ConsumeNumberResult.NeedMoreData; } private ConsumeNumberResult ConsumeIntegerDigits(ref ReadOnlySpan data, ref int i) { byte value = 0; while (i < data.Length) { value = data[i]; if (!JsonHelpers.IsDigit(value)) { break; } i++; } if (i >= data.Length) { if (IsLastSpan) { return ConsumeNumberResult.Success; } return ConsumeNumberResult.NeedMoreData; } if (JsonConstants.Delimiters.IndexOf(value) >= 0) { return ConsumeNumberResult.Success; } return ConsumeNumberResult.OperationIncomplete; } private ConsumeNumberResult ConsumeDecimalDigits(ref ReadOnlySpan data, ref int i) { if (i >= data.Length) { if (IsLastSpan) { _bytePositionInLine += i; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); } return ConsumeNumberResult.NeedMoreData; } byte b = data[i]; if (!JsonHelpers.IsDigit(b)) { _bytePositionInLine += i; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundAfterDecimal, b); } i++; return ConsumeIntegerDigits(ref data, ref i); } private ConsumeNumberResult ConsumeSign(ref ReadOnlySpan data, ref int i) { if (i >= data.Length) { if (IsLastSpan) { _bytePositionInLine += i; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); } return ConsumeNumberResult.NeedMoreData; } byte b = data[i]; if (b == 43 || b == 45) { i++; if (i >= data.Length) { if (IsLastSpan) { _bytePositionInLine += i; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); } return ConsumeNumberResult.NeedMoreData; } b = data[i]; } if (!JsonHelpers.IsDigit(b)) { _bytePositionInLine += i; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundAfterSign, b); } return ConsumeNumberResult.OperationIncomplete; } private bool ConsumeNextTokenOrRollback(byte marker) { int consumed = _consumed; long bytePositionInLine = _bytePositionInLine; long lineNumber = _lineNumber; JsonTokenType tokenType = _tokenType; bool trailingCommaBeforeComment = _trailingCommaBeforeComment; switch (ConsumeNextToken(marker)) { case ConsumeTokenResult.Success: return true; case ConsumeTokenResult.NotEnoughDataRollBackState: _consumed = consumed; _tokenType = tokenType; _bytePositionInLine = bytePositionInLine; _lineNumber = lineNumber; _trailingCommaBeforeComment = trailingCommaBeforeComment; break; } return false; } private ConsumeTokenResult ConsumeNextToken(byte marker) { if (_readerOptions.CommentHandling != 0) { if (_readerOptions.CommentHandling != JsonCommentHandling.Allow) { return ConsumeNextTokenUntilAfterAllCommentsAreSkipped(marker); } if (marker == 47) { if (!ConsumeComment()) { return ConsumeTokenResult.NotEnoughDataRollBackState; } return ConsumeTokenResult.Success; } if (_tokenType == JsonTokenType.Comment) { return ConsumeNextTokenFromLastNonCommentToken(); } } if (_bitStack.CurrentDepth == 0) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndAfterSingleJson, marker); } switch (marker) { case 44: { _consumed++; _bytePositionInLine++; if (_consumed >= (uint)_buffer.Length) { if (IsLastSpan) { _consumed--; _bytePositionInLine--; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); } return ConsumeTokenResult.NotEnoughDataRollBackState; } byte b = _buffer[_consumed]; if (b <= 32) { SkipWhiteSpace(); if (!HasMoreData(ExceptionResource.ExpectedStartOfPropertyOrValueNotFound)) { return ConsumeTokenResult.NotEnoughDataRollBackState; } b = _buffer[_consumed]; } TokenStartIndex = _consumed; if (_readerOptions.CommentHandling == JsonCommentHandling.Allow && b == 47) { _trailingCommaBeforeComment = true; if (!ConsumeComment()) { return ConsumeTokenResult.NotEnoughDataRollBackState; } return ConsumeTokenResult.Success; } if (_inObject) { if (b != 34) { if (b == 125) { if (_readerOptions.AllowTrailingCommas) { EndObject(); return ConsumeTokenResult.Success; } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd, 0); } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); } if (!ConsumePropertyName()) { return ConsumeTokenResult.NotEnoughDataRollBackState; } return ConsumeTokenResult.Success; } if (b == 93) { if (_readerOptions.AllowTrailingCommas) { EndArray(); return ConsumeTokenResult.Success; } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd, 0); } if (!ConsumeValue(b)) { return ConsumeTokenResult.NotEnoughDataRollBackState; } return ConsumeTokenResult.Success; } case 125: EndObject(); break; case 93: EndArray(); break; default: ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.FoundInvalidCharacter, marker); break; } return ConsumeTokenResult.Success; } private ConsumeTokenResult ConsumeNextTokenFromLastNonCommentToken() { if (JsonReaderHelper.IsTokenTypePrimitive(_previousTokenType)) { _tokenType = (_inObject ? JsonTokenType.StartObject : JsonTokenType.StartArray); } else { _tokenType = _previousTokenType; } if (HasMoreData()) { byte b = _buffer[_consumed]; if (b <= 32) { SkipWhiteSpace(); if (!HasMoreData()) { goto IL_0343; } b = _buffer[_consumed]; } if (_bitStack.CurrentDepth == 0 && _tokenType != 0) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndAfterSingleJson, b); } TokenStartIndex = _consumed; if (b != 44) { if (b == 125) { EndObject(); } else { if (b != 93) { if (_tokenType == JsonTokenType.None) { if (ReadFirstToken(b)) { goto IL_0341; } } else if (_tokenType == JsonTokenType.StartObject) { if (b != 34) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); } int consumed = _consumed; long bytePositionInLine = _bytePositionInLine; long lineNumber = _lineNumber; if (ConsumePropertyName()) { goto IL_0341; } _consumed = consumed; _tokenType = JsonTokenType.StartObject; _bytePositionInLine = bytePositionInLine; _lineNumber = lineNumber; } else if (_tokenType == JsonTokenType.StartArray) { if (ConsumeValue(b)) { goto IL_0341; } } else if (_tokenType == JsonTokenType.PropertyName) { if (ConsumeValue(b)) { goto IL_0341; } } else if (_inObject) { if (b != 34) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); } if (ConsumePropertyName()) { goto IL_0341; } } else if (ConsumeValue(b)) { goto IL_0341; } goto IL_0343; } EndArray(); } goto IL_0341; } if ((int)_previousTokenType <= 1 || _previousTokenType == JsonTokenType.StartArray || _trailingCommaBeforeComment) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueAfterComment, b); } _consumed++; _bytePositionInLine++; if (_consumed >= (uint)_buffer.Length) { if (IsLastSpan) { _consumed--; _bytePositionInLine--; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); } } else { b = _buffer[_consumed]; if (b <= 32) { SkipWhiteSpace(); if (!HasMoreData(ExceptionResource.ExpectedStartOfPropertyOrValueNotFound)) { goto IL_0343; } b = _buffer[_consumed]; } TokenStartIndex = _consumed; if (b == 47) { _trailingCommaBeforeComment = true; if (ConsumeComment()) { goto IL_0341; } } else if (_inObject) { if (b != 34) { if (b == 125) { if (_readerOptions.AllowTrailingCommas) { EndObject(); goto IL_0341; } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd, 0); } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); } if (ConsumePropertyName()) { goto IL_0341; } } else { if (b == 93) { if (_readerOptions.AllowTrailingCommas) { EndArray(); goto IL_0341; } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd, 0); } if (ConsumeValue(b)) { goto IL_0341; } } } } goto IL_0343; IL_0343: return ConsumeTokenResult.NotEnoughDataRollBackState; IL_0341: return ConsumeTokenResult.Success; } private bool SkipAllComments(ref byte marker) { while (true) { if (marker == 47) { if (!SkipComment() || !HasMoreData()) { break; } marker = _buffer[_consumed]; if (marker <= 32) { SkipWhiteSpace(); if (!HasMoreData()) { break; } marker = _buffer[_consumed]; } continue; } return true; } return false; } private bool SkipAllComments(ref byte marker, ExceptionResource resource) { while (true) { if (marker == 47) { if (!SkipComment() || !HasMoreData(resource)) { break; } marker = _buffer[_consumed]; if (marker <= 32) { SkipWhiteSpace(); if (!HasMoreData(resource)) { break; } marker = _buffer[_consumed]; } continue; } return true; } return false; } private ConsumeTokenResult ConsumeNextTokenUntilAfterAllCommentsAreSkipped(byte marker) { if (SkipAllComments(ref marker)) { TokenStartIndex = _consumed; if (_tokenType == JsonTokenType.StartObject) { if (marker == 125) { EndObject(); } else { if (marker != 34) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, marker); } int consumed = _consumed; long bytePositionInLine = _bytePositionInLine; long lineNumber = _lineNumber; if (!ConsumePropertyName()) { _consumed = consumed; _tokenType = JsonTokenType.StartObject; _bytePositionInLine = bytePositionInLine; _lineNumber = lineNumber; goto IL_0281; } } } else if (_tokenType == JsonTokenType.StartArray) { if (marker == 93) { EndArray(); } else if (!ConsumeValue(marker)) { goto IL_0281; } } else if (_tokenType == JsonTokenType.PropertyName) { if (!ConsumeValue(marker)) { goto IL_0281; } } else if (_bitStack.CurrentDepth == 0) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndAfterSingleJson, marker); } else { switch (marker) { case 44: _consumed++; _bytePositionInLine++; if (_consumed >= (uint)_buffer.Length) { if (IsLastSpan) { _consumed--; _bytePositionInLine--; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); } return ConsumeTokenResult.NotEnoughDataRollBackState; } marker = _buffer[_consumed]; if (marker <= 32) { SkipWhiteSpace(); if (!HasMoreData(ExceptionResource.ExpectedStartOfPropertyOrValueNotFound)) { return ConsumeTokenResult.NotEnoughDataRollBackState; } marker = _buffer[_consumed]; } if (SkipAllComments(ref marker, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound)) { TokenStartIndex = _consumed; if (_inObject) { if (marker != 34) { if (marker == 125) { if (_readerOptions.AllowTrailingCommas) { EndObject(); break; } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd, 0); } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, marker); } if (!ConsumePropertyName()) { return ConsumeTokenResult.NotEnoughDataRollBackState; } return ConsumeTokenResult.Success; } if (marker == 93) { if (_readerOptions.AllowTrailingCommas) { EndArray(); break; } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd, 0); } if (!ConsumeValue(marker)) { return ConsumeTokenResult.NotEnoughDataRollBackState; } return ConsumeTokenResult.Success; } return ConsumeTokenResult.NotEnoughDataRollBackState; case 125: EndObject(); break; case 93: EndArray(); break; default: ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.FoundInvalidCharacter, marker); break; } } return ConsumeTokenResult.Success; } goto IL_0281; IL_0281: return ConsumeTokenResult.IncompleteNoRollBackNecessary; } private bool SkipComment() { ReadOnlySpan readOnlySpan = _buffer.Slice(_consumed + 1); if (readOnlySpan.Length > 0) { int idx; switch (readOnlySpan[0]) { case 47: return SkipSingleLineComment(readOnlySpan.Slice(1), out idx); case 42: return SkipMultiLineComment(readOnlySpan.Slice(1), out idx); } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfValueNotFound, 47); } if (IsLastSpan) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfValueNotFound, 47); } return false; } private bool SkipSingleLineComment(ReadOnlySpan localBuffer, out int idx) { idx = FindLineSeparator(localBuffer); int num = 0; if (idx != -1) { num = idx; if (localBuffer[idx] != 10) { if (idx < localBuffer.Length - 1) { if (localBuffer[idx + 1] == 10) { num++; } } else if (!IsLastSpan) { return false; } } num++; _bytePositionInLine = 0L; _lineNumber++; } else { if (!IsLastSpan) { return false; } idx = localBuffer.Length; num = idx; _bytePositionInLine += 2 + localBuffer.Length; } _consumed += 2 + num; return true; } private int FindLineSeparator(ReadOnlySpan localBuffer) { int num = 0; while (true) { int num2 = localBuffer.IndexOfAny(10, 13, 226); if (num2 == -1) { return -1; } num += num2; if (localBuffer[num2] != 226) { break; } num++; localBuffer = localBuffer.Slice(num2 + 1); ThrowOnDangerousLineSeparator(localBuffer); } return num; } private void ThrowOnDangerousLineSeparator(ReadOnlySpan localBuffer) { if (localBuffer.Length >= 2) { byte b = localBuffer[1]; if (localBuffer[0] == 128 && (b == 168 || b == 169)) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfLineSeparator, 0); } } } private bool SkipMultiLineComment(ReadOnlySpan localBuffer, out int idx) { idx = 0; while (true) { int num = localBuffer.Slice(idx).IndexOf(47); switch (num) { case -1: if (IsLastSpan) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfCommentNotFound, 0); } return false; default: if (localBuffer[num + idx - 1] == 42) { idx += num - 1; _consumed += 4 + idx; var (num2, num3) = JsonReaderHelper.CountNewLines(localBuffer.Slice(0, idx)); _lineNumber += num2; if (num3 != -1) { _bytePositionInLine = idx - num3 + 1; } else { _bytePositionInLine += 4 + idx; } return true; } break; case 0: break; } idx += num + 1; } } private bool ConsumeComment() { ReadOnlySpan readOnlySpan = _buffer.Slice(_consumed + 1); if (readOnlySpan.Length > 0) { byte b = readOnlySpan[0]; switch (b) { case 47: return ConsumeSingleLineComment(readOnlySpan.Slice(1), _consumed); case 42: return ConsumeMultiLineComment(readOnlySpan.Slice(1), _consumed); } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterAtStartOfComment, b); } if (IsLastSpan) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfDataWhileReadingComment, 0); } return false; } private bool ConsumeSingleLineComment(ReadOnlySpan localBuffer, int previousConsumed) { if (!SkipSingleLineComment(localBuffer, out var idx)) { return false; } ValueSpan = _buffer.Slice(previousConsumed + 2, idx); if (_tokenType != JsonTokenType.Comment) { _previousTokenType = _tokenType; } _tokenType = JsonTokenType.Comment; return true; } private bool ConsumeMultiLineComment(ReadOnlySpan localBuffer, int previousConsumed) { if (!SkipMultiLineComment(localBuffer, out var idx)) { return false; } ValueSpan = _buffer.Slice(previousConsumed + 2, idx); if (_tokenType != JsonTokenType.Comment) { _previousTokenType = _tokenType; } _tokenType = JsonTokenType.Comment; return true; } private ReadOnlySpan GetUnescapedSpan() { ReadOnlySpan readOnlySpan; if (!HasValueSequence) { readOnlySpan = ValueSpan; } else { ReadOnlySequence sequence = ValueSequence; readOnlySpan = BuffersExtensions.ToArray(in sequence); } ReadOnlySpan readOnlySpan2 = readOnlySpan; if (_stringHasEscaping) { int idx = readOnlySpan2.IndexOf(92); readOnlySpan2 = JsonReaderHelper.GetUnescapedSpan(readOnlySpan2, idx); } return readOnlySpan2; } public Utf8JsonReader(ReadOnlySequence jsonData, bool isFinalBlock, JsonReaderState state) { ReadOnlyMemory memory = jsonData.First; _buffer = memory.Span; _isFinalBlock = isFinalBlock; _isInputSequence = true; _lineNumber = state._lineNumber; _bytePositionInLine = state._bytePositionInLine; _inObject = state._inObject; _isNotPrimitive = state._isNotPrimitive; _numberFormat = state._numberFormat; _stringHasEscaping = state._stringHasEscaping; _trailingCommaBeforeComment = state._trailingCommaBeforeComment; _tokenType = state._tokenType; _previousTokenType = state._previousTokenType; _readerOptions = state._readerOptions; if (_readerOptions.MaxDepth == 0) { _readerOptions.MaxDepth = 64; } _bitStack = state._bitStack; _consumed = 0; TokenStartIndex = 0L; _totalConsumed = 0L; ValueSpan = ReadOnlySpan.Empty; _sequence = jsonData; HasValueSequence = false; ValueSequence = ReadOnlySequence.Empty; if (jsonData.IsSingleSegment) { _nextPosition = default(SequencePosition); _currentPosition = jsonData.Start; _isLastSegment = isFinalBlock; _isMultiSegment = false; return; } _currentPosition = jsonData.Start; _nextPosition = _currentPosition; bool flag = _buffer.Length == 0; if (flag) { SequencePosition nextPosition = _nextPosition; ReadOnlyMemory memory2; while (jsonData.TryGet(ref _nextPosition, out memory2)) { _currentPosition = nextPosition; if (memory2.Length != 0) { _buffer = memory2.Span; break; } nextPosition = _nextPosition; } } _isLastSegment = !jsonData.TryGet(ref _nextPosition, out memory, !flag) && isFinalBlock; _isMultiSegment = true; } public Utf8JsonReader(ReadOnlySequence jsonData, JsonReaderOptions options = default(JsonReaderOptions)) : this(jsonData, isFinalBlock: true, new JsonReaderState(options)) { } private bool ReadMultiSegment() { bool flag = false; HasValueSequence = false; ValueSpan = default(ReadOnlySpan); ValueSequence = default(ReadOnlySequence); if (HasMoreDataMultiSegment()) { byte b = _buffer[_consumed]; if (b <= 32) { SkipWhiteSpaceMultiSegment(); if (!HasMoreDataMultiSegment()) { goto IL_016c; } b = _buffer[_consumed]; } TokenStartIndex = BytesConsumed; if (_tokenType != 0) { if (b == 47) { flag = ConsumeNextTokenOrRollbackMultiSegment(b); } else if (_tokenType == JsonTokenType.StartObject) { if (b == 125) { EndObject(); goto IL_016a; } if (b != 34) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); } long totalConsumed = _totalConsumed; int consumed = _consumed; long bytePositionInLine = _bytePositionInLine; long lineNumber = _lineNumber; SequencePosition currentPosition = _currentPosition; flag = ConsumePropertyNameMultiSegment(); if (!flag) { _consumed = consumed; _tokenType = JsonTokenType.StartObject; _bytePositionInLine = bytePositionInLine; _lineNumber = lineNumber; _totalConsumed = totalConsumed; _currentPosition = currentPosition; } } else if (_tokenType != JsonTokenType.StartArray) { flag = ((_tokenType != JsonTokenType.PropertyName) ? ConsumeNextTokenOrRollbackMultiSegment(b) : ConsumeValueMultiSegment(b)); } else { if (b == 93) { EndArray(); goto IL_016a; } flag = ConsumeValueMultiSegment(b); } } else { flag = ReadFirstTokenMultiSegment(b); } } goto IL_016c; IL_016a: flag = true; goto IL_016c; IL_016c: return flag; } private bool ValidateStateAtEndOfData() { if (_bitStack.CurrentDepth != 0) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ZeroDepthAtEnd, 0); } if (_readerOptions.CommentHandling == JsonCommentHandling.Allow && _tokenType == JsonTokenType.Comment) { return false; } if (_tokenType != JsonTokenType.EndArray && _tokenType != JsonTokenType.EndObject) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidEndOfJsonNonPrimitive, 0); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool HasMoreDataMultiSegment() { if (_consumed >= (uint)_buffer.Length) { if (_isNotPrimitive && IsLastSpan && !ValidateStateAtEndOfData()) { return false; } if (!GetNextSpan()) { if (_isNotPrimitive && IsLastSpan) { ValidateStateAtEndOfData(); } return false; } } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool HasMoreDataMultiSegment(ExceptionResource resource) { if (_consumed >= (uint)_buffer.Length) { if (IsLastSpan) { ThrowHelper.ThrowJsonReaderException(ref this, resource, 0); } if (!GetNextSpan()) { if (IsLastSpan) { ThrowHelper.ThrowJsonReaderException(ref this, resource, 0); } return false; } } return true; } private bool GetNextSpan() { ReadOnlyMemory memory = default(ReadOnlyMemory); while (true) { SequencePosition currentPosition = _currentPosition; _currentPosition = _nextPosition; if (!_sequence.TryGet(ref _nextPosition, out memory)) { _currentPosition = currentPosition; _isLastSegment = true; return false; } if (memory.Length != 0) { break; } _currentPosition = currentPosition; } if (_isFinalBlock) { _isLastSegment = !_sequence.TryGet(ref _nextPosition, out var _, advance: false); } _buffer = memory.Span; _totalConsumed += _consumed; _consumed = 0; return true; } private bool ReadFirstTokenMultiSegment(byte first) { switch (first) { case 123: _bitStack.SetFirstBit(); _tokenType = JsonTokenType.StartObject; ValueSpan = _buffer.Slice(_consumed, 1); _consumed++; _bytePositionInLine++; _inObject = true; _isNotPrimitive = true; break; case 91: _bitStack.ResetFirstBit(); _tokenType = JsonTokenType.StartArray; ValueSpan = _buffer.Slice(_consumed, 1); _consumed++; _bytePositionInLine++; _isNotPrimitive = true; break; default: if (JsonHelpers.IsDigit(first) || first == 45) { if (!TryGetNumberMultiSegment(_buffer.Slice(_consumed), out var consumed)) { return false; } _tokenType = JsonTokenType.Number; _consumed += consumed; return true; } if (!ConsumeValueMultiSegment(first)) { return false; } if (_tokenType == JsonTokenType.StartObject || _tokenType == JsonTokenType.StartArray) { _isNotPrimitive = true; } break; } return true; } private void SkipWhiteSpaceMultiSegment() { do { SkipWhiteSpace(); } while (_consumed >= _buffer.Length && GetNextSpan()); } private bool ConsumeValueMultiSegment(byte marker) { while (true) { _trailingCommaBeforeComment = false; switch (marker) { case 34: return ConsumeStringMultiSegment(); case 123: StartObject(); break; case 91: StartArray(); break; default: if (JsonHelpers.IsDigit(marker) || marker == 45) { return ConsumeNumberMultiSegment(); } switch (marker) { case 102: return ConsumeLiteralMultiSegment(JsonConstants.FalseValue, JsonTokenType.False); case 116: return ConsumeLiteralMultiSegment(JsonConstants.TrueValue, JsonTokenType.True); case 110: return ConsumeLiteralMultiSegment(JsonConstants.NullValue, JsonTokenType.Null); } switch (_readerOptions.CommentHandling) { case JsonCommentHandling.Allow: if (marker == 47) { SequencePosition currentPosition2 = _currentPosition; if (!SkipOrConsumeCommentMultiSegmentWithRollback()) { _currentPosition = currentPosition2; return false; } return true; } break; default: { if (marker != 47) { break; } SequencePosition currentPosition = _currentPosition; if (SkipCommentMultiSegment(out var _)) { if (_consumed >= (uint)_buffer.Length) { if (_isNotPrimitive && IsLastSpan && _tokenType != JsonTokenType.EndArray && _tokenType != JsonTokenType.EndObject) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidEndOfJsonNonPrimitive, 0); } if (!GetNextSpan()) { if (_isNotPrimitive && IsLastSpan && _tokenType != JsonTokenType.EndArray && _tokenType != JsonTokenType.EndObject) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidEndOfJsonNonPrimitive, 0); } _currentPosition = currentPosition; return false; } } marker = _buffer[_consumed]; if (marker <= 32) { SkipWhiteSpaceMultiSegment(); if (!HasMoreDataMultiSegment()) { _currentPosition = currentPosition; return false; } marker = _buffer[_consumed]; } goto IL_01a8; } _currentPosition = currentPosition; return false; } case JsonCommentHandling.Disallow: break; } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfValueNotFound, marker); break; } break; IL_01a8: TokenStartIndex = BytesConsumed; } return true; } private bool ConsumeLiteralMultiSegment(ReadOnlySpan literal, JsonTokenType tokenType) { ReadOnlySpan span = _buffer.Slice(_consumed); int consumed = literal.Length; if (!span.StartsWith(literal)) { int consumed2 = _consumed; if (!CheckLiteralMultiSegment(span, literal, out consumed)) { _consumed = consumed2; return false; } } else { ValueSpan = span.Slice(0, literal.Length); HasValueSequence = false; } _tokenType = tokenType; _consumed += consumed; _bytePositionInLine += consumed; return true; } private bool CheckLiteralMultiSegment(ReadOnlySpan span, ReadOnlySpan literal, out int consumed) { Span destination = stackalloc byte[literal.Length]; int num = 0; long totalConsumed = _totalConsumed; SequencePosition currentPosition = _currentPosition; if (span.Length >= literal.Length || IsLastSpan) { _bytePositionInLine += FindMismatch(span, literal); int num2 = Math.Min(span.Length, (int)_bytePositionInLine + 1); span.Slice(0, num2).CopyTo(destination); num += num2; } else if (!literal.StartsWith(span)) { _bytePositionInLine += FindMismatch(span, literal); int num3 = Math.Min(span.Length, (int)_bytePositionInLine + 1); span.Slice(0, num3).CopyTo(destination); num += num3; } else { ReadOnlySpan readOnlySpan = literal.Slice(span.Length); SequencePosition currentPosition2 = _currentPosition; int consumed2 = _consumed; int num4 = literal.Length - readOnlySpan.Length; while (true) { _totalConsumed += num4; _bytePositionInLine += num4; if (!GetNextSpan()) { _totalConsumed = totalConsumed; consumed = 0; _currentPosition = currentPosition; if (IsLastSpan) { break; } return false; } int num5 = Math.Min(span.Length, destination.Length - num); span.Slice(0, num5).CopyTo(destination.Slice(num)); num += num5; span = _buffer; if (span.StartsWith(readOnlySpan)) { HasValueSequence = true; SequencePosition start = new SequencePosition(currentPosition2.GetObject(), currentPosition2.GetInteger() + consumed2); SequencePosition end = new SequencePosition(_currentPosition.GetObject(), _currentPosition.GetInteger() + readOnlySpan.Length); ValueSequence = _sequence.Slice(start, end); consumed = readOnlySpan.Length; return true; } if (!readOnlySpan.StartsWith(span)) { _bytePositionInLine += FindMismatch(span, readOnlySpan); num5 = Math.Min(span.Length, (int)_bytePositionInLine + 1); span.Slice(0, num5).CopyTo(destination.Slice(num)); num += num5; break; } readOnlySpan = readOnlySpan.Slice(span.Length); num4 = span.Length; } } _totalConsumed = totalConsumed; consumed = 0; _currentPosition = currentPosition; throw GetInvalidLiteralMultiSegment(destination.Slice(0, num).ToArray()); } private int FindMismatch(ReadOnlySpan span, ReadOnlySpan literal) { int num = 0; int num2 = Math.Min(span.Length, literal.Length); int i; for (i = 0; i < num2 && span[i] == literal[i]; i++) { } return i; } private JsonException GetInvalidLiteralMultiSegment(ReadOnlySpan span) { return ThrowHelper.GetJsonReaderException(ref this, span[0] switch { 116 => ExceptionResource.ExpectedTrue, 102 => ExceptionResource.ExpectedFalse, _ => ExceptionResource.ExpectedNull, }, 0, span); } private bool ConsumeNumberMultiSegment() { if (!TryGetNumberMultiSegment(_buffer.Slice(_consumed), out var consumed)) { return false; } _tokenType = JsonTokenType.Number; _consumed += consumed; if (_consumed >= (uint)_buffer.Length && _isNotPrimitive) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndOfDigitNotFound, _buffer[_consumed - 1]); } return true; } private bool ConsumePropertyNameMultiSegment() { _trailingCommaBeforeComment = false; if (!ConsumeStringMultiSegment()) { return false; } if (!HasMoreDataMultiSegment(ExceptionResource.ExpectedValueAfterPropertyNameNotFound)) { return false; } byte b = _buffer[_consumed]; if (b <= 32) { SkipWhiteSpaceMultiSegment(); if (!HasMoreDataMultiSegment(ExceptionResource.ExpectedValueAfterPropertyNameNotFound)) { return false; } b = _buffer[_consumed]; } if (b != 58) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedSeparatorAfterPropertyNameNotFound, b); } _consumed++; _bytePositionInLine++; _tokenType = JsonTokenType.PropertyName; return true; } private bool ConsumeStringMultiSegment() { ReadOnlySpan readOnlySpan = _buffer.Slice(_consumed + 1); int num = readOnlySpan.IndexOfQuoteOrAnyControlOrBackSlash(); if (num >= 0) { byte b = readOnlySpan[num]; if (b == 34) { _bytePositionInLine += num + 2; ValueSpan = readOnlySpan.Slice(0, num); HasValueSequence = false; _stringHasEscaping = false; _tokenType = JsonTokenType.String; _consumed += num + 2; return true; } return ConsumeStringAndValidateMultiSegment(readOnlySpan, num); } if (IsLastSpan) { _bytePositionInLine += readOnlySpan.Length + 1; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound, 0); } return ConsumeStringNextSegment(); } private bool ConsumeStringNextSegment() { PartialStateForRollback state = CaptureState(); HasValueSequence = true; int num = _buffer.Length - _consumed; ReadOnlySpan buffer; int num2; while (true) { if (!GetNextSpan()) { if (IsLastSpan) { _bytePositionInLine += num; RollBackState(in state, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound, 0); } RollBackState(in state); return false; } buffer = _buffer; num2 = buffer.IndexOfQuoteOrAnyControlOrBackSlash(); if (num2 >= 0) { break; } _totalConsumed += buffer.Length; _bytePositionInLine += buffer.Length; } byte b = buffer[num2]; SequencePosition end; if (b == 34) { end = new SequencePosition(_currentPosition.GetObject(), _currentPosition.GetInteger() + num2); _bytePositionInLine += num + num2 + 1; _totalConsumed += num; _consumed = num2 + 1; _stringHasEscaping = false; } else { _bytePositionInLine += num + num2; _stringHasEscaping = true; bool flag = false; while (true) { if (num2 < buffer.Length) { byte b2 = buffer[num2]; if (b2 == 34) { if (!flag) { break; } flag = false; } else if (b2 == 92) { flag = !flag; } else if (flag) { int num3 = JsonConstants.EscapableChars.IndexOf(b2); if (num3 == -1) { RollBackState(in state, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterAfterEscapeWithinString, b2); } if (b2 == 117) { _bytePositionInLine++; int num4 = 0; int num5 = num2 + 1; while (true) { if (num5 < buffer.Length) { byte nextByte = buffer[num5]; if (!JsonReaderHelper.IsHexDigit(nextByte)) { RollBackState(in state, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidHexCharacterWithinString, nextByte); } num4++; _bytePositionInLine++; if (num4 >= 4) { break; } num5++; continue; } if (!GetNextSpan()) { if (IsLastSpan) { RollBackState(in state, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound, 0); } RollBackState(in state); return false; } _totalConsumed += buffer.Length; buffer = _buffer; num5 = 0; } flag = false; num2 = num5 + 1; continue; } flag = false; } else if (b2 < 32) { RollBackState(in state, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterWithinString, b2); } _bytePositionInLine++; num2++; continue; } if (!GetNextSpan()) { if (IsLastSpan) { RollBackState(in state, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound, 0); } RollBackState(in state); return false; } _totalConsumed += buffer.Length; buffer = _buffer; num2 = 0; } _bytePositionInLine++; _consumed = num2 + 1; _totalConsumed += num; end = new SequencePosition(_currentPosition.GetObject(), _currentPosition.GetInteger() + num2); } SequencePosition startPosition = state.GetStartPosition(1); ValueSequence = _sequence.Slice(startPosition, end); _tokenType = JsonTokenType.String; return true; } private bool ConsumeStringAndValidateMultiSegment(ReadOnlySpan data, int idx) { PartialStateForRollback state = CaptureState(); HasValueSequence = false; int num = _buffer.Length - _consumed; _bytePositionInLine += idx + 1; bool flag = false; while (true) { if (idx < data.Length) { byte b = data[idx]; switch (b) { case 34: if (flag) { flag = false; goto IL_01b7; } if (HasValueSequence) { _bytePositionInLine++; _consumed = idx + 1; _totalConsumed += num; SequencePosition end = new SequencePosition(_currentPosition.GetObject(), _currentPosition.GetInteger() + idx); SequencePosition startPosition = state.GetStartPosition(1); ValueSequence = _sequence.Slice(startPosition, end); } else { _bytePositionInLine++; _consumed += idx + 2; ValueSpan = data.Slice(0, idx); } _stringHasEscaping = true; _tokenType = JsonTokenType.String; return true; case 92: flag = !flag; goto IL_01b7; default: { if (flag) { int num2 = JsonConstants.EscapableChars.IndexOf(b); if (num2 == -1) { RollBackState(in state, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterAfterEscapeWithinString, b); } if (b == 117) { _bytePositionInLine++; int num3 = 0; int num4 = idx + 1; while (true) { if (num4 < data.Length) { byte nextByte = data[num4]; if (!JsonReaderHelper.IsHexDigit(nextByte)) { RollBackState(in state, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidHexCharacterWithinString, nextByte); } num3++; _bytePositionInLine++; if (num3 >= 4) { break; } num4++; continue; } if (!GetNextSpan()) { if (IsLastSpan) { RollBackState(in state, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound, 0); } RollBackState(in state); return false; } if (HasValueSequence) { _totalConsumed += data.Length; } data = _buffer; num4 = 0; HasValueSequence = true; } flag = false; idx = num4 + 1; break; } flag = false; } else if (b < 32) { RollBackState(in state, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterWithinString, b); } goto IL_01b7; } IL_01b7: _bytePositionInLine++; idx++; break; } } else { if (!GetNextSpan()) { break; } if (HasValueSequence) { _totalConsumed += data.Length; } data = _buffer; idx = 0; HasValueSequence = true; } } if (IsLastSpan) { RollBackState(in state, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound, 0); } RollBackState(in state); return false; } private void RollBackState(in PartialStateForRollback state, bool isError = false) { _totalConsumed = state._prevTotalConsumed; if (!isError) { _bytePositionInLine = state._prevBytePositionInLine; } _consumed = state._prevConsumed; _currentPosition = state._prevCurrentPosition; } private bool TryGetNumberMultiSegment(ReadOnlySpan data, out int consumed) { _numberFormat = '\0'; PartialStateForRollback rollBackState = CaptureState(); consumed = 0; int i = 0; ConsumeNumberResult consumeNumberResult = ConsumeNegativeSignMultiSegment(ref data, ref i, in rollBackState); if (consumeNumberResult == ConsumeNumberResult.NeedMoreData) { RollBackState(in rollBackState); return false; } byte b = data[i]; if (b == 48) { ConsumeNumberResult consumeNumberResult2 = ConsumeZeroMultiSegment(ref data, ref i, in rollBackState); if (consumeNumberResult2 == ConsumeNumberResult.NeedMoreData) { RollBackState(in rollBackState); return false; } if (consumeNumberResult2 != 0) { b = data[i]; goto IL_00c6; } } else { ConsumeNumberResult consumeNumberResult3 = ConsumeIntegerDigitsMultiSegment(ref data, ref i); if (consumeNumberResult3 == ConsumeNumberResult.NeedMoreData) { RollBackState(in rollBackState); return false; } if (consumeNumberResult3 != 0) { b = data[i]; if (b != 46 && b != 69 && b != 101) { RollBackState(in rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndOfDigitNotFound, b); } goto IL_00c6; } } goto IL_01c0; IL_00c6: if (b == 46) { i++; _bytePositionInLine++; ConsumeNumberResult consumeNumberResult4 = ConsumeDecimalDigitsMultiSegment(ref data, ref i, in rollBackState); if (consumeNumberResult4 == ConsumeNumberResult.NeedMoreData) { RollBackState(in rollBackState); return false; } if (consumeNumberResult4 == ConsumeNumberResult.Success) { goto IL_01c0; } b = data[i]; if (b != 69 && b != 101) { RollBackState(in rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedNextDigitEValueNotFound, b); } } i++; _numberFormat = 'e'; _bytePositionInLine++; consumeNumberResult = ConsumeSignMultiSegment(ref data, ref i, in rollBackState); if (consumeNumberResult == ConsumeNumberResult.NeedMoreData) { RollBackState(in rollBackState); return false; } i++; _bytePositionInLine++; switch (ConsumeIntegerDigitsMultiSegment(ref data, ref i)) { case ConsumeNumberResult.NeedMoreData: RollBackState(in rollBackState); return false; default: RollBackState(in rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndOfDigitNotFound, data[i]); break; case ConsumeNumberResult.Success: break; } goto IL_01c0; IL_01c0: if (HasValueSequence) { SequencePosition startPosition = rollBackState.GetStartPosition(); SequencePosition end = new SequencePosition(_currentPosition.GetObject(), _currentPosition.GetInteger() + i); ValueSequence = _sequence.Slice(startPosition, end); consumed = i; } else { ValueSpan = data.Slice(0, i); consumed = i; } return true; } private ConsumeNumberResult ConsumeNegativeSignMultiSegment(ref ReadOnlySpan data, ref int i, in PartialStateForRollback rollBackState) { byte b = data[i]; if (b == 45) { i++; _bytePositionInLine++; if (i >= data.Length) { if (IsLastSpan) { RollBackState(in rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); } if (!GetNextSpan()) { if (IsLastSpan) { RollBackState(in rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); } return ConsumeNumberResult.NeedMoreData; } _totalConsumed += i; HasValueSequence = true; i = 0; data = _buffer; } b = data[i]; if (!JsonHelpers.IsDigit(b)) { RollBackState(in rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundAfterSign, b); } } return ConsumeNumberResult.OperationIncomplete; } private ConsumeNumberResult ConsumeZeroMultiSegment(ref ReadOnlySpan data, ref int i, in PartialStateForRollback rollBackState) { i++; _bytePositionInLine++; byte value; if (i < data.Length) { value = data[i]; if (JsonConstants.Delimiters.IndexOf(value) >= 0) { return ConsumeNumberResult.Success; } } else { if (IsLastSpan) { return ConsumeNumberResult.Success; } if (!GetNextSpan()) { if (IsLastSpan) { return ConsumeNumberResult.Success; } return ConsumeNumberResult.NeedMoreData; } _totalConsumed += i; HasValueSequence = true; i = 0; data = _buffer; value = data[i]; if (JsonConstants.Delimiters.IndexOf(value) >= 0) { return ConsumeNumberResult.Success; } } value = data[i]; if (value != 46 && value != 69 && value != 101) { RollBackState(in rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, JsonHelpers.IsInRangeInclusive(value, 48, 57) ? ExceptionResource.InvalidLeadingZeroInNumber : ExceptionResource.ExpectedEndOfDigitNotFound, value); } return ConsumeNumberResult.OperationIncomplete; } private ConsumeNumberResult ConsumeIntegerDigitsMultiSegment(ref ReadOnlySpan data, ref int i) { byte value = 0; int num = 0; while (i < data.Length) { value = data[i]; if (!JsonHelpers.IsDigit(value)) { break; } num++; i++; } if (i >= data.Length) { if (IsLastSpan) { _bytePositionInLine += num; return ConsumeNumberResult.Success; } while (true) { if (!GetNextSpan()) { if (IsLastSpan) { _bytePositionInLine += num; return ConsumeNumberResult.Success; } return ConsumeNumberResult.NeedMoreData; } _totalConsumed += i; _bytePositionInLine += num; num = 0; HasValueSequence = true; i = 0; data = _buffer; while (i < data.Length) { value = data[i]; if (!JsonHelpers.IsDigit(value)) { break; } i++; } _bytePositionInLine += i; if (i < data.Length) { break; } if (IsLastSpan) { return ConsumeNumberResult.Success; } } } else { _bytePositionInLine += num; } if (JsonConstants.Delimiters.IndexOf(value) >= 0) { return ConsumeNumberResult.Success; } return ConsumeNumberResult.OperationIncomplete; } private ConsumeNumberResult ConsumeDecimalDigitsMultiSegment(ref ReadOnlySpan data, ref int i, in PartialStateForRollback rollBackState) { if (i >= data.Length) { if (IsLastSpan) { RollBackState(in rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); } if (!GetNextSpan()) { if (IsLastSpan) { RollBackState(in rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); } return ConsumeNumberResult.NeedMoreData; } _totalConsumed += i; HasValueSequence = true; i = 0; data = _buffer; } byte b = data[i]; if (!JsonHelpers.IsDigit(b)) { RollBackState(in rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundAfterDecimal, b); } i++; _bytePositionInLine++; return ConsumeIntegerDigitsMultiSegment(ref data, ref i); } private ConsumeNumberResult ConsumeSignMultiSegment(ref ReadOnlySpan data, ref int i, in PartialStateForRollback rollBackState) { if (i >= data.Length) { if (IsLastSpan) { RollBackState(in rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); } if (!GetNextSpan()) { if (IsLastSpan) { RollBackState(in rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); } return ConsumeNumberResult.NeedMoreData; } _totalConsumed += i; HasValueSequence = true; i = 0; data = _buffer; } byte b = data[i]; if (b == 43 || b == 45) { i++; _bytePositionInLine++; if (i >= data.Length) { if (IsLastSpan) { RollBackState(in rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); } if (!GetNextSpan()) { if (IsLastSpan) { RollBackState(in rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundEndOfData, 0); } return ConsumeNumberResult.NeedMoreData; } _totalConsumed += i; HasValueSequence = true; i = 0; data = _buffer; } b = data[i]; } if (!JsonHelpers.IsDigit(b)) { RollBackState(in rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.RequiredDigitNotFoundAfterSign, b); } return ConsumeNumberResult.OperationIncomplete; } private bool ConsumeNextTokenOrRollbackMultiSegment(byte marker) { long totalConsumed = _totalConsumed; int consumed = _consumed; long bytePositionInLine = _bytePositionInLine; long lineNumber = _lineNumber; JsonTokenType tokenType = _tokenType; SequencePosition currentPosition = _currentPosition; bool trailingCommaBeforeComment = _trailingCommaBeforeComment; switch (ConsumeNextTokenMultiSegment(marker)) { case ConsumeTokenResult.Success: return true; case ConsumeTokenResult.NotEnoughDataRollBackState: _consumed = consumed; _tokenType = tokenType; _bytePositionInLine = bytePositionInLine; _lineNumber = lineNumber; _totalConsumed = totalConsumed; _currentPosition = currentPosition; _trailingCommaBeforeComment = trailingCommaBeforeComment; break; } return false; } private ConsumeTokenResult ConsumeNextTokenMultiSegment(byte marker) { if (_readerOptions.CommentHandling != 0) { if (_readerOptions.CommentHandling != JsonCommentHandling.Allow) { return ConsumeNextTokenUntilAfterAllCommentsAreSkippedMultiSegment(marker); } if (marker == 47) { if (!SkipOrConsumeCommentMultiSegmentWithRollback()) { return ConsumeTokenResult.NotEnoughDataRollBackState; } return ConsumeTokenResult.Success; } if (_tokenType == JsonTokenType.Comment) { return ConsumeNextTokenFromLastNonCommentTokenMultiSegment(); } } if (_bitStack.CurrentDepth == 0) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndAfterSingleJson, marker); } switch (marker) { case 44: { _consumed++; _bytePositionInLine++; if (_consumed >= (uint)_buffer.Length) { if (IsLastSpan) { _consumed--; _bytePositionInLine--; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); } if (!GetNextSpan()) { if (IsLastSpan) { _consumed--; _bytePositionInLine--; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); } return ConsumeTokenResult.NotEnoughDataRollBackState; } } byte b = _buffer[_consumed]; if (b <= 32) { SkipWhiteSpaceMultiSegment(); if (!HasMoreDataMultiSegment(ExceptionResource.ExpectedStartOfPropertyOrValueNotFound)) { return ConsumeTokenResult.NotEnoughDataRollBackState; } b = _buffer[_consumed]; } TokenStartIndex = BytesConsumed; if (_readerOptions.CommentHandling == JsonCommentHandling.Allow && b == 47) { _trailingCommaBeforeComment = true; if (!SkipOrConsumeCommentMultiSegmentWithRollback()) { return ConsumeTokenResult.NotEnoughDataRollBackState; } return ConsumeTokenResult.Success; } if (_inObject) { if (b != 34) { if (b == 125) { if (_readerOptions.AllowTrailingCommas) { EndObject(); return ConsumeTokenResult.Success; } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd, 0); } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); } if (!ConsumePropertyNameMultiSegment()) { return ConsumeTokenResult.NotEnoughDataRollBackState; } return ConsumeTokenResult.Success; } if (b == 93) { if (_readerOptions.AllowTrailingCommas) { EndArray(); return ConsumeTokenResult.Success; } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd, 0); } if (!ConsumeValueMultiSegment(b)) { return ConsumeTokenResult.NotEnoughDataRollBackState; } return ConsumeTokenResult.Success; } case 125: EndObject(); break; case 93: EndArray(); break; default: ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.FoundInvalidCharacter, marker); break; } return ConsumeTokenResult.Success; } private ConsumeTokenResult ConsumeNextTokenFromLastNonCommentTokenMultiSegment() { if (JsonReaderHelper.IsTokenTypePrimitive(_previousTokenType)) { _tokenType = (_inObject ? JsonTokenType.StartObject : JsonTokenType.StartArray); } else { _tokenType = _previousTokenType; } if (HasMoreDataMultiSegment()) { byte b = _buffer[_consumed]; if (b <= 32) { SkipWhiteSpaceMultiSegment(); if (!HasMoreDataMultiSegment()) { goto IL_0393; } b = _buffer[_consumed]; } if (_bitStack.CurrentDepth == 0 && _tokenType != 0) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndAfterSingleJson, b); } TokenStartIndex = BytesConsumed; if (b != 44) { if (b == 125) { EndObject(); } else { if (b != 93) { if (_tokenType == JsonTokenType.None) { if (ReadFirstTokenMultiSegment(b)) { goto IL_0391; } } else if (_tokenType == JsonTokenType.StartObject) { if (b != 34) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); } long totalConsumed = _totalConsumed; int consumed = _consumed; long bytePositionInLine = _bytePositionInLine; long lineNumber = _lineNumber; if (ConsumePropertyNameMultiSegment()) { goto IL_0391; } _consumed = consumed; _tokenType = JsonTokenType.StartObject; _bytePositionInLine = bytePositionInLine; _lineNumber = lineNumber; _totalConsumed = totalConsumed; } else if (_tokenType == JsonTokenType.StartArray) { if (ConsumeValueMultiSegment(b)) { goto IL_0391; } } else if (_tokenType == JsonTokenType.PropertyName) { if (ConsumeValueMultiSegment(b)) { goto IL_0391; } } else if (_inObject) { if (b != 34) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); } if (ConsumePropertyNameMultiSegment()) { goto IL_0391; } } else if (ConsumeValueMultiSegment(b)) { goto IL_0391; } goto IL_0393; } EndArray(); } goto IL_0391; } if ((int)_previousTokenType <= 1 || _previousTokenType == JsonTokenType.StartArray || _trailingCommaBeforeComment) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueAfterComment, b); } _consumed++; _bytePositionInLine++; if (_consumed >= (uint)_buffer.Length) { if (IsLastSpan) { _consumed--; _bytePositionInLine--; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); } if (!GetNextSpan()) { if (IsLastSpan) { _consumed--; _bytePositionInLine--; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); } goto IL_0393; } } b = _buffer[_consumed]; if (b <= 32) { SkipWhiteSpaceMultiSegment(); if (!HasMoreDataMultiSegment(ExceptionResource.ExpectedStartOfPropertyOrValueNotFound)) { goto IL_0393; } b = _buffer[_consumed]; } TokenStartIndex = BytesConsumed; if (b == 47) { _trailingCommaBeforeComment = true; if (SkipOrConsumeCommentMultiSegmentWithRollback()) { goto IL_0391; } } else if (_inObject) { if (b != 34) { if (b == 125) { if (_readerOptions.AllowTrailingCommas) { EndObject(); goto IL_0391; } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd, 0); } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, b); } if (ConsumePropertyNameMultiSegment()) { goto IL_0391; } } else { if (b == 93) { if (_readerOptions.AllowTrailingCommas) { EndArray(); goto IL_0391; } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd, 0); } if (ConsumeValueMultiSegment(b)) { goto IL_0391; } } } goto IL_0393; IL_0393: return ConsumeTokenResult.NotEnoughDataRollBackState; IL_0391: return ConsumeTokenResult.Success; } private bool SkipAllCommentsMultiSegment(ref byte marker) { while (true) { if (marker == 47) { if (!SkipOrConsumeCommentMultiSegmentWithRollback() || !HasMoreDataMultiSegment()) { break; } marker = _buffer[_consumed]; if (marker <= 32) { SkipWhiteSpaceMultiSegment(); if (!HasMoreDataMultiSegment()) { break; } marker = _buffer[_consumed]; } continue; } return true; } return false; } private bool SkipAllCommentsMultiSegment(ref byte marker, ExceptionResource resource) { while (true) { if (marker == 47) { if (!SkipOrConsumeCommentMultiSegmentWithRollback() || !HasMoreDataMultiSegment(resource)) { break; } marker = _buffer[_consumed]; if (marker <= 32) { SkipWhiteSpaceMultiSegment(); if (!HasMoreDataMultiSegment(resource)) { break; } marker = _buffer[_consumed]; } continue; } return true; } return false; } private ConsumeTokenResult ConsumeNextTokenUntilAfterAllCommentsAreSkippedMultiSegment(byte marker) { if (SkipAllCommentsMultiSegment(ref marker)) { TokenStartIndex = BytesConsumed; if (_tokenType == JsonTokenType.StartObject) { if (marker == 125) { EndObject(); } else { if (marker != 34) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, marker); } long totalConsumed = _totalConsumed; int consumed = _consumed; long bytePositionInLine = _bytePositionInLine; long lineNumber = _lineNumber; SequencePosition currentPosition = _currentPosition; if (!ConsumePropertyNameMultiSegment()) { _consumed = consumed; _tokenType = JsonTokenType.StartObject; _bytePositionInLine = bytePositionInLine; _lineNumber = lineNumber; _totalConsumed = totalConsumed; _currentPosition = currentPosition; goto IL_02e7; } } } else if (_tokenType == JsonTokenType.StartArray) { if (marker == 93) { EndArray(); } else if (!ConsumeValueMultiSegment(marker)) { goto IL_02e7; } } else if (_tokenType == JsonTokenType.PropertyName) { if (!ConsumeValueMultiSegment(marker)) { goto IL_02e7; } } else if (_bitStack.CurrentDepth == 0) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndAfterSingleJson, marker); } else { switch (marker) { case 44: _consumed++; _bytePositionInLine++; if (_consumed >= (uint)_buffer.Length) { if (IsLastSpan) { _consumed--; _bytePositionInLine--; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); } if (!GetNextSpan()) { if (IsLastSpan) { _consumed--; _bytePositionInLine--; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound, 0); } return ConsumeTokenResult.NotEnoughDataRollBackState; } } marker = _buffer[_consumed]; if (marker <= 32) { SkipWhiteSpaceMultiSegment(); if (!HasMoreDataMultiSegment(ExceptionResource.ExpectedStartOfPropertyOrValueNotFound)) { return ConsumeTokenResult.NotEnoughDataRollBackState; } marker = _buffer[_consumed]; } if (SkipAllCommentsMultiSegment(ref marker, ExceptionResource.ExpectedStartOfPropertyOrValueNotFound)) { TokenStartIndex = BytesConsumed; if (_inObject) { if (marker != 34) { if (marker == 125) { if (_readerOptions.AllowTrailingCommas) { EndObject(); break; } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd, 0); } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, marker); } if (!ConsumePropertyNameMultiSegment()) { return ConsumeTokenResult.NotEnoughDataRollBackState; } return ConsumeTokenResult.Success; } if (marker == 93) { if (_readerOptions.AllowTrailingCommas) { EndArray(); break; } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd, 0); } if (!ConsumeValueMultiSegment(marker)) { return ConsumeTokenResult.NotEnoughDataRollBackState; } return ConsumeTokenResult.Success; } return ConsumeTokenResult.NotEnoughDataRollBackState; case 125: EndObject(); break; case 93: EndArray(); break; default: ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.FoundInvalidCharacter, marker); break; } } return ConsumeTokenResult.Success; } goto IL_02e7; IL_02e7: return ConsumeTokenResult.IncompleteNoRollBackNecessary; } private bool SkipOrConsumeCommentMultiSegmentWithRollback() { long bytesConsumed = BytesConsumed; SequencePosition start = new SequencePosition(_currentPosition.GetObject(), _currentPosition.GetInteger() + _consumed); int tailBytesToIgnore; bool flag = SkipCommentMultiSegment(out tailBytesToIgnore); if (flag) { if (_readerOptions.CommentHandling == JsonCommentHandling.Allow) { SequencePosition end = new SequencePosition(_currentPosition.GetObject(), _currentPosition.GetInteger() + _consumed); ReadOnlySequence readOnlySequence = _sequence.Slice(start, end); readOnlySequence = readOnlySequence.Slice(2L, readOnlySequence.Length - 2 - tailBytesToIgnore); HasValueSequence = !readOnlySequence.IsSingleSegment; if (HasValueSequence) { ValueSequence = readOnlySequence; } else { ValueSpan = readOnlySequence.First.Span; } if (_tokenType != JsonTokenType.Comment) { _previousTokenType = _tokenType; } _tokenType = JsonTokenType.Comment; } } else { _totalConsumed = bytesConsumed; _consumed = 0; } return flag; } private bool SkipCommentMultiSegment(out int tailBytesToIgnore) { _consumed++; _bytePositionInLine++; ReadOnlySpan localBuffer = _buffer.Slice(_consumed); if (localBuffer.Length == 0) { if (IsLastSpan) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfDataWhileReadingComment, 0); } if (!GetNextSpan()) { if (IsLastSpan) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfDataWhileReadingComment, 0); } tailBytesToIgnore = 0; return false; } localBuffer = _buffer; } byte b = localBuffer[0]; if (b != 47 && b != 42) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterAtStartOfComment, b); } bool flag = b == 42; _consumed++; _bytePositionInLine++; localBuffer = localBuffer.Slice(1); if (localBuffer.Length == 0) { if (IsLastSpan) { tailBytesToIgnore = 0; if (flag) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfDataWhileReadingComment, 0); } return true; } if (!GetNextSpan()) { tailBytesToIgnore = 0; if (IsLastSpan) { if (flag) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfDataWhileReadingComment, 0); } return true; } return false; } localBuffer = _buffer; } if (flag) { tailBytesToIgnore = 2; return SkipMultiLineCommentMultiSegment(localBuffer); } return SkipSingleLineCommentMultiSegment(localBuffer, out tailBytesToIgnore); } private bool SkipSingleLineCommentMultiSegment(ReadOnlySpan localBuffer, out int tailBytesToSkip) { bool flag = false; int dangerousLineSeparatorBytesConsumed = 0; tailBytesToSkip = 0; while (true) { if (flag) { if (localBuffer[0] == 10) { tailBytesToSkip++; _consumed++; } break; } int num = FindLineSeparatorMultiSegment(localBuffer, ref dangerousLineSeparatorBytesConsumed); if (num != -1) { tailBytesToSkip++; _consumed += num + 1; _bytePositionInLine += num + 1; if (localBuffer[num] == 10) { break; } if (num < localBuffer.Length - 1) { if (localBuffer[num + 1] == 10) { tailBytesToSkip++; _consumed++; _bytePositionInLine++; } break; } flag = true; } else { _consumed += localBuffer.Length; _bytePositionInLine += localBuffer.Length; } if (IsLastSpan) { if (flag) { break; } return true; } if (!GetNextSpan()) { if (IsLastSpan) { if (flag) { break; } return true; } return false; } localBuffer = _buffer; } _bytePositionInLine = 0L; _lineNumber++; return true; } private int FindLineSeparatorMultiSegment(ReadOnlySpan localBuffer, ref int dangerousLineSeparatorBytesConsumed) { if (dangerousLineSeparatorBytesConsumed != 0) { ThrowOnDangerousLineSeparatorMultiSegment(localBuffer, ref dangerousLineSeparatorBytesConsumed); if (dangerousLineSeparatorBytesConsumed != 0) { return -1; } } int num = 0; do { int num2 = localBuffer.IndexOfAny(10, 13, 226); dangerousLineSeparatorBytesConsumed = 0; if (num2 == -1) { return -1; } if (localBuffer[num2] != 226) { return num + num2; } int num3 = num2 + 1; localBuffer = localBuffer.Slice(num3); num += num3; dangerousLineSeparatorBytesConsumed++; ThrowOnDangerousLineSeparatorMultiSegment(localBuffer, ref dangerousLineSeparatorBytesConsumed); } while (dangerousLineSeparatorBytesConsumed == 0); return -1; } private void ThrowOnDangerousLineSeparatorMultiSegment(ReadOnlySpan localBuffer, ref int dangerousLineSeparatorBytesConsumed) { if (localBuffer.IsEmpty) { return; } if (dangerousLineSeparatorBytesConsumed == 1) { if (localBuffer[0] != 128) { dangerousLineSeparatorBytesConsumed = 0; return; } localBuffer = localBuffer.Slice(1); dangerousLineSeparatorBytesConsumed++; if (localBuffer.IsEmpty) { return; } } if (dangerousLineSeparatorBytesConsumed == 2) { byte b = localBuffer[0]; if (b == 168 || b == 169) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfLineSeparator, 0); } else { dangerousLineSeparatorBytesConsumed = 0; } } } private bool SkipMultiLineCommentMultiSegment(ReadOnlySpan localBuffer) { bool flag = false; bool flag2 = false; while (true) { if (flag) { if (localBuffer[0] == 47) { _consumed++; _bytePositionInLine++; return true; } flag = false; } if (flag2) { if (localBuffer[0] == 10) { _consumed++; localBuffer = localBuffer.Slice(1); } flag2 = false; } int num = localBuffer.IndexOfAny(42, 10, 13); if (num != -1) { int num2 = num + 1; byte b = localBuffer[num]; localBuffer = localBuffer.Slice(num2); _consumed += num2; switch (b) { case 42: flag = true; _bytePositionInLine += num2; break; case 10: _bytePositionInLine = 0L; _lineNumber++; break; default: _bytePositionInLine = 0L; _lineNumber++; flag2 = true; break; } } else { _consumed += localBuffer.Length; _bytePositionInLine += localBuffer.Length; localBuffer = ReadOnlySpan.Empty; } if (!localBuffer.IsEmpty) { continue; } if (IsLastSpan) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfDataWhileReadingComment, 0); } if (!GetNextSpan()) { if (!IsLastSpan) { break; } ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfDataWhileReadingComment, 0); } localBuffer = _buffer; } return false; } private PartialStateForRollback CaptureState() { return new PartialStateForRollback(_totalConsumed, _bytePositionInLine, _consumed, _currentPosition); } public string? GetString() { if (TokenType == JsonTokenType.Null) { return null; } if (TokenType != JsonTokenType.String && TokenType != JsonTokenType.PropertyName) { throw ThrowHelper.GetInvalidOperationException_ExpectedString(TokenType); } ReadOnlySpan readOnlySpan; if (!HasValueSequence) { readOnlySpan = ValueSpan; } else { ReadOnlySequence sequence = ValueSequence; readOnlySpan = BuffersExtensions.ToArray(in sequence); } ReadOnlySpan readOnlySpan2 = readOnlySpan; if (_stringHasEscaping) { int idx = readOnlySpan2.IndexOf(92); return JsonReaderHelper.GetUnescapedString(readOnlySpan2, idx); } return JsonReaderHelper.TranscodeHelper(readOnlySpan2); } public string GetComment() { if (TokenType != JsonTokenType.Comment) { throw ThrowHelper.GetInvalidOperationException_ExpectedComment(TokenType); } ReadOnlySpan readOnlySpan; if (!HasValueSequence) { readOnlySpan = ValueSpan; } else { ReadOnlySequence sequence = ValueSequence; readOnlySpan = BuffersExtensions.ToArray(in sequence); } ReadOnlySpan utf8Unescaped = readOnlySpan; return JsonReaderHelper.TranscodeHelper(utf8Unescaped); } public bool GetBoolean() { ReadOnlySpan readOnlySpan; if (!HasValueSequence) { readOnlySpan = ValueSpan; } else { ReadOnlySequence sequence = ValueSequence; readOnlySpan = BuffersExtensions.ToArray(in sequence); } ReadOnlySpan readOnlySpan2 = readOnlySpan; if (TokenType == JsonTokenType.True) { return true; } if (TokenType == JsonTokenType.False) { return false; } throw ThrowHelper.GetInvalidOperationException_ExpectedBoolean(TokenType); } public byte[] GetBytesFromBase64() { if (!TryGetBytesFromBase64(out byte[] value)) { throw ThrowHelper.GetFormatException(DataType.Base64String); } return value; } public byte GetByte() { if (!TryGetByte(out var value)) { throw ThrowHelper.GetFormatException(NumericType.Byte); } return value; } internal byte GetByteWithQuotes() { ReadOnlySpan unescapedSpan = GetUnescapedSpan(); if (!TryGetByteCore(out var value, unescapedSpan)) { throw ThrowHelper.GetFormatException(NumericType.Byte); } return value; } [CLSCompliant(false)] public sbyte GetSByte() { if (!TryGetSByte(out var value)) { throw ThrowHelper.GetFormatException(NumericType.SByte); } return value; } internal sbyte GetSByteWithQuotes() { ReadOnlySpan unescapedSpan = GetUnescapedSpan(); if (!TryGetSByteCore(out var value, unescapedSpan)) { throw ThrowHelper.GetFormatException(NumericType.SByte); } return value; } public short GetInt16() { if (!TryGetInt16(out var value)) { throw ThrowHelper.GetFormatException(NumericType.Int16); } return value; } internal short GetInt16WithQuotes() { ReadOnlySpan unescapedSpan = GetUnescapedSpan(); if (!TryGetInt16Core(out var value, unescapedSpan)) { throw ThrowHelper.GetFormatException(NumericType.Int16); } return value; } public int GetInt32() { if (!TryGetInt32(out var value)) { throw ThrowHelper.GetFormatException(NumericType.Int32); } return value; } internal int GetInt32WithQuotes() { ReadOnlySpan unescapedSpan = GetUnescapedSpan(); if (!TryGetInt32Core(out var value, unescapedSpan)) { throw ThrowHelper.GetFormatException(NumericType.Int32); } return value; } public long GetInt64() { if (!TryGetInt64(out var value)) { throw ThrowHelper.GetFormatException(NumericType.Int64); } return value; } internal long GetInt64WithQuotes() { ReadOnlySpan unescapedSpan = GetUnescapedSpan(); if (!TryGetInt64Core(out var value, unescapedSpan)) { throw ThrowHelper.GetFormatException(NumericType.Int64); } return value; } [CLSCompliant(false)] public ushort GetUInt16() { if (!TryGetUInt16(out var value)) { throw ThrowHelper.GetFormatException(NumericType.UInt16); } return value; } internal ushort GetUInt16WithQuotes() { ReadOnlySpan unescapedSpan = GetUnescapedSpan(); if (!TryGetUInt16Core(out var value, unescapedSpan)) { throw ThrowHelper.GetFormatException(NumericType.UInt16); } return value; } [CLSCompliant(false)] public uint GetUInt32() { if (!TryGetUInt32(out var value)) { throw ThrowHelper.GetFormatException(NumericType.UInt32); } return value; } internal uint GetUInt32WithQuotes() { ReadOnlySpan unescapedSpan = GetUnescapedSpan(); if (!TryGetUInt32Core(out var value, unescapedSpan)) { throw ThrowHelper.GetFormatException(NumericType.UInt32); } return value; } [CLSCompliant(false)] public ulong GetUInt64() { if (!TryGetUInt64(out var value)) { throw ThrowHelper.GetFormatException(NumericType.UInt64); } return value; } internal ulong GetUInt64WithQuotes() { ReadOnlySpan unescapedSpan = GetUnescapedSpan(); if (!TryGetUInt64Core(out var value, unescapedSpan)) { throw ThrowHelper.GetFormatException(NumericType.UInt64); } return value; } public float GetSingle() { if (!TryGetSingle(out var value)) { throw ThrowHelper.GetFormatException(NumericType.Single); } return value; } internal float GetSingleWithQuotes() { ReadOnlySpan unescapedSpan = GetUnescapedSpan(); if (JsonReaderHelper.TryGetFloatingPointConstant(unescapedSpan, out float value)) { return value; } char floatingPointStandardParseFormat = JsonReaderHelper.GetFloatingPointStandardParseFormat(unescapedSpan); if (Utf8Parser.TryParse(unescapedSpan, out value, out int bytesConsumed, floatingPointStandardParseFormat) && unescapedSpan.Length == bytesConsumed && !float.IsNaN(value) && !float.IsPositiveInfinity(value) && !float.IsNegativeInfinity(value)) { return value; } throw ThrowHelper.GetFormatException(NumericType.Single); } internal float GetSingleFloatingPointConstant() { ReadOnlySpan unescapedSpan = GetUnescapedSpan(); if (JsonReaderHelper.TryGetFloatingPointConstant(unescapedSpan, out float value)) { return value; } throw ThrowHelper.GetFormatException(NumericType.Single); } public double GetDouble() { if (!TryGetDouble(out var value)) { throw ThrowHelper.GetFormatException(NumericType.Double); } return value; } internal double GetDoubleWithQuotes() { ReadOnlySpan unescapedSpan = GetUnescapedSpan(); if (JsonReaderHelper.TryGetFloatingPointConstant(unescapedSpan, out double value)) { return value; } char floatingPointStandardParseFormat = JsonReaderHelper.GetFloatingPointStandardParseFormat(unescapedSpan); if (Utf8Parser.TryParse(unescapedSpan, out value, out int bytesConsumed, floatingPointStandardParseFormat) && unescapedSpan.Length == bytesConsumed && !double.IsNaN(value) && !double.IsPositiveInfinity(value) && !double.IsNegativeInfinity(value)) { return value; } throw ThrowHelper.GetFormatException(NumericType.Double); } internal double GetDoubleFloatingPointConstant() { ReadOnlySpan unescapedSpan = GetUnescapedSpan(); if (JsonReaderHelper.TryGetFloatingPointConstant(unescapedSpan, out double value)) { return value; } throw ThrowHelper.GetFormatException(NumericType.Double); } public decimal GetDecimal() { if (!TryGetDecimal(out var value)) { throw ThrowHelper.GetFormatException(NumericType.Decimal); } return value; } internal decimal GetDecimalWithQuotes() { ReadOnlySpan unescapedSpan = GetUnescapedSpan(); char floatingPointStandardParseFormat = JsonReaderHelper.GetFloatingPointStandardParseFormat(unescapedSpan); if (Utf8Parser.TryParse(unescapedSpan, out decimal value, out int bytesConsumed, floatingPointStandardParseFormat) && unescapedSpan.Length == bytesConsumed) { return value; } throw ThrowHelper.GetFormatException(NumericType.Decimal); } public DateTime GetDateTime() { if (!TryGetDateTime(out var value)) { throw ThrowHelper.GetFormatException(DataType.DateTime); } return value; } internal DateTime GetDateTimeNoValidation() { if (!TryGetDateTimeCore(out var value)) { throw ThrowHelper.GetFormatException(DataType.DateTime); } return value; } public DateTimeOffset GetDateTimeOffset() { if (!TryGetDateTimeOffset(out var value)) { throw ThrowHelper.GetFormatException(DataType.DateTimeOffset); } return value; } internal DateTimeOffset GetDateTimeOffsetNoValidation() { if (!TryGetDateTimeOffsetCore(out var value)) { throw ThrowHelper.GetFormatException(DataType.DateTimeOffset); } return value; } public Guid GetGuid() { if (!TryGetGuid(out var value)) { throw ThrowHelper.GetFormatException(DataType.Guid); } return value; } internal Guid GetGuidNoValidation() { if (!TryGetGuidCore(out var value)) { throw ThrowHelper.GetFormatException(DataType.Guid); } return value; } public bool TryGetBytesFromBase64([NotNullWhen(true)] out byte[]? value) { if (TokenType != JsonTokenType.String) { throw ThrowHelper.GetInvalidOperationException_ExpectedString(TokenType); } ReadOnlySpan readOnlySpan; if (!HasValueSequence) { readOnlySpan = ValueSpan; } else { ReadOnlySequence sequence = ValueSequence; readOnlySpan = BuffersExtensions.ToArray(in sequence); } ReadOnlySpan readOnlySpan2 = readOnlySpan; if (_stringHasEscaping) { int idx = readOnlySpan2.IndexOf(92); return JsonReaderHelper.TryGetUnescapedBase64Bytes(readOnlySpan2, idx, out value); } return JsonReaderHelper.TryDecodeBase64(readOnlySpan2, out value); } public bool TryGetByte(out byte value) { if (TokenType != JsonTokenType.Number) { throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType); } ReadOnlySpan readOnlySpan; if (!HasValueSequence) { readOnlySpan = ValueSpan; } else { ReadOnlySequence sequence = ValueSequence; readOnlySpan = BuffersExtensions.ToArray(in sequence); } ReadOnlySpan span = readOnlySpan; return TryGetByteCore(out value, span); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool TryGetByteCore(out byte value, ReadOnlySpan span) { if (Utf8Parser.TryParse(span, out byte value2, out int bytesConsumed, '\0') && span.Length == bytesConsumed) { value = value2; return true; } value = 0; return false; } [CLSCompliant(false)] public bool TryGetSByte(out sbyte value) { if (TokenType != JsonTokenType.Number) { throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType); } ReadOnlySpan readOnlySpan; if (!HasValueSequence) { readOnlySpan = ValueSpan; } else { ReadOnlySequence sequence = ValueSequence; readOnlySpan = BuffersExtensions.ToArray(in sequence); } ReadOnlySpan span = readOnlySpan; return TryGetSByteCore(out value, span); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool TryGetSByteCore(out sbyte value, ReadOnlySpan span) { if (Utf8Parser.TryParse(span, out sbyte value2, out int bytesConsumed, '\0') && span.Length == bytesConsumed) { value = value2; return true; } value = 0; return false; } public bool TryGetInt16(out short value) { if (TokenType != JsonTokenType.Number) { throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType); } ReadOnlySpan readOnlySpan; if (!HasValueSequence) { readOnlySpan = ValueSpan; } else { ReadOnlySequence sequence = ValueSequence; readOnlySpan = BuffersExtensions.ToArray(in sequence); } ReadOnlySpan span = readOnlySpan; return TryGetInt16Core(out value, span); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool TryGetInt16Core(out short value, ReadOnlySpan span) { if (Utf8Parser.TryParse(span, out short value2, out int bytesConsumed, '\0') && span.Length == bytesConsumed) { value = value2; return true; } value = 0; return false; } public bool TryGetInt32(out int value) { if (TokenType != JsonTokenType.Number) { throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType); } ReadOnlySpan readOnlySpan; if (!HasValueSequence) { readOnlySpan = ValueSpan; } else { ReadOnlySequence sequence = ValueSequence; readOnlySpan = BuffersExtensions.ToArray(in sequence); } ReadOnlySpan span = readOnlySpan; return TryGetInt32Core(out value, span); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool TryGetInt32Core(out int value, ReadOnlySpan span) { if (Utf8Parser.TryParse(span, out int value2, out int bytesConsumed, '\0') && span.Length == bytesConsumed) { value = value2; return true; } value = 0; return false; } public bool TryGetInt64(out long value) { if (TokenType != JsonTokenType.Number) { throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType); } ReadOnlySpan readOnlySpan; if (!HasValueSequence) { readOnlySpan = ValueSpan; } else { ReadOnlySequence sequence = ValueSequence; readOnlySpan = BuffersExtensions.ToArray(in sequence); } ReadOnlySpan span = readOnlySpan; return TryGetInt64Core(out value, span); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool TryGetInt64Core(out long value, ReadOnlySpan span) { if (Utf8Parser.TryParse(span, out long value2, out int bytesConsumed, '\0') && span.Length == bytesConsumed) { value = value2; return true; } value = 0L; return false; } [CLSCompliant(false)] public bool TryGetUInt16(out ushort value) { if (TokenType != JsonTokenType.Number) { throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType); } ReadOnlySpan readOnlySpan; if (!HasValueSequence) { readOnlySpan = ValueSpan; } else { ReadOnlySequence sequence = ValueSequence; readOnlySpan = BuffersExtensions.ToArray(in sequence); } ReadOnlySpan span = readOnlySpan; return TryGetUInt16Core(out value, span); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool TryGetUInt16Core(out ushort value, ReadOnlySpan span) { if (Utf8Parser.TryParse(span, out ushort value2, out int bytesConsumed, '\0') && span.Length == bytesConsumed) { value = value2; return true; } value = 0; return false; } [CLSCompliant(false)] public bool TryGetUInt32(out uint value) { if (TokenType != JsonTokenType.Number) { throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType); } ReadOnlySpan readOnlySpan; if (!HasValueSequence) { readOnlySpan = ValueSpan; } else { ReadOnlySequence sequence = ValueSequence; readOnlySpan = BuffersExtensions.ToArray(in sequence); } ReadOnlySpan span = readOnlySpan; return TryGetUInt32Core(out value, span); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool TryGetUInt32Core(out uint value, ReadOnlySpan span) { if (Utf8Parser.TryParse(span, out uint value2, out int bytesConsumed, '\0') && span.Length == bytesConsumed) { value = value2; return true; } value = 0u; return false; } [CLSCompliant(false)] public bool TryGetUInt64(out ulong value) { if (TokenType != JsonTokenType.Number) { throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType); } ReadOnlySpan readOnlySpan; if (!HasValueSequence) { readOnlySpan = ValueSpan; } else { ReadOnlySequence sequence = ValueSequence; readOnlySpan = BuffersExtensions.ToArray(in sequence); } ReadOnlySpan span = readOnlySpan; return TryGetUInt64Core(out value, span); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool TryGetUInt64Core(out ulong value, ReadOnlySpan span) { if (Utf8Parser.TryParse(span, out ulong value2, out int bytesConsumed, '\0') && span.Length == bytesConsumed) { value = value2; return true; } value = 0uL; return false; } public bool TryGetSingle(out float value) { if (TokenType != JsonTokenType.Number) { throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType); } ReadOnlySpan readOnlySpan; if (!HasValueSequence) { readOnlySpan = ValueSpan; } else { ReadOnlySequence sequence = ValueSequence; readOnlySpan = BuffersExtensions.ToArray(in sequence); } ReadOnlySpan source = readOnlySpan; if (Utf8Parser.TryParse(source, out float value2, out int bytesConsumed, _numberFormat) && source.Length == bytesConsumed) { value = value2; return true; } value = 0f; return false; } public bool TryGetDouble(out double value) { if (TokenType != JsonTokenType.Number) { throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType); } ReadOnlySpan readOnlySpan; if (!HasValueSequence) { readOnlySpan = ValueSpan; } else { ReadOnlySequence sequence = ValueSequence; readOnlySpan = BuffersExtensions.ToArray(in sequence); } ReadOnlySpan source = readOnlySpan; if (Utf8Parser.TryParse(source, out double value2, out int bytesConsumed, _numberFormat) && source.Length == bytesConsumed) { value = value2; return true; } value = 0.0; return false; } public bool TryGetDecimal(out decimal value) { if (TokenType != JsonTokenType.Number) { throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType); } ReadOnlySpan readOnlySpan; if (!HasValueSequence) { readOnlySpan = ValueSpan; } else { ReadOnlySequence sequence = ValueSequence; readOnlySpan = BuffersExtensions.ToArray(in sequence); } ReadOnlySpan source = readOnlySpan; if (Utf8Parser.TryParse(source, out decimal value2, out int bytesConsumed, _numberFormat) && source.Length == bytesConsumed) { value = value2; return true; } value = default(decimal); return false; } public bool TryGetDateTime(out DateTime value) { if (TokenType != JsonTokenType.String) { throw ThrowHelper.GetInvalidOperationException_ExpectedString(TokenType); } return TryGetDateTimeCore(out value); } internal bool TryGetDateTimeCore(out DateTime value) { ReadOnlySpan readOnlySpan = default(Span); if (HasValueSequence) { long length = ValueSequence.Length; if (!JsonHelpers.IsValidDateTimeOffsetParseLength(length)) { value = default(DateTime); return false; } Span span = stackalloc byte[(int)length]; ReadOnlySequence source = ValueSequence; source.CopyTo(span); readOnlySpan = span; } else { if (!JsonHelpers.IsValidDateTimeOffsetParseLength(ValueSpan.Length)) { value = default(DateTime); return false; } readOnlySpan = ValueSpan; } if (_stringHasEscaping) { return JsonReaderHelper.TryGetEscapedDateTime(readOnlySpan, out value); } if (JsonHelpers.TryParseAsISO(readOnlySpan, out DateTime value2)) { value = value2; return true; } value = default(DateTime); return false; } public bool TryGetDateTimeOffset(out DateTimeOffset value) { if (TokenType != JsonTokenType.String) { throw ThrowHelper.GetInvalidOperationException_ExpectedString(TokenType); } return TryGetDateTimeOffsetCore(out value); } internal bool TryGetDateTimeOffsetCore(out DateTimeOffset value) { ReadOnlySpan readOnlySpan = default(Span); if (HasValueSequence) { long length = ValueSequence.Length; if (!JsonHelpers.IsValidDateTimeOffsetParseLength(length)) { value = default(DateTimeOffset); return false; } Span span = stackalloc byte[(int)length]; ReadOnlySequence source = ValueSequence; source.CopyTo(span); readOnlySpan = span; } else { if (!JsonHelpers.IsValidDateTimeOffsetParseLength(ValueSpan.Length)) { value = default(DateTimeOffset); return false; } readOnlySpan = ValueSpan; } if (_stringHasEscaping) { return JsonReaderHelper.TryGetEscapedDateTimeOffset(readOnlySpan, out value); } if (JsonHelpers.TryParseAsISO(readOnlySpan, out DateTimeOffset value2)) { value = value2; return true; } value = default(DateTimeOffset); return false; } public bool TryGetGuid(out Guid value) { if (TokenType != JsonTokenType.String) { throw ThrowHelper.GetInvalidOperationException_ExpectedString(TokenType); } return TryGetGuidCore(out value); } internal bool TryGetGuidCore(out Guid value) { ReadOnlySpan readOnlySpan = default(Span); if (HasValueSequence) { long length = ValueSequence.Length; if (length > 216) { value = default(Guid); return false; } Span span = stackalloc byte[(int)length]; ReadOnlySequence source = ValueSequence; source.CopyTo(span); readOnlySpan = span; } else { if (ValueSpan.Length > 216) { value = default(Guid); return false; } readOnlySpan = ValueSpan; } if (_stringHasEscaping) { return JsonReaderHelper.TryGetEscapedGuid(readOnlySpan, out value); } if (readOnlySpan.Length == 36 && Utf8Parser.TryParse(readOnlySpan, out Guid value2, out int _, 'D')) { value = value2; return true; } value = default(Guid); return false; } } internal sealed class Arguments { public TArg0 Arg0; public TArg1 Arg1; public TArg2 Arg2; public TArg3 Arg3; } internal class ArgumentState { public object Arguments; public (JsonPropertyInfo, JsonReaderState, long, byte[], string)[] FoundProperties; public (JsonPropertyInfo, object, string)[] FoundPropertiesAsync; public int FoundPropertyCount; public JsonParameterInfo JsonParameterInfo; public int ParameterIndex; public List ParameterRefCache; public bool FoundKey; public bool FoundValue; } internal enum ClassType : byte { None = 0, Object = 1, Value = 2, NewValue = 4, Enumerable = 8, Dictionary = 0x10 } internal sealed class JsonCamelCaseNamingPolicy : JsonNamingPolicy { public override string ConvertName(string name) { if (string.IsNullOrEmpty(name) || !char.IsUpper(name[0])) { return name; } char[] array = name.ToCharArray(); FixCasing(array); return new string(array); } private static void FixCasing(Span chars) { for (int i = 0; i < chars.Length && (i != 1 || char.IsUpper(chars[i])); i++) { bool flag = i + 1 < chars.Length; if (i > 0 && flag && !char.IsUpper(chars[i + 1])) { if (chars[i + 1] == ' ') { chars[i] = char.ToLowerInvariant(chars[i]); } break; } chars[i] = char.ToLowerInvariant(chars[i]); } } } [DebuggerDisplay("ClassType.{ClassType}, {Type.Name}")] internal sealed class JsonClassInfo { public delegate object ConstructorDelegate(); public delegate T ParameterizedConstructorDelegate(object[] arguments); public delegate T ParameterizedConstructorDelegate(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3); private sealed class ParameterLookupKey { public string Name { get; } public Type Type { get; } public ParameterLookupKey(string name, Type type) { Name = name; Type = type; } public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(Name); } public override bool Equals(object obj) { ParameterLookupKey parameterLookupKey = (ParameterLookupKey)obj; if (Type == parameterLookupKey.Type) { return string.Equals(Name, parameterLookupKey.Name, StringComparison.OrdinalIgnoreCase); } return false; } } private sealed class ParameterLookupValue { public string DuplicateName { get; set; } public JsonPropertyInfo JsonPropertyInfo { get; } public ParameterLookupValue(JsonPropertyInfo jsonPropertyInfo) { JsonPropertyInfo = jsonPropertyInfo; } } private JsonClassInfo _elementClassInfo; public static readonly Type ObjectType = typeof(object); private const int PropertyNameKeyLength = 7; private const int ParameterNameCountCacheThreshold = 32; private const int PropertyNameCountCacheThreshold = 64; public Dictionary ParameterCache; public Dictionary PropertyCache; public JsonPropertyInfo[] PropertyCacheArray; private volatile ParameterRef[] _parameterRefsSorted; private volatile PropertyRef[] _propertyRefsSorted; public ConstructorDelegate CreateObject { get; private set; } public object CreateObjectWithArgs { get; set; } public object AddMethodDelegate { get; set; } public ClassType ClassType { get; private set; } public JsonPropertyInfo DataExtensionProperty { get; private set; } public JsonClassInfo ElementClassInfo { get { if (_elementClassInfo == null && ElementType != null) { _elementClassInfo = Options.GetOrAddClass(ElementType); } return _elementClassInfo; } } public Type ElementType { get; set; } public JsonSerializerOptions Options { get; private set; } public Type Type { get; private set; } public JsonPropertyInfo PropertyInfoForClassInfo { get; private set; } public int ParameterCount { get; private set; } public JsonClassInfo(Type type, JsonSerializerOptions options) { Type = type; Options = options; Type runtimeType; JsonConverter converter = GetConverter(Type, null, null, out runtimeType, Options); ClassType = converter.ClassType; JsonNumberHandling? numberHandlingForType = GetNumberHandlingForType(Type); PropertyInfoForClassInfo = CreatePropertyInfoForClassInfo(Type, runtimeType, converter, Options); switch (ClassType) { case ClassType.Object: { CreateObject = Options.MemberAccessorStrategy.CreateConstructor(type); Dictionary dictionary = new Dictionary(Options.PropertyNameCaseInsensitive ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); Dictionary ignoredMembers = null; Type type2 = type; while (type2 != null) { PropertyInfo[] properties = type2.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (PropertyInfo propertyInfo in properties) { if (propertyInfo.GetIndexParameters().Length != 0 || PropertyIsOverridenAndIgnored(propertyInfo, ignoredMembers)) { continue; } MethodInfo? getMethod = propertyInfo.GetMethod; if ((object)getMethod == null || !getMethod.IsPublic) { MethodInfo? setMethod = propertyInfo.SetMethod; if ((object)setMethod == null || !setMethod.IsPublic) { if (JsonPropertyInfo.GetAttribute(propertyInfo) != null) { ThrowHelper.ThrowInvalidOperationException_JsonIncludeOnNonPublicInvalid(propertyInfo, type2); } continue; } } CacheMember(type2, propertyInfo.PropertyType, propertyInfo, numberHandlingForType, dictionary, ref ignoredMembers); } FieldInfo[] fields = type2.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { if (PropertyIsOverridenAndIgnored(fieldInfo, ignoredMembers)) { continue; } bool flag = JsonPropertyInfo.GetAttribute(fieldInfo) != null; if (fieldInfo.IsPublic) { if (flag || Options.IncludeFields) { CacheMember(type2, fieldInfo.FieldType, fieldInfo, numberHandlingForType, dictionary, ref ignoredMembers); } } else if (flag) { ThrowHelper.ThrowInvalidOperationException_JsonIncludeOnNonPublicInvalid(fieldInfo, type2); } } type2 = type2.BaseType; } JsonPropertyInfo[] array; if (DetermineExtensionDataProperty(dictionary)) { dictionary.Remove(DataExtensionProperty.NameAsString); array = new JsonPropertyInfo[dictionary.Count + 1]; array[dictionary.Count] = DataExtensionProperty; } else { array = new JsonPropertyInfo[dictionary.Count]; } dictionary.Values.CopyTo(array, 0); PropertyCache = dictionary; PropertyCacheArray = array; if (converter.ConstructorIsParameterized) { InitializeConstructorParameters(converter.ConstructorInfo); } break; } case ClassType.Enumerable: case ClassType.Dictionary: ElementType = converter.ElementType; CreateObject = Options.MemberAccessorStrategy.CreateConstructor(runtimeType); break; case ClassType.Value: case ClassType.NewValue: CreateObject = Options.MemberAccessorStrategy.CreateConstructor(type); break; case ClassType.None: ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(type); break; default: throw new InvalidOperationException(); } } private void CacheMember(Type declaringType, Type memberType, MemberInfo memberInfo, JsonNumberHandling? typeNumberHandling, Dictionary cache, ref Dictionary ignoredMembers) { JsonPropertyInfo value = AddProperty(memberInfo, memberType, declaringType, typeNumberHandling, Options); string name = memberInfo.Name; string key = value.NameAsString; if (!JsonHelpers.TryAdd(cache, in key, in value)) { JsonPropertyInfo jsonPropertyInfo = cache[value.NameAsString]; if (jsonPropertyInfo.IsIgnored) { cache[value.NameAsString] = value; } else if (!value.IsIgnored && jsonPropertyInfo.MemberInfo.Name != name) { Dictionary obj = ignoredMembers; if (obj == null || !obj.ContainsKey(name)) { ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameConflict(Type, value); } } } if (value.IsIgnored) { (ignoredMembers ?? (ignoredMembers = new Dictionary())).Add(name, memberInfo); } } private void InitializeConstructorParameters(ConstructorInfo constructorInfo) { ParameterInfo[] parameters = constructorInfo.GetParameters(); Dictionary dictionary = new Dictionary(parameters.Length, Options.PropertyNameCaseInsensitive ? StringComparer.OrdinalIgnoreCase : null); Dictionary dictionary2 = new Dictionary(PropertyCacheArray.Length); JsonPropertyInfo[] propertyCacheArray = PropertyCacheArray; foreach (JsonPropertyInfo jsonPropertyInfo in propertyCacheArray) { string name = jsonPropertyInfo.MemberInfo.Name; ParameterLookupKey key = new ParameterLookupKey(name, GetMemberType(jsonPropertyInfo.MemberInfo)); ParameterLookupValue value = new ParameterLookupValue(jsonPropertyInfo); if (!JsonHelpers.TryAdd(dictionary2, in key, in value)) { ParameterLookupValue parameterLookupValue = dictionary2[key]; parameterLookupValue.DuplicateName = name; } } ParameterInfo[] array = parameters; foreach (ParameterInfo parameterInfo in array) { ParameterLookupKey key2 = new ParameterLookupKey(parameterInfo.Name, parameterInfo.ParameterType); if (dictionary2.TryGetValue(key2, out var value2)) { if (value2.DuplicateName != null) { ThrowHelper.ThrowInvalidOperationException_MultiplePropertiesBindToConstructorParameters(Type, parameterInfo.Name, value2.JsonPropertyInfo.NameAsString, value2.DuplicateName, constructorInfo); } JsonPropertyInfo jsonPropertyInfo2 = value2.JsonPropertyInfo; JsonParameterInfo value3 = AddConstructorParameter(parameterInfo, jsonPropertyInfo2, Options); dictionary.Add(jsonPropertyInfo2.NameAsString, value3); PropertyCache.Remove(jsonPropertyInfo2.NameAsString); } } if (DataExtensionProperty != null && dictionary.ContainsKey(DataExtensionProperty.NameAsString)) { ThrowHelper.ThrowInvalidOperationException_ExtensionDataCannotBindToCtorParam(DataExtensionProperty.MemberInfo, Type, constructorInfo); } ParameterCache = dictionary; ParameterCount = parameters.Length; static Type GetMemberType(MemberInfo memberInfo) { if (!(memberInfo is PropertyInfo propertyInfo)) { return Unsafe.As(memberInfo).FieldType; } return propertyInfo.PropertyType; } } private static bool PropertyIsOverridenAndIgnored(MemberInfo currentMember, Dictionary ignoredMembers) { if (ignoredMembers == null || !ignoredMembers.TryGetValue(currentMember.Name, out var value)) { return false; } PropertyInfo propertyInfo = currentMember as PropertyInfo; Type type = ((propertyInfo == null) ? Unsafe.As(currentMember).FieldType : propertyInfo.PropertyType); PropertyInfo propertyInfo2 = value as PropertyInfo; Type type2 = ((propertyInfo2 == null) ? Unsafe.As(value).FieldType : propertyInfo2.PropertyType); if (type == type2 && PropertyIsVirtual(propertyInfo)) { return PropertyIsVirtual(propertyInfo2); } return false; } private static bool PropertyIsVirtual(PropertyInfo propertyInfo) { if (propertyInfo != null) { MethodInfo? getMethod = propertyInfo.GetMethod; if ((object)getMethod == null || !getMethod.IsVirtual) { return propertyInfo.SetMethod?.IsVirtual ?? false; } return true; } return false; } public bool DetermineExtensionDataProperty(Dictionary cache) { JsonPropertyInfo propertyWithUniqueAttribute = GetPropertyWithUniqueAttribute(Type, typeof(JsonExtensionDataAttribute), cache); if (propertyWithUniqueAttribute != null) { Type declaredPropertyType = propertyWithUniqueAttribute.DeclaredPropertyType; if (typeof(IDictionary).IsAssignableFrom(declaredPropertyType) || typeof(IDictionary).IsAssignableFrom(declaredPropertyType)) { JsonConverter converter = Options.GetConverter(declaredPropertyType); } else { ThrowHelper.ThrowInvalidOperationException_SerializationDataExtensionPropertyInvalid(Type, propertyWithUniqueAttribute); } DataExtensionProperty = propertyWithUniqueAttribute; return true; } return false; } private static JsonPropertyInfo GetPropertyWithUniqueAttribute(Type classType, Type attributeType, Dictionary cache) { JsonPropertyInfo jsonPropertyInfo = null; foreach (JsonPropertyInfo value in cache.Values) { Attribute customAttribute = value.MemberInfo.GetCustomAttribute(attributeType); if (customAttribute != null) { if (jsonPropertyInfo != null) { ThrowHelper.ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(classType, attributeType); } jsonPropertyInfo = value; } } return jsonPropertyInfo; } private static JsonParameterInfo AddConstructorParameter(ParameterInfo parameterInfo, JsonPropertyInfo jsonPropertyInfo, JsonSerializerOptions options) { if (jsonPropertyInfo.IsIgnored) { return JsonParameterInfo.CreateIgnoredParameterPlaceholder(jsonPropertyInfo); } JsonConverter converterBase = jsonPropertyInfo.ConverterBase; JsonParameterInfo jsonParameterInfo = converterBase.CreateJsonParameterInfo(); jsonParameterInfo.Initialize(jsonPropertyInfo.RuntimePropertyType, parameterInfo, jsonPropertyInfo, options); return jsonParameterInfo; } public static JsonConverter GetConverter(Type type, Type parentClassType, MemberInfo memberInfo, out Type runtimeType, JsonSerializerOptions options) { ValidateType(type, parentClassType, memberInfo, options); JsonConverter jsonConverter = options.DetermineConverter(parentClassType, type, memberInfo); Type runtimeType2 = jsonConverter.RuntimeType; if (type == runtimeType2) { runtimeType = type; } else if (type.IsInterface) { runtimeType = runtimeType2; } else if (runtimeType2.IsInterface) { runtimeType = type; } else if (type.IsAssignableFrom(runtimeType2)) { runtimeType = runtimeType2; } else if (runtimeType2.IsAssignableFrom(type) || jsonConverter.TypeToConvert.IsAssignableFrom(type)) { runtimeType = type; } else { runtimeType = null; ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(type); } return jsonConverter; } private static void ValidateType(Type type, Type parentClassType, MemberInfo memberInfo, JsonSerializerOptions options) { if (!options.TypeIsCached(type) && IsInvalidForSerialization(type)) { ThrowHelper.ThrowInvalidOperationException_CannotSerializeInvalidType(type, parentClassType, memberInfo); } } private static bool IsInvalidForSerialization(Type type) { if (!type.IsPointer && !IsByRefLike(type)) { return type.ContainsGenericParameters; } return true; } private static bool IsByRefLike(Type type) { if (!type.IsValueType) { return false; } object[] customAttributes = type.GetCustomAttributes(inherit: false); for (int i = 0; i < customAttributes.Length; i++) { if (customAttributes[i].GetType().FullName == "System.Runtime.CompilerServices.IsByRefLikeAttribute") { return true; } } return false; } private static JsonNumberHandling? GetNumberHandlingForType(Type type) { return ((JsonNumberHandlingAttribute)JsonSerializerOptions.GetAttributeThatCanHaveMultiple(type, typeof(JsonNumberHandlingAttribute)))?.Handling; } public static JsonPropertyInfo AddProperty(MemberInfo memberInfo, Type memberType, Type parentClassType, JsonNumberHandling? parentTypeNumberHandling, JsonSerializerOptions options) { JsonIgnoreCondition? jsonIgnoreCondition = JsonPropertyInfo.GetAttribute(memberInfo)?.Condition; if (jsonIgnoreCondition == JsonIgnoreCondition.Always) { return JsonPropertyInfo.CreateIgnoredPropertyPlaceholder(memberInfo, options); } Type runtimeType; JsonConverter converter = GetConverter(memberType, parentClassType, memberInfo, out runtimeType, options); return CreateProperty(memberType, runtimeType, memberInfo, parentClassType, converter, options, parentTypeNumberHandling, jsonIgnoreCondition); } internal static JsonPropertyInfo CreateProperty(Type declaredPropertyType, Type runtimePropertyType, MemberInfo memberInfo, Type parentClassType, JsonConverter converter, JsonSerializerOptions options, JsonNumberHandling? parentTypeNumberHandling = null, JsonIgnoreCondition? ignoreCondition = null) { JsonPropertyInfo jsonPropertyInfo = converter.CreateJsonPropertyInfo(); jsonPropertyInfo.Initialize(parentClassType, declaredPropertyType, runtimePropertyType, converter.ClassType, memberInfo, converter, ignoreCondition, parentTypeNumberHandling, options); return jsonPropertyInfo; } internal static JsonPropertyInfo CreatePropertyInfoForClassInfo(Type declaredPropertyType, Type runtimePropertyType, JsonConverter converter, JsonSerializerOptions options) { JsonNumberHandling? numberHandlingForType = GetNumberHandlingForType(declaredPropertyType); return CreateProperty(declaredPropertyType, runtimePropertyType, null, ObjectType, converter, options, numberHandlingForType); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public JsonPropertyInfo GetProperty(ReadOnlySpan propertyName, ref ReadStackFrame frame, out byte[] utf8PropertyName) { ulong key = GetKey(propertyName); PropertyRef[] propertyRefsSorted = _propertyRefsSorted; if (propertyRefsSorted != null) { int propertyIndex = frame.PropertyIndex; int num = propertyRefsSorted.Length; int num2 = Math.Min(propertyIndex, num); int num3 = num2 - 1; while (true) { if (num2 < num) { PropertyRef propertyRef = propertyRefsSorted[num2]; if (IsPropertyRefEqual(in propertyRef, propertyName, key)) { utf8PropertyName = propertyRef.NameFromJson; return propertyRef.Info; } num2++; if (num3 >= 0) { propertyRef = propertyRefsSorted[num3]; if (IsPropertyRefEqual(in propertyRef, propertyName, key)) { utf8PropertyName = propertyRef.NameFromJson; return propertyRef.Info; } num3--; } } else { if (num3 < 0) { break; } PropertyRef propertyRef = propertyRefsSorted[num3]; if (IsPropertyRefEqual(in propertyRef, propertyName, key)) { utf8PropertyName = propertyRef.NameFromJson; return propertyRef.Info; } num3--; } } } if (PropertyCache.TryGetValue(JsonHelpers.Utf8GetString(propertyName), out var value)) { if (Options.PropertyNameCaseInsensitive) { if (propertyName.SequenceEqual(value.NameAsUtf8Bytes)) { utf8PropertyName = value.NameAsUtf8Bytes; } else { utf8PropertyName = propertyName.ToArray(); } } else { utf8PropertyName = value.NameAsUtf8Bytes; } } else { value = JsonPropertyInfo.s_missingProperty; utf8PropertyName = propertyName.ToArray(); } int num4 = 0; if (propertyRefsSorted != null) { num4 = propertyRefsSorted.Length; } if (num4 < 64) { if (frame.PropertyRefCache != null) { num4 += frame.PropertyRefCache.Count; } if (num4 < 64) { if (frame.PropertyRefCache == null) { frame.PropertyRefCache = new List(); } PropertyRef propertyRef = new PropertyRef(key, value, utf8PropertyName); frame.PropertyRefCache.Add(propertyRef); } } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public JsonParameterInfo GetParameter(ReadOnlySpan propertyName, ref ReadStackFrame frame, out byte[] utf8PropertyName) { ulong key = GetKey(propertyName); ParameterRef[] parameterRefsSorted = _parameterRefsSorted; if (parameterRefsSorted != null) { int parameterIndex = frame.CtorArgumentState.ParameterIndex; int num = parameterRefsSorted.Length; int num2 = Math.Min(parameterIndex, num); int num3 = num2 - 1; while (true) { if (num2 < num) { ParameterRef parameterRef = parameterRefsSorted[num2]; if (IsParameterRefEqual(in parameterRef, propertyName, key)) { utf8PropertyName = parameterRef.NameFromJson; return parameterRef.Info; } num2++; if (num3 >= 0) { parameterRef = parameterRefsSorted[num3]; if (IsParameterRefEqual(in parameterRef, propertyName, key)) { utf8PropertyName = parameterRef.NameFromJson; return parameterRef.Info; } num3--; } } else { if (num3 < 0) { break; } ParameterRef parameterRef = parameterRefsSorted[num3]; if (IsParameterRefEqual(in parameterRef, propertyName, key)) { utf8PropertyName = parameterRef.NameFromJson; return parameterRef.Info; } num3--; } } } if (ParameterCache.TryGetValue(JsonHelpers.Utf8GetString(propertyName), out var value)) { if (Options.PropertyNameCaseInsensitive) { if (propertyName.SequenceEqual(value.NameAsUtf8Bytes)) { utf8PropertyName = value.NameAsUtf8Bytes; } else { utf8PropertyName = propertyName.ToArray(); } } else { utf8PropertyName = value.NameAsUtf8Bytes; } } else { utf8PropertyName = propertyName.ToArray(); } int num4 = 0; if (parameterRefsSorted != null) { num4 = parameterRefsSorted.Length; } if (num4 < 32) { if (frame.CtorArgumentState.ParameterRefCache != null) { num4 += frame.CtorArgumentState.ParameterRefCache.Count; } if (num4 < 32) { if (frame.CtorArgumentState.ParameterRefCache == null) { frame.CtorArgumentState.ParameterRefCache = new List(); } ParameterRef parameterRef = new ParameterRef(key, value, utf8PropertyName); frame.CtorArgumentState.ParameterRefCache.Add(parameterRef); } } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsPropertyRefEqual(in PropertyRef propertyRef, ReadOnlySpan propertyName, ulong key) { if (key == propertyRef.Key && (propertyName.Length <= 7 || propertyName.SequenceEqual(propertyRef.NameFromJson))) { return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsParameterRefEqual(in ParameterRef parameterRef, ReadOnlySpan parameterName, ulong key) { if (key == parameterRef.Key && (parameterName.Length <= 7 || parameterName.SequenceEqual(parameterRef.NameFromJson))) { return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong GetKey(ReadOnlySpan name) { ref byte reference = ref MemoryMarshal.GetReference(name); int length = name.Length; ulong num; if (length > 7) { num = Unsafe.ReadUnaligned(ref reference) & 0xFFFFFFFFFFFFFFuL; num |= (ulong)((long)Math.Min(length, 255) << 56); } else { num = ((length > 5) ? (Unsafe.ReadUnaligned(ref reference) | ((ulong)Unsafe.ReadUnaligned(ref Unsafe.Add(ref reference, 4)) << 32)) : ((length > 3) ? ((ulong)Unsafe.ReadUnaligned(ref reference)) : ((ulong)((length > 1) ? Unsafe.ReadUnaligned(ref reference) : 0)))); num |= (ulong)((long)length << 56); if (((uint)length & (true ? 1u : 0u)) != 0) { int num2 = length - 1; num |= (ulong)Unsafe.Add(ref reference, num2) << num2 * 8; } } return num; } public void UpdateSortedPropertyCache(ref ReadStackFrame frame) { List propertyRefCache = frame.PropertyRefCache; if (_propertyRefsSorted != null) { List list = new List(_propertyRefsSorted); while (list.Count + propertyRefCache.Count > 64) { propertyRefCache.RemoveAt(propertyRefCache.Count - 1); } list.AddRange(propertyRefCache); _propertyRefsSorted = list.ToArray(); } else { _propertyRefsSorted = propertyRefCache.ToArray(); } frame.PropertyRefCache = null; } public void UpdateSortedParameterCache(ref ReadStackFrame frame) { List parameterRefCache = frame.CtorArgumentState.ParameterRefCache; if (_parameterRefsSorted != null) { List list = new List(_parameterRefsSorted); while (list.Count + parameterRefCache.Count > 32) { parameterRefCache.RemoveAt(parameterRefCache.Count - 1); } list.AddRange(parameterRefCache); _parameterRefsSorted = list.ToArray(); } else { _parameterRefsSorted = parameterRefCache.ToArray(); } frame.CtorArgumentState.ParameterRefCache = null; } } internal class JsonDefaultNamingPolicy : JsonNamingPolicy { public override string ConvertName(string name) { return name; } } internal abstract class JsonNamingPolicy { public static JsonNamingPolicy CamelCase { get; } = new JsonCamelCaseNamingPolicy(); internal static JsonNamingPolicy Default { get; } = new JsonDefaultNamingPolicy(); public abstract string ConvertName(string name); } internal abstract class JsonParameterInfo { private JsonClassInfo _runtimeClassInfo; public JsonConverter ConverterBase { get; private set; } public object DefaultValue { get; protected set; } public bool IgnoreDefaultValuesOnRead { get; private set; } public JsonSerializerOptions Options { get; set; } public byte[] NameAsUtf8Bytes { get; private set; } public JsonNumberHandling? NumberHandling { get; private set; } public int Position { get; private set; } public JsonClassInfo RuntimeClassInfo { get { if (_runtimeClassInfo == null) { _runtimeClassInfo = Options.GetOrAddClass(RuntimePropertyType); } return _runtimeClassInfo; } } internal Type RuntimePropertyType { get; set; } public bool ShouldDeserialize { get; private set; } public virtual void Initialize(Type runtimePropertyType, ParameterInfo parameterInfo, JsonPropertyInfo matchingProperty, JsonSerializerOptions options) { RuntimePropertyType = runtimePropertyType; Position = parameterInfo.Position; NameAsUtf8Bytes = matchingProperty.NameAsUtf8Bytes; Options = options; ShouldDeserialize = true; ConverterBase = matchingProperty.ConverterBase; IgnoreDefaultValuesOnRead = matchingProperty.IgnoreDefaultValuesOnRead; NumberHandling = matchingProperty.NumberHandling; } public static JsonParameterInfo CreateIgnoredParameterPlaceholder(JsonPropertyInfo matchingProperty) { JsonParameterInfo jsonParameterInfo = new JsonParameterInfo(); jsonParameterInfo.RuntimePropertyType = typeof(sbyte); jsonParameterInfo.NameAsUtf8Bytes = matchingProperty.NameAsUtf8Bytes; return jsonParameterInfo; } } internal class JsonParameterInfo : JsonParameterInfo { public T TypedDefaultValue { get; private set; } public override void Initialize(Type runtimePropertyType, ParameterInfo parameterInfo, JsonPropertyInfo matchingProperty, JsonSerializerOptions options) { base.Initialize(runtimePropertyType, parameterInfo, matchingProperty, options); if (parameterInfo.HasDefaultValue) { if (parameterInfo.DefaultValue == null && !matchingProperty.PropertyTypeCanBeNull) { base.DefaultValue = TypedDefaultValue; return; } base.DefaultValue = parameterInfo.DefaultValue; TypedDefaultValue = (T)parameterInfo.DefaultValue; } else { base.DefaultValue = TypedDefaultValue; } } } [DebuggerDisplay("MemberInfo={MemberInfo}")] internal abstract class JsonPropertyInfo { public static readonly JsonPropertyInfo s_missingProperty = GetPropertyPlaceholder(); private JsonClassInfo _runtimeClassInfo; public ClassType ClassType; public byte[] NameAsUtf8Bytes; public byte[] EscapedNameSection; public abstract JsonConverter ConverterBase { get; set; } public Type DeclaredPropertyType { get; private set; } public bool HasGetter { get; set; } public bool HasSetter { get; set; } public bool IgnoreDefaultValuesOnRead { get; private set; } public bool IgnoreDefaultValuesOnWrite { get; private set; } public bool IsForClassInfo { get; protected set; } public string NameAsString { get; private set; } protected JsonSerializerOptions Options { get; set; } public Type ParentClassType { get; private set; } public MemberInfo MemberInfo { get; private set; } public JsonClassInfo RuntimeClassInfo { get { if (_runtimeClassInfo == null) { _runtimeClassInfo = Options.GetOrAddClass(RuntimePropertyType); } return _runtimeClassInfo; } } public Type RuntimePropertyType { get; private set; } public bool ShouldSerialize { get; private set; } public bool ShouldDeserialize { get; private set; } public bool IsIgnored { get; private set; } public JsonNumberHandling? NumberHandling { get; private set; } public bool PropertyTypeCanBeNull { get; protected set; } public static JsonPropertyInfo GetPropertyPlaceholder() { JsonPropertyInfo jsonPropertyInfo = new JsonPropertyInfo(); jsonPropertyInfo.NameAsString = string.Empty; return jsonPropertyInfo; } public static JsonPropertyInfo CreateIgnoredPropertyPlaceholder(MemberInfo memberInfo, JsonSerializerOptions options) { JsonPropertyInfo jsonPropertyInfo = new JsonPropertyInfo(); jsonPropertyInfo.Options = options; jsonPropertyInfo.MemberInfo = memberInfo; jsonPropertyInfo.DeterminePropertyName(); jsonPropertyInfo.IsIgnored = true; return jsonPropertyInfo; } public virtual void GetPolicies(JsonIgnoreCondition? ignoreCondition, JsonNumberHandling? parentTypeNumberHandling, bool defaultValueIsNull) { DetermineSerializationCapabilities(ignoreCondition); DeterminePropertyName(); DetermineIgnoreCondition(ignoreCondition, defaultValueIsNull); DetermineNumberHandling(parentTypeNumberHandling); } private void DeterminePropertyName() { if (MemberInfo == null) { return; } JsonPropertyNameAttribute attribute = GetAttribute(MemberInfo); if (attribute != null) { string name = attribute.Name; if (name == null) { ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameNull(ParentClassType, this); } NameAsString = name; } else if (Options.PropertyNamingPolicy != null) { string text = Options.PropertyNamingPolicy.ConvertName(MemberInfo.Name); if (text == null) { ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameNull(ParentClassType, this); } NameAsString = text; } else { NameAsString = MemberInfo.Name; } NameAsUtf8Bytes = Encoding.UTF8.GetBytes(NameAsString); EscapedNameSection = JsonHelpers.GetEscapedPropertyNameSection(NameAsUtf8Bytes, Options.Encoder); } private void DetermineSerializationCapabilities(JsonIgnoreCondition? ignoreCondition) { if ((ClassType & (ClassType)24) == 0) { bool flag = ignoreCondition.HasValue || ((MemberInfo is PropertyInfo) ? (!Options.IgnoreReadOnlyProperties) : (!Options.IgnoreReadOnlyFields)); ShouldSerialize = HasGetter && (HasSetter || flag); ShouldDeserialize = HasSetter; } else if (HasGetter) { ShouldSerialize = true; if (HasSetter) { ShouldDeserialize = true; } } } private void DetermineIgnoreCondition(JsonIgnoreCondition? ignoreCondition, bool defaultValueIsNull) { if (ignoreCondition.HasValue) { if (ignoreCondition == JsonIgnoreCondition.WhenWritingDefault) { IgnoreDefaultValuesOnWrite = true; } else if (ignoreCondition == JsonIgnoreCondition.WhenWritingNull) { if (defaultValueIsNull) { IgnoreDefaultValuesOnWrite = true; } else { ThrowHelper.ThrowInvalidOperationException_IgnoreConditionOnValueTypeInvalid(this); } } } else if (Options.IgnoreNullValues) { if (defaultValueIsNull) { IgnoreDefaultValuesOnRead = true; IgnoreDefaultValuesOnWrite = true; } } else if (Options.DefaultIgnoreCondition == JsonIgnoreCondition.WhenWritingNull) { if (defaultValueIsNull) { IgnoreDefaultValuesOnWrite = true; } } else if (Options.DefaultIgnoreCondition == JsonIgnoreCondition.WhenWritingDefault) { IgnoreDefaultValuesOnWrite = true; } } private void DetermineNumberHandling(JsonNumberHandling? parentTypeNumberHandling) { if (IsForClassInfo) { if (parentTypeNumberHandling.HasValue && !ConverterBase.IsInternalConverter) { ThrowHelper.ThrowInvalidOperationException_NumberHandlingOnPropertyInvalid(this); } NumberHandling = parentTypeNumberHandling; if (!NumberHandling.HasValue && Options.NumberHandling != 0) { NumberHandling = Options.NumberHandling; } return; } JsonNumberHandling? jsonNumberHandling = null; if (MemberInfo != null) { JsonNumberHandlingAttribute attribute = GetAttribute(MemberInfo); if (attribute != null && !ConverterBase.IsInternalConverterForNumberType && ((ClassType)24 & ClassType) == 0) { ThrowHelper.ThrowInvalidOperationException_NumberHandlingOnPropertyInvalid(this); } jsonNumberHandling = attribute?.Handling; } JsonNumberHandling? jsonNumberHandling2 = jsonNumberHandling; if (!jsonNumberHandling2.HasValue) { jsonNumberHandling = parentTypeNumberHandling; } if (!jsonNumberHandling.HasValue && Options.NumberHandling != 0) { jsonNumberHandling = Options.NumberHandling; } NumberHandling = jsonNumberHandling; } public static TAttribute GetAttribute(MemberInfo memberInfo) where TAttribute : Attribute { return (TAttribute)memberInfo.GetCustomAttribute(typeof(TAttribute), inherit: false); } public abstract bool GetMemberAndWriteJson(object obj, ref WriteStack state, Utf8JsonWriter writer); public abstract bool GetMemberAndWriteJsonExtensionData(object obj, ref WriteStack state, Utf8JsonWriter writer); public abstract object GetValueAsObject(object obj); public virtual void Initialize(Type parentClassType, Type declaredPropertyType, Type runtimePropertyType, ClassType runtimeClassType, MemberInfo memberInfo, JsonConverter converter, JsonIgnoreCondition? ignoreCondition, JsonNumberHandling? parentTypeNumberHandling, JsonSerializerOptions options) { ParentClassType = parentClassType; DeclaredPropertyType = declaredPropertyType; RuntimePropertyType = runtimePropertyType; ClassType = runtimeClassType; MemberInfo = memberInfo; ConverterBase = converter; Options = options; } public bool ReadJsonAndAddExtensionProperty(object obj, ref ReadStack state, ref Utf8JsonReader reader) { object valueAsObject = GetValueAsObject(obj); if (valueAsObject is IDictionary dictionary) { if (reader.TokenType == JsonTokenType.Null) { dictionary[state.Current.JsonPropertyNameAsString] = null; } else { JsonConverter jsonConverter = (JsonConverter)Options.GetConverter(JsonClassInfo.ObjectType); if (!jsonConverter.TryRead(ref reader, typeof(JsonElement), Options, ref state, out var value)) { return false; } dictionary[state.Current.JsonPropertyNameAsString] = value; } } else { IDictionary dictionary2 = (IDictionary)valueAsObject; JsonConverter jsonConverter2 = (JsonConverter)Options.GetConverter(typeof(JsonElement)); if (!jsonConverter2.TryRead(ref reader, typeof(JsonElement), Options, ref state, out var value2)) { return false; } dictionary2[state.Current.JsonPropertyNameAsString] = value2; } return true; } public abstract bool ReadJsonAndSetMember(object obj, ref ReadStack state, ref Utf8JsonReader reader); public abstract bool ReadJsonAsObject(ref ReadStack state, ref Utf8JsonReader reader, out object value); public bool ReadJsonExtensionDataValue(ref ReadStack state, ref Utf8JsonReader reader, out object value) { if (RuntimeClassInfo.ElementType == JsonClassInfo.ObjectType && reader.TokenType == JsonTokenType.Null) { value = null; return true; } JsonConverter jsonConverter = (JsonConverter)Options.GetConverter(typeof(JsonElement)); if (!jsonConverter.TryRead(ref reader, typeof(JsonElement), Options, ref state, out var value2)) { value = null; return false; } value = value2; return true; } public abstract void SetExtensionDictionaryAsObject(object obj, object extensionDict); } internal sealed class JsonPropertyInfo : JsonPropertyInfo { private bool _converterIsExternalAndPolymorphic; public Func Get { get; private set; } public Action Set { get; private set; } public JsonConverter Converter { get; internal set; } public override JsonConverter ConverterBase { get { return Converter; } set { Converter = (JsonConverter)value; } } public override void Initialize(Type parentClassType, Type declaredPropertyType, Type runtimePropertyType, ClassType runtimeClassType, MemberInfo memberInfo, JsonConverter converter, JsonIgnoreCondition? ignoreCondition, JsonNumberHandling? parentTypeNumberHandling, JsonSerializerOptions options) { base.Initialize(parentClassType, declaredPropertyType, runtimePropertyType, runtimeClassType, memberInfo, converter, ignoreCondition, parentTypeNumberHandling, options); if (!(memberInfo is PropertyInfo propertyInfo)) { if (memberInfo is FieldInfo fieldInfo) { base.HasGetter = true; Get = options.MemberAccessorStrategy.CreateFieldGetter(fieldInfo); if (!fieldInfo.IsInitOnly) { base.HasSetter = true; Set = options.MemberAccessorStrategy.CreateFieldSetter(fieldInfo); } } else { base.IsForClassInfo = true; base.HasGetter = true; base.HasSetter = true; } } else { bool flag = JsonPropertyInfo.GetAttribute(propertyInfo) != null; MethodInfo getMethod = propertyInfo.GetMethod; if (getMethod != null && (getMethod.IsPublic || flag)) { base.HasGetter = true; Get = options.MemberAccessorStrategy.CreatePropertyGetter(propertyInfo); } MethodInfo setMethod = propertyInfo.SetMethod; if (setMethod != null && (setMethod.IsPublic || flag)) { base.HasSetter = true; Set = options.MemberAccessorStrategy.CreatePropertySetter(propertyInfo); } } _converterIsExternalAndPolymorphic = !converter.IsInternalConverter && base.DeclaredPropertyType != converter.TypeToConvert; base.PropertyTypeCanBeNull = !base.DeclaredPropertyType.IsValueType || (base.DeclaredPropertyType.IsGenericType && base.DeclaredPropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)); GetPolicies(ignoreCondition, parentTypeNumberHandling, Converter.CanBeNull); } public override object GetValueAsObject(object obj) { if (base.IsForClassInfo) { return obj; } return Get(obj); } public override bool GetMemberAndWriteJson(object obj, ref WriteStack state, Utf8JsonWriter writer) { T value = Get(obj); if (base.IgnoreDefaultValuesOnWrite && ((default(T) == null) ? (value == null) : EqualityComparer.Default.Equals(default(T), value))) { return true; } if (value == null) { if (Converter.HandleNullOnWrite) { if ((int)state.Current.PropertyState < 2) { state.Current.PropertyState = StackFramePropertyState.Name; writer.WritePropertyNameSection(EscapedNameSection); } int currentDepth = writer.CurrentDepth; Converter.Write(writer, value, base.Options); if (currentDepth != writer.CurrentDepth) { ThrowHelper.ThrowJsonException_SerializationConverterWrite(Converter); } } else { writer.WriteNullSection(EscapedNameSection); } return true; } if ((int)state.Current.PropertyState < 2) { state.Current.PropertyState = StackFramePropertyState.Name; writer.WritePropertyNameSection(EscapedNameSection); } return Converter.TryWrite(writer, in value, base.Options, ref state); } public override bool GetMemberAndWriteJsonExtensionData(object obj, ref WriteStack state, Utf8JsonWriter writer) { T val = Get(obj); if (val == null) { return true; } return Converter.TryWriteDataExtensionProperty(writer, val, base.Options, ref state); } public override bool ReadJsonAndSetMember(object obj, ref ReadStack state, ref Utf8JsonReader reader) { bool flag = reader.TokenType == JsonTokenType.Null; bool flag2; if (flag && !Converter.HandleNullOnRead && !state.IsContinuation) { if (!Converter.CanBeNull) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Converter.TypeToConvert); } if (!base.IgnoreDefaultValuesOnRead) { Set(obj, default(T)); } flag2 = true; } else if (Converter.CanUseDirectReadOrWrite && !state.Current.NumberHandling.HasValue) { if (!flag || !base.IgnoreDefaultValuesOnRead || !Converter.CanBeNull) { T arg = Converter.Read(ref reader, base.RuntimePropertyType, base.Options); Set(obj, arg); } flag2 = true; } else { flag2 = true; if (!flag || !base.IgnoreDefaultValuesOnRead || !Converter.CanBeNull || state.IsContinuation) { flag2 = Converter.TryRead(ref reader, base.RuntimePropertyType, base.Options, ref state, out var value); if (flag2) { if (_converterIsExternalAndPolymorphic) { if (value != null) { Type type = value.GetType(); if (!base.DeclaredPropertyType.IsAssignableFrom(type)) { ThrowHelper.ThrowInvalidCastException_DeserializeUnableToAssignValue(type, base.DeclaredPropertyType); } } else if (base.DeclaredPropertyType.IsValueType && !base.DeclaredPropertyType.IsNullableValueType()) { ThrowHelper.ThrowInvalidOperationException_DeserializeUnableToAssignNull(base.DeclaredPropertyType); } } Set(obj, value); } } } return flag2; } public override bool ReadJsonAsObject(ref ReadStack state, ref Utf8JsonReader reader, out object value) { bool result; if (reader.TokenType == JsonTokenType.Null && !Converter.HandleNullOnRead && !state.IsContinuation) { if (!Converter.CanBeNull) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Converter.TypeToConvert); } value = default(T); result = true; } else if (Converter.CanUseDirectReadOrWrite && !state.Current.NumberHandling.HasValue) { value = Converter.Read(ref reader, base.RuntimePropertyType, base.Options); result = true; } else { result = Converter.TryRead(ref reader, base.RuntimePropertyType, base.Options, ref state, out var value2); value = value2; } return result; } public override void SetExtensionDictionaryAsObject(object obj, object extensionDict) { T arg = (T)extensionDict; Set(obj, arg); } } internal static class JsonSerializer { internal static readonly byte[] s_idPropertyName = new byte[3] { 36, 105, 100 }; internal static readonly byte[] s_refPropertyName = new byte[4] { 36, 114, 101, 102 }; internal static readonly byte[] s_valuesPropertyName = new byte[7] { 36, 118, 97, 108, 117, 101, 115 }; private const DynamicallyAccessedMemberTypes MembersAccessedOnRead = DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties; internal static readonly JsonEncodedText s_metadataId = JsonEncodedText.Encode("$id"); internal static readonly JsonEncodedText s_metadataRef = JsonEncodedText.Encode("$ref"); internal static readonly JsonEncodedText s_metadataValues = JsonEncodedText.Encode("$values"); private const DynamicallyAccessedMemberTypes MembersAccessedOnWrite = DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties; internal static bool IsValidNumberHandlingValue(JsonNumberHandling handling) { return JsonHelpers.IsInRangeInclusive((int)handling, 0, 7); } internal static bool ResolveMetadataForJsonObject(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) where T : notnull { JsonConverter converterBase = state.Current.JsonClassInfo.PropertyInfoForClassInfo.ConverterBase; if ((int)state.Current.ObjectState < 2 && !TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadNameOrEndObject)) { return false; } if (state.Current.ObjectState == StackFrameObjectState.ReadNameOrEndObject) { if (reader.TokenType != JsonTokenType.PropertyName) { state.Current.ObjectState = StackFrameObjectState.PropertyValue; state.Current.PropertyState = StackFramePropertyState.ReadName; return true; } ReadOnlySpan span = reader.GetSpan(); switch (GetMetadataPropertyName(span)) { case MetadataPropertyName.Id: state.Current.JsonPropertyName = s_idPropertyName; if (!converterBase.CanHaveIdMetadata) { ThrowHelper.ThrowJsonException_MetadataCannotParsePreservedObjectIntoImmutable(converterBase.TypeToConvert); } state.Current.ObjectState = StackFrameObjectState.ReadAheadIdValue; break; case MetadataPropertyName.Ref: state.Current.JsonPropertyName = s_refPropertyName; if (converterBase.IsValueType) { ThrowHelper.ThrowJsonException_MetadataInvalidReferenceToValueType(converterBase.TypeToConvert); } state.Current.ObjectState = StackFrameObjectState.ReadAheadRefValue; break; case MetadataPropertyName.Values: ThrowHelper.ThrowJsonException_MetadataInvalidPropertyWithLeadingDollarSign(span, ref state, in reader); break; default: state.Current.ObjectState = StackFrameObjectState.PropertyValue; state.Current.PropertyState = StackFramePropertyState.ReadName; return true; } } if (state.Current.ObjectState == StackFrameObjectState.ReadAheadRefValue) { if (!TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadRefValue)) { return false; } } else if (state.Current.ObjectState == StackFrameObjectState.ReadAheadIdValue && !TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadIdValue)) { return false; } if (state.Current.ObjectState == StackFrameObjectState.ReadRefValue) { if (reader.TokenType != JsonTokenType.String) { ThrowHelper.ThrowJsonException_MetadataValueWasNotString(reader.TokenType); } string @string = reader.GetString(); object obj = state.ReferenceResolver.ResolveReference(@string); ValidateValueIsCorrectType(obj, @string); state.Current.ReturnValue = obj; state.Current.ObjectState = StackFrameObjectState.ReadAheadRefEndObject; } else if (state.Current.ObjectState == StackFrameObjectState.ReadIdValue) { if (reader.TokenType != JsonTokenType.String) { ThrowHelper.ThrowJsonException_MetadataValueWasNotString(reader.TokenType); } converterBase.CreateInstanceForReferenceResolver(ref reader, ref state, options); string string2 = reader.GetString(); state.ReferenceResolver.AddReference(string2, state.Current.ReturnValue); state.Current.ObjectState = StackFrameObjectState.CreatedObject; } state.Current.JsonPropertyName = null; if (state.Current.ObjectState == StackFrameObjectState.ReadAheadRefEndObject && !TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadRefEndObject)) { return false; } if (state.Current.ObjectState == StackFrameObjectState.ReadRefEndObject && reader.TokenType != JsonTokenType.EndObject) { ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(reader.GetSpan(), ref state); } return true; } internal static bool ResolveMetadataForJsonArray(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) where T : notnull { JsonConverter converterBase = state.Current.JsonClassInfo.PropertyInfoForClassInfo.ConverterBase; if ((int)state.Current.ObjectState < 2 && !TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadNameOrEndObject)) { return false; } if (state.Current.ObjectState == StackFrameObjectState.ReadNameOrEndObject) { if (reader.TokenType != JsonTokenType.PropertyName) { ThrowHelper.ThrowJsonException_MetadataPreservedArrayValuesNotFound(ref state, converterBase.TypeToConvert); } ReadOnlySpan span = reader.GetSpan(); switch (GetMetadataPropertyName(span)) { case MetadataPropertyName.Id: state.Current.JsonPropertyName = s_idPropertyName; if (!converterBase.CanHaveIdMetadata) { ThrowHelper.ThrowJsonException_MetadataCannotParsePreservedObjectIntoImmutable(converterBase.TypeToConvert); } state.Current.ObjectState = StackFrameObjectState.ReadAheadIdValue; break; case MetadataPropertyName.Ref: state.Current.JsonPropertyName = s_refPropertyName; if (converterBase.IsValueType) { ThrowHelper.ThrowJsonException_MetadataInvalidReferenceToValueType(converterBase.TypeToConvert); } state.Current.ObjectState = StackFrameObjectState.ReadAheadRefValue; break; case MetadataPropertyName.Values: ThrowHelper.ThrowJsonException_MetadataMissingIdBeforeValues(ref state, span); break; default: ThrowHelper.ThrowJsonException_MetadataPreservedArrayInvalidProperty(ref state, converterBase.TypeToConvert, in reader); break; } } if (state.Current.ObjectState == StackFrameObjectState.ReadAheadRefValue) { if (!TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadRefValue)) { return false; } } else if (state.Current.ObjectState == StackFrameObjectState.ReadAheadIdValue && !TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadIdValue)) { return false; } if (state.Current.ObjectState == StackFrameObjectState.ReadRefValue) { if (reader.TokenType != JsonTokenType.String) { ThrowHelper.ThrowJsonException_MetadataValueWasNotString(reader.TokenType); } string @string = reader.GetString(); object obj = state.ReferenceResolver.ResolveReference(@string); ValidateValueIsCorrectType(obj, @string); state.Current.ReturnValue = obj; state.Current.ObjectState = StackFrameObjectState.ReadAheadRefEndObject; } else if (state.Current.ObjectState == StackFrameObjectState.ReadIdValue) { if (reader.TokenType != JsonTokenType.String) { ThrowHelper.ThrowJsonException_MetadataValueWasNotString(reader.TokenType); } converterBase.CreateInstanceForReferenceResolver(ref reader, ref state, options); string string2 = reader.GetString(); state.ReferenceResolver.AddReference(string2, state.Current.ReturnValue); state.Current.ObjectState = StackFrameObjectState.ReadAheadValuesName; } state.Current.JsonPropertyName = null; if (state.Current.ObjectState == StackFrameObjectState.ReadAheadRefEndObject && !TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadRefEndObject)) { return false; } if (state.Current.ObjectState == StackFrameObjectState.ReadRefEndObject) { if (reader.TokenType != JsonTokenType.EndObject) { ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(reader.GetSpan(), ref state); } return true; } if (state.Current.ObjectState == StackFrameObjectState.ReadAheadValuesName && !TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadValuesName)) { return false; } if (state.Current.ObjectState == StackFrameObjectState.ReadValuesName) { if (reader.TokenType != JsonTokenType.PropertyName) { ThrowHelper.ThrowJsonException_MetadataPreservedArrayValuesNotFound(ref state, converterBase.TypeToConvert); } ReadOnlySpan span2 = reader.GetSpan(); if (GetMetadataPropertyName(span2) != MetadataPropertyName.Values) { ThrowHelper.ThrowJsonException_MetadataPreservedArrayInvalidProperty(ref state, converterBase.TypeToConvert, in reader); } state.Current.JsonPropertyName = s_valuesPropertyName; state.Current.ObjectState = StackFrameObjectState.ReadAheadValuesStartArray; } if (state.Current.ObjectState == StackFrameObjectState.ReadAheadValuesStartArray && !TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadValuesStartArray)) { return false; } if (state.Current.ObjectState == StackFrameObjectState.ReadValuesStartArray) { if (reader.TokenType != JsonTokenType.StartArray) { ThrowHelper.ThrowJsonException_MetadataValuesInvalidToken(reader.TokenType); } state.Current.ValidateEndTokenOnArray = true; state.Current.ObjectState = StackFrameObjectState.CreatedObject; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryReadAheadMetadataAndSetState(ref Utf8JsonReader reader, ref ReadStack state, StackFrameObjectState nextState) { state.Current.ObjectState = nextState; return reader.Read(); } internal static MetadataPropertyName GetMetadataPropertyName(ReadOnlySpan propertyName) { if (propertyName.Length > 0 && propertyName[0] == 36) { switch (propertyName.Length) { case 3: if (propertyName[1] == 105 && propertyName[2] == 100) { return MetadataPropertyName.Id; } break; case 4: if (propertyName[1] == 114 && propertyName[2] == 101 && propertyName[3] == 102) { return MetadataPropertyName.Ref; } break; case 7: if (propertyName[1] == 118 && propertyName[2] == 97 && propertyName[3] == 108 && propertyName[4] == 117 && propertyName[5] == 101 && propertyName[6] == 115) { return MetadataPropertyName.Values; } break; } } return MetadataPropertyName.NoMetadata; } internal static bool TryGetReferenceFromJsonElement(ref ReadStack state, JsonElement element, out object referenceValue) { bool flag = false; referenceValue = null; if (element.ValueKind == JsonValueKind.Object) { int num = 0; foreach (JsonProperty item in element.EnumerateObject()) { num++; if (flag) { ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(); } else if (item.EscapedNameEquals(s_refPropertyName)) { if (num > 1) { ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(); } if (item.Value.ValueKind != JsonValueKind.String) { ThrowHelper.ThrowJsonException_MetadataValueWasNotString(item.Value.ValueKind); } referenceValue = state.ReferenceResolver.ResolveReference(item.Value.GetString()); flag = true; } } } return flag; } private static void ValidateValueIsCorrectType(object value, string referenceId) where T : notnull { try { T val = (T)value; } catch (InvalidCastException) { ThrowHelper.ThrowInvalidOperationException_MetadataReferenceOfTypeCannotBeAssignedToType(referenceId, value.GetType(), typeof(T)); throw; } } internal static JsonPropertyInfo LookupProperty(object obj, ReadOnlySpan unescapedPropertyName, ref ReadStack state, out bool useExtensionProperty, bool createExtensionProperty = true) { useExtensionProperty = false; byte[] utf8PropertyName; JsonPropertyInfo jsonPropertyInfo = state.Current.JsonClassInfo.GetProperty(unescapedPropertyName, ref state.Current, out utf8PropertyName); state.Current.PropertyIndex++; state.Current.JsonPropertyName = utf8PropertyName; if (jsonPropertyInfo == JsonPropertyInfo.s_missingProperty) { JsonPropertyInfo dataExtensionProperty = state.Current.JsonClassInfo.DataExtensionProperty; if (dataExtensionProperty != null && dataExtensionProperty.HasGetter && dataExtensionProperty.HasSetter) { state.Current.JsonPropertyNameAsString = JsonHelpers.Utf8GetString(unescapedPropertyName); if (createExtensionProperty) { CreateDataExtensionProperty(obj, dataExtensionProperty); } jsonPropertyInfo = dataExtensionProperty; useExtensionProperty = true; } } state.Current.JsonPropertyInfo = jsonPropertyInfo; state.Current.NumberHandling = jsonPropertyInfo.NumberHandling; return jsonPropertyInfo; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static ReadOnlySpan GetPropertyName(ref ReadStack state, ref Utf8JsonReader reader, JsonSerializerOptions options) { ReadOnlySpan span = reader.GetSpan(); ReadOnlySpan result; if (reader._stringHasEscaping) { int idx = span.IndexOf(92); result = JsonReaderHelper.GetUnescapedSpan(span, idx); } else { result = span; } if (options.ReferenceHandler != null && span.Length > 0 && span[0] == 36) { ThrowHelper.ThrowUnexpectedMetadataException(span, ref reader, ref state); } return result; } internal static void CreateDataExtensionProperty(object obj, JsonPropertyInfo jsonPropertyInfo) { object valueAsObject = jsonPropertyInfo.GetValueAsObject(obj); if (valueAsObject == null) { if (jsonPropertyInfo.RuntimeClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(jsonPropertyInfo.DeclaredPropertyType); } valueAsObject = jsonPropertyInfo.RuntimeClassInfo.CreateObject(); jsonPropertyInfo.SetExtensionDictionaryAsObject(obj, valueAsObject); } } private static TValue ReadCore(ref Utf8JsonReader reader, Type returnType, JsonSerializerOptions options) where TValue : notnull { ReadStack state = default(ReadStack); state.Initialize(returnType, options, supportContinuation: false); JsonConverter converterBase = state.Current.JsonPropertyInfo.ConverterBase; return ReadCore(converterBase, ref reader, options, ref state); } private static TValue ReadCore(JsonConverter jsonConverter, ref Utf8JsonReader reader, JsonSerializerOptions options, ref ReadStack state) where TValue : notnull { if (jsonConverter is JsonConverter jsonConverter2) { return jsonConverter2.ReadCore(ref reader, options, ref state); } object obj = jsonConverter.ReadCoreAsObject(ref reader, options, ref state); return (TValue)obj; } public static TValue? Deserialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(ReadOnlySpan utf8Json, JsonSerializerOptions? options = null) { if (options == null) { options = JsonSerializerOptions.s_defaultOptions; } JsonReaderState state = new JsonReaderState(options.GetReaderOptions()); Utf8JsonReader reader = new Utf8JsonReader(utf8Json, isFinalBlock: true, state); return ReadCore(ref reader, typeof(TValue), options); } public static object? Deserialize(ReadOnlySpan utf8Json, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] Type returnType, JsonSerializerOptions? options = null) { if (returnType == null) { throw new ArgumentNullException("returnType"); } if (options == null) { options = JsonSerializerOptions.s_defaultOptions; } JsonReaderState state = new JsonReaderState(options.GetReaderOptions()); Utf8JsonReader reader = new Utf8JsonReader(utf8Json, isFinalBlock: true, state); return ReadCore(ref reader, returnType, options); } public static ValueTask DeserializeAsync<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(Stream utf8Json, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { if (utf8Json == null) { throw new ArgumentNullException("utf8Json"); } return ReadAsync(utf8Json, typeof(TValue), options, cancellationToken); } public static ValueTask DeserializeAsync(Stream utf8Json, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] Type returnType, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { if (utf8Json == null) { throw new ArgumentNullException("utf8Json"); } if (returnType == null) { throw new ArgumentNullException("returnType"); } return ReadAsync(utf8Json, returnType, options, cancellationToken); } private static async ValueTask ReadAsync(Stream utf8Json, Type returnType, JsonSerializerOptions options, CancellationToken cancellationToken) where TValue : notnull { if (options == null) { options = JsonSerializerOptions.s_defaultOptions; } ReadStack state = default(ReadStack); state.Initialize(returnType, options, supportContinuation: true); JsonConverter converter = state.Current.JsonPropertyInfo.ConverterBase; JsonReaderState readerState = new JsonReaderState(options.GetReaderOptions()); int utf8BomLength = JsonConstants.Utf8Bom.Length; byte[] buffer = ArrayPool.Shared.Rent(Math.Max(options.DefaultBufferSize, utf8BomLength)); int bytesInBuffer = 0; long totalBytesRead = 0L; int clearMax = 0; bool isFirstIteration = true; try { TValue result; while (true) { bool isFinalBlock = false; do { int num = await utf8Json.ReadAsync(buffer, bytesInBuffer, buffer.Length - bytesInBuffer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num == 0) { isFinalBlock = true; break; } totalBytesRead += num; bytesInBuffer += num; } while (bytesInBuffer != buffer.Length); if (bytesInBuffer > clearMax) { clearMax = bytesInBuffer; } int num2 = 0; if (isFirstIteration) { isFirstIteration = false; if (MemoryExtensions.AsSpan(buffer).StartsWith(JsonConstants.Utf8Bom)) { num2 += utf8BomLength; bytesInBuffer -= utf8BomLength; } } result = ReadCore(ref readerState, isFinalBlock, new ReadOnlySpan(buffer, num2, bytesInBuffer), options, ref state, converter); int num3 = checked((int)state.BytesConsumed); bytesInBuffer -= num3; if (isFinalBlock) { break; } if ((uint)bytesInBuffer > (uint)buffer.Length / 2u) { byte[] array = ArrayPool.Shared.Rent((buffer.Length < 1073741823) ? (buffer.Length * 2) : int.MaxValue); Buffer.BlockCopy(buffer, num3 + num2, array, 0, bytesInBuffer); new Span(buffer, 0, clearMax).Clear(); ArrayPool.Shared.Return(buffer); clearMax = bytesInBuffer; buffer = array; } else if (bytesInBuffer != 0) { Buffer.BlockCopy(buffer, num3 + num2, buffer, 0, bytesInBuffer); } } return result; } finally { new Span(buffer, 0, clearMax).Clear(); ArrayPool.Shared.Return(buffer); } } private static TValue ReadCore(ref JsonReaderState readerState, bool isFinalBlock, ReadOnlySpan buffer, JsonSerializerOptions options, ref ReadStack state, JsonConverter converterBase) where TValue : notnull { Utf8JsonReader reader = new Utf8JsonReader(buffer, isFinalBlock, readerState); state.ReadAhead = !isFinalBlock; state.BytesConsumed = 0L; TValue result = ReadCore(converterBase, ref reader, options, ref state); readerState = reader.CurrentState; return result; } public static TValue? Deserialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(string json, JsonSerializerOptions? options = null) { if (json == null) { throw new ArgumentNullException("json"); } return Deserialize(json, typeof(TValue), options); } public static object? Deserialize(string json, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] Type returnType, JsonSerializerOptions? options = null) { if (json == null) { throw new ArgumentNullException("json"); } if (returnType == null) { throw new ArgumentNullException("returnType"); } return Deserialize(json, returnType, options); } private static TValue Deserialize(string json, Type returnType, JsonSerializerOptions options) where TValue : notnull { if (options == null) { options = JsonSerializerOptions.s_defaultOptions; } byte[] array = null; Span span = (((long)json.Length > 349525L) ? new byte[JsonReaderHelper.GetUtf8ByteCount(MemoryExtensions.AsSpan(json))] : (array = ArrayPool.Shared.Rent(json.Length * 3))); try { span = span[..JsonReaderHelper.GetUtf8FromText(MemoryExtensions.AsSpan(json), span)]; Utf8JsonReader reader = new Utf8JsonReader(state: new JsonReaderState(options.GetReaderOptions()), jsonData: span, isFinalBlock: true); return ReadCore(ref reader, returnType, options); } finally { if (array != null) { span.Clear(); ArrayPool.Shared.Return(array); } } } public static TValue? Deserialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(ref Utf8JsonReader reader, JsonSerializerOptions? options = null) { if (options == null) { options = JsonSerializerOptions.s_defaultOptions; } ReadStack state = default(ReadStack); state.Initialize(typeof(TValue), options, supportContinuation: false); return ReadValueCore(options, ref reader, ref state); } public static object? Deserialize(ref Utf8JsonReader reader, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] Type returnType, JsonSerializerOptions? options = null) { if (returnType == null) { throw new ArgumentNullException("returnType"); } if (options == null) { options = JsonSerializerOptions.s_defaultOptions; } ReadStack state = default(ReadStack); state.Initialize(returnType, options, supportContinuation: false); return ReadValueCore(options, ref reader, ref state); } private static void CheckSupportedOptions(JsonReaderOptions readerOptions, string paramName) { if (readerOptions.CommentHandling == JsonCommentHandling.Allow) { throw new ArgumentException(System.SR.JsonSerializerDoesNotSupportComments, paramName); } } private static TValue ReadValueCore(JsonSerializerOptions options, ref Utf8JsonReader reader, ref ReadStack state) where TValue : notnull { JsonReaderState currentState = reader.CurrentState; CheckSupportedOptions(currentState.Options, "reader"); Utf8JsonReader utf8JsonReader = reader; ReadOnlySpan readOnlySpan = default(ReadOnlySpan); ReadOnlySequence source = default(ReadOnlySequence); try { JsonTokenType tokenType = reader.TokenType; ReadOnlySpan bytes; if ((tokenType == JsonTokenType.None || tokenType == JsonTokenType.PropertyName) && !reader.Read()) { bytes = default(ReadOnlySpan); ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.ExpectedOneCompleteToken, 0, bytes); } switch (reader.TokenType) { case JsonTokenType.StartObject: case JsonTokenType.StartArray: { long tokenStartIndex = reader.TokenStartIndex; if (!reader.TrySkip()) { bytes = default(ReadOnlySpan); ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.NotEnoughData, 0, bytes); } long num = reader.BytesConsumed - tokenStartIndex; ReadOnlySequence originalSequence = reader.OriginalSequence; if (originalSequence.IsEmpty) { bytes = reader.OriginalSpan; readOnlySpan = checked(bytes.Slice((int)tokenStartIndex, (int)num)); } else { source = originalSequence.Slice(tokenStartIndex, num); } break; } case JsonTokenType.Number: case JsonTokenType.True: case JsonTokenType.False: case JsonTokenType.Null: if (reader.HasValueSequence) { source = reader.ValueSequence; } else { readOnlySpan = reader.ValueSpan; } break; case JsonTokenType.String: { ReadOnlySequence originalSequence2 = reader.OriginalSequence; if (originalSequence2.IsEmpty) { bytes = reader.ValueSpan; int length = bytes.Length + 2; readOnlySpan = reader.OriginalSpan.Slice((int)reader.TokenStartIndex, length); break; } long num2 = 2L; if (reader.HasValueSequence) { num2 += reader.ValueSequence.Length; } else { long num3 = num2; bytes = reader.ValueSpan; num2 = num3 + bytes.Length; } source = originalSequence2.Slice(reader.TokenStartIndex, num2); break; } default: { byte b; if (reader.HasValueSequence) { bytes = reader.ValueSequence.First.Span; b = bytes[0]; } else { bytes = reader.ValueSpan; b = bytes[0]; } byte nextByte = b; bytes = default(ReadOnlySpan); ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.ExpectedStartOfValueNotFound, nextByte, bytes); break; } } } catch (JsonReaderException ex) { reader = utf8JsonReader; ThrowHelper.ReThrowWithPath(in state, ex); } int num4 = (readOnlySpan.IsEmpty ? checked((int)source.Length) : readOnlySpan.Length); byte[] array = ArrayPool.Shared.Rent(num4); Span span = MemoryExtensions.AsSpan(array, 0, num4); try { if (readOnlySpan.IsEmpty) { source.CopyTo(span); } else { readOnlySpan.CopyTo(span); } JsonReaderOptions options2 = currentState.Options; Utf8JsonReader reader2 = new Utf8JsonReader(span, options2); JsonConverter converterBase = state.Current.JsonPropertyInfo.ConverterBase; return ReadCore(converterBase, ref reader2, options, ref state); } catch (JsonException) { reader = utf8JsonReader; throw; } finally { span.Clear(); ArrayPool.Shared.Return(array); } } public static byte[] SerializeToUtf8Bytes<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(TValue value, JsonSerializerOptions? options = null) { return WriteCoreBytes(in value, typeof(TValue), options); } public static byte[] SerializeToUtf8Bytes(object? value, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] Type inputType, JsonSerializerOptions? options = null) { if (inputType == null) { throw new ArgumentNullException("inputType"); } if (value != null && !inputType.IsAssignableFrom(value.GetType())) { ThrowHelper.ThrowArgumentException_DeserializeWrongType(inputType, value); } return WriteCoreBytes(in value, inputType, options); } private static byte[] WriteCoreBytes(in TValue value, Type inputType, JsonSerializerOptions options) where TValue : notnull { if (options == null) { options = JsonSerializerOptions.s_defaultOptions; } using PooledByteBufferWriter pooledByteBufferWriter = new PooledByteBufferWriter(options.DefaultBufferSize); using (Utf8JsonWriter writer = new Utf8JsonWriter(pooledByteBufferWriter, options.GetWriterOptions())) { WriteCore(writer, in value, inputType, options); } return pooledByteBufferWriter.WrittenMemory.ToArray(); } internal static MetadataPropertyName WriteReferenceForObject(JsonConverter jsonConverter, object currentValue, ref WriteStack state, Utf8JsonWriter writer) { if (!jsonConverter.CanHaveIdMetadata || jsonConverter.IsValueType) { return MetadataPropertyName.NoMetadata; } bool alreadyExists; string reference = state.ReferenceResolver.GetReference(currentValue, out alreadyExists); if (alreadyExists) { writer.WriteString(s_metadataRef, reference); writer.WriteEndObject(); return MetadataPropertyName.Ref; } writer.WriteString(s_metadataId, reference); return MetadataPropertyName.Id; } internal static MetadataPropertyName WriteReferenceForCollection(JsonConverter jsonConverter, object currentValue, ref WriteStack state, Utf8JsonWriter writer) { if (!jsonConverter.CanHaveIdMetadata || jsonConverter.IsValueType) { writer.WriteStartArray(); return MetadataPropertyName.NoMetadata; } bool alreadyExists; string reference = state.ReferenceResolver.GetReference(currentValue, out alreadyExists); if (alreadyExists) { writer.WriteStartObject(); writer.WriteString(s_metadataRef, reference); writer.WriteEndObject(); return MetadataPropertyName.Ref; } writer.WriteStartObject(); writer.WriteString(s_metadataId, reference); writer.WriteStartArray(s_metadataValues); return MetadataPropertyName.Id; } private static void WriteCore(Utf8JsonWriter writer, in TValue value, Type inputType, JsonSerializerOptions options) where TValue : notnull { if (value != null && inputType == JsonClassInfo.ObjectType) { inputType = value.GetType(); } WriteStack state = default(WriteStack); JsonConverter jsonConverter = state.Initialize(inputType, options, supportContinuation: false); bool flag = WriteCore(jsonConverter, writer, in value, options, ref state); } private static bool WriteCore(JsonConverter jsonConverter, Utf8JsonWriter writer, in TValue value, JsonSerializerOptions options, ref WriteStack state) where TValue : notnull { bool result = ((!(jsonConverter is JsonConverter jsonConverter2)) ? jsonConverter.WriteCoreAsObject(writer, value, options, ref state) : jsonConverter2.WriteCore(writer, in value, options, ref state)); writer.Flush(); return result; } public static Task SerializeAsync<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(Stream utf8Json, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { if (utf8Json == null) { throw new ArgumentNullException("utf8Json"); } return WriteAsyncCore(utf8Json, value, typeof(TValue), options, cancellationToken); } public static Task SerializeAsync(Stream utf8Json, object? value, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] Type inputType, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { if (utf8Json == null) { throw new ArgumentNullException("utf8Json"); } if (inputType == null) { throw new ArgumentNullException("inputType"); } if (value != null && !inputType.IsAssignableFrom(value.GetType())) { ThrowHelper.ThrowArgumentException_DeserializeWrongType(inputType, value); } return WriteAsyncCore(utf8Json, value, inputType, options, cancellationToken); } private static async Task WriteAsyncCore(Stream utf8Json, TValue value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken) where TValue : notnull { if (options == null) { options = JsonSerializerOptions.s_defaultOptions; } JsonWriterOptions writerOptions = options.GetWriterOptions(); using PooledByteBufferWriter bufferWriter = new PooledByteBufferWriter(options.DefaultBufferSize); using Utf8JsonWriter writer = new Utf8JsonWriter(bufferWriter, writerOptions); if (inputType == JsonClassInfo.ObjectType && value != null) { inputType = value.GetType(); } WriteStack state = default(WriteStack); JsonConverter converterBase = state.Initialize(inputType, options, supportContinuation: true); bool isFinalBlock; do { state.FlushThreshold = (int)((float)bufferWriter.Capacity * 0.9f); isFinalBlock = WriteCore(converterBase, writer, in value, options, ref state); await bufferWriter.WriteToStreamAsync(utf8Json, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); bufferWriter.Clear(); } while (!isFinalBlock); } public static string Serialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(TValue value, JsonSerializerOptions? options = null) { return Serialize(in value, typeof(TValue), options); } public static string Serialize(object? value, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] Type inputType, JsonSerializerOptions? options = null) { if (inputType == null) { throw new ArgumentNullException("inputType"); } if (value != null && !inputType.IsAssignableFrom(value.GetType())) { ThrowHelper.ThrowArgumentException_DeserializeWrongType(inputType, value); } return Serialize(in value, inputType, options); } private static string Serialize(in TValue value, Type inputType, JsonSerializerOptions options) where TValue : notnull { if (options == null) { options = JsonSerializerOptions.s_defaultOptions; } using PooledByteBufferWriter pooledByteBufferWriter = new PooledByteBufferWriter(options.DefaultBufferSize); using (Utf8JsonWriter writer = new Utf8JsonWriter(pooledByteBufferWriter, options.GetWriterOptions())) { WriteCore(writer, in value, inputType, options); } return JsonReaderHelper.TranscodeHelper(pooledByteBufferWriter.WrittenMemory.Span); } public static void Serialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(Utf8JsonWriter writer, TValue value, JsonSerializerOptions? options = null) { Serialize(writer, in value, typeof(TValue), options); } public static void Serialize(Utf8JsonWriter writer, object? value, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] Type inputType, JsonSerializerOptions? options = null) { if (inputType == null) { throw new ArgumentNullException("inputType"); } if (value != null && !inputType.IsAssignableFrom(value.GetType())) { ThrowHelper.ThrowArgumentException_DeserializeWrongType(inputType, value); } Serialize(writer, in value, inputType, options); } private static void Serialize(Utf8JsonWriter writer, in TValue value, Type type, JsonSerializerOptions options) where TValue : notnull { if (options == null) { options = JsonSerializerOptions.s_defaultOptions; } if (writer == null) { throw new ArgumentNullException("writer"); } WriteCore(writer, in value, type, options); } } internal enum JsonSerializerDefaults { General, Web } internal sealed class JsonSerializerOptions { private static readonly Dictionary? s_defaultSimpleConverters = GetDefaultSimpleConverters(); private static readonly JsonConverter?[]? s_defaultFactoryConverters = new JsonConverter[4] { new NullableConverterFactory(), new EnumConverterFactory(), new IEnumerableConverterFactory(), new ObjectConverterFactory() }; private readonly ConcurrentDictionary? _converters = new ConcurrentDictionary(); private ConcurrentDictionary? _dictionaryKeyConverters; internal const int BufferSizeDefault = 16384; internal static readonly JsonSerializerOptions? s_defaultOptions = new JsonSerializerOptions(); private readonly ConcurrentDictionary? _classes = new ConcurrentDictionary(); private MemberAccessor? _memberAccessorStrategy; private JsonNamingPolicy? _dictionaryKeyPolicy; private JsonNamingPolicy? _jsonPropertyNamingPolicy; private JsonCommentHandling _readCommentHandling; private ReferenceHandler? _referenceHandler; private JavaScriptEncoder? _encoder; private JsonIgnoreCondition _defaultIgnoreCondition; private JsonNumberHandling _numberHandling; private int _defaultBufferSize = 16384; private int _maxDepth; private bool _allowTrailingCommas; private bool _haveTypesBeenCreated; private bool _ignoreNullValues; private bool _ignoreReadOnlyProperties; private bool _ignoreReadonlyFields; private bool _includeFields; private bool _propertyNameCaseInsensitive; private bool _writeIndented; public IList Converters { get; } private JsonClassInfo? _lastClass { get; set; } public bool AllowTrailingCommas { get { return _allowTrailingCommas; } set { VerifyMutable(); _allowTrailingCommas = value; } } public int DefaultBufferSize { get { return _defaultBufferSize; } set { VerifyMutable(); if (value < 1) { throw new ArgumentException(System.SR.SerializationInvalidBufferSize); } _defaultBufferSize = value; } } public JavaScriptEncoder? Encoder { get { return _encoder; } set { VerifyMutable(); _encoder = value; } } public JsonNamingPolicy? DictionaryKeyPolicy { get { return _dictionaryKeyPolicy; } set { VerifyMutable(); _dictionaryKeyPolicy = value; } } [EditorBrowsable(EditorBrowsableState.Never)] public bool IgnoreNullValues { get { return _ignoreNullValues; } set { VerifyMutable(); if (value && _defaultIgnoreCondition != 0) { throw new InvalidOperationException(System.SR.DefaultIgnoreConditionAlreadySpecified); } _ignoreNullValues = value; } } public JsonIgnoreCondition DefaultIgnoreCondition { get { return _defaultIgnoreCondition; } set { VerifyMutable(); switch (value) { case JsonIgnoreCondition.Always: throw new ArgumentException(System.SR.DefaultIgnoreConditionInvalid); default: if (_ignoreNullValues) { throw new InvalidOperationException(System.SR.DefaultIgnoreConditionAlreadySpecified); } break; case JsonIgnoreCondition.Never: break; } _defaultIgnoreCondition = value; } } public JsonNumberHandling NumberHandling { get { return _numberHandling; } set { VerifyMutable(); if (!JsonSerializer.IsValidNumberHandlingValue(value)) { throw new ArgumentOutOfRangeException("value"); } _numberHandling = value; } } public bool IgnoreReadOnlyProperties { get { return _ignoreReadOnlyProperties; } set { VerifyMutable(); _ignoreReadOnlyProperties = value; } } public bool IgnoreReadOnlyFields { get { return _ignoreReadonlyFields; } set { VerifyMutable(); _ignoreReadonlyFields = value; } } public bool IncludeFields { get { return _includeFields; } set { VerifyMutable(); _includeFields = value; } } public int MaxDepth { get { return _maxDepth; } set { VerifyMutable(); if (value < 0) { throw ThrowHelper.GetArgumentOutOfRangeException_MaxDepthMustBePositive("value"); } _maxDepth = value; EffectiveMaxDepth = ((value == 0) ? 64 : value); } } internal int EffectiveMaxDepth { get; private set; } = 64; public JsonNamingPolicy? PropertyNamingPolicy { get { return _jsonPropertyNamingPolicy; } set { VerifyMutable(); _jsonPropertyNamingPolicy = value; } } public bool PropertyNameCaseInsensitive { get { return _propertyNameCaseInsensitive; } set { VerifyMutable(); _propertyNameCaseInsensitive = value; } } public JsonCommentHandling ReadCommentHandling { get { return _readCommentHandling; } set { VerifyMutable(); if ((int)value > 1) { throw new ArgumentOutOfRangeException("value", System.SR.JsonSerializerDoesNotSupportComments); } _readCommentHandling = value; } } public bool WriteIndented { get { return _writeIndented; } set { VerifyMutable(); _writeIndented = value; } } public ReferenceHandler? ReferenceHandler { get { return _referenceHandler; } set { VerifyMutable(); _referenceHandler = value; } } internal MemberAccessor MemberAccessorStrategy { get { if (_memberAccessorStrategy == null) { _memberAccessorStrategy = new ReflectionMemberAccessor(); } return _memberAccessorStrategy; } } private static Dictionary? GetDefaultSimpleConverters() { Dictionary? converters = new Dictionary(23); Add(new System.Text.Json.Serialization.Converters.BooleanConverter()); Add(new System.Text.Json.Serialization.Converters.ByteConverter()); Add(new ByteArrayConverter()); Add(new System.Text.Json.Serialization.Converters.CharConverter()); Add(new System.Text.Json.Serialization.Converters.DateTimeConverter()); Add(new System.Text.Json.Serialization.Converters.DateTimeOffsetConverter()); Add(new System.Text.Json.Serialization.Converters.DoubleConverter()); Add(new System.Text.Json.Serialization.Converters.DecimalConverter()); Add(new System.Text.Json.Serialization.Converters.GuidConverter()); Add(new System.Text.Json.Serialization.Converters.Int16Converter()); Add(new System.Text.Json.Serialization.Converters.Int32Converter()); Add(new System.Text.Json.Serialization.Converters.Int64Converter()); Add(new JsonElementConverter()); Add(new JsonDocumentConverter()); Add(new ObjectConverter()); Add(new System.Text.Json.Serialization.Converters.SByteConverter()); Add(new System.Text.Json.Serialization.Converters.SingleConverter()); Add(new System.Text.Json.Serialization.Converters.StringConverter()); Add(new System.Text.Json.Serialization.Converters.TypeConverter()); Add(new System.Text.Json.Serialization.Converters.UInt16Converter()); Add(new System.Text.Json.Serialization.Converters.UInt32Converter()); Add(new System.Text.Json.Serialization.Converters.UInt64Converter()); Add(new UriConverter()); return converters; void Add(JsonConverter? converter) { converters.Add(converter.TypeToConvert, converter); } } internal JsonConverter? GetDictionaryKeyConverter(Type? keyType) { JsonSerializerOptions? jsonSerializerOptions = this; if (_dictionaryKeyConverters == null) { _dictionaryKeyConverters = GetDictionaryKeyConverters(); } if (!_dictionaryKeyConverters.TryGetValue(keyType, out JsonConverter value)) { if (keyType.IsEnum) { value = GetEnumConverter(); _dictionaryKeyConverters[keyType] = value; } else { ThrowHelper.ThrowNotSupportedException_DictionaryKeyTypeNotSupported(keyType); } } return value; JsonConverter? GetEnumConverter() { return (JsonConverter)Activator.CreateInstance(typeof(EnumConverter<>).MakeGenericType(keyType), BindingFlags.Instance | BindingFlags.Public, null, new object[2] { EnumConverterOptions.AllowStrings | EnumConverterOptions.AllowNumbers, this }, null); } } private static ConcurrentDictionary? GetDictionaryKeyConverters() { ConcurrentDictionary? converters = new ConcurrentDictionary(Environment.ProcessorCount, 18); Add(s_defaultSimpleConverters[typeof(bool)]); Add(s_defaultSimpleConverters[typeof(byte)]); Add(s_defaultSimpleConverters[typeof(char)]); Add(s_defaultSimpleConverters[typeof(DateTime)]); Add(s_defaultSimpleConverters[typeof(DateTimeOffset)]); Add(s_defaultSimpleConverters[typeof(double)]); Add(s_defaultSimpleConverters[typeof(decimal)]); Add(s_defaultSimpleConverters[typeof(Guid)]); Add(s_defaultSimpleConverters[typeof(short)]); Add(s_defaultSimpleConverters[typeof(int)]); Add(s_defaultSimpleConverters[typeof(long)]); Add(s_defaultSimpleConverters[typeof(object)]); Add(s_defaultSimpleConverters[typeof(sbyte)]); Add(s_defaultSimpleConverters[typeof(float)]); Add(s_defaultSimpleConverters[typeof(string)]); Add(s_defaultSimpleConverters[typeof(ushort)]); Add(s_defaultSimpleConverters[typeof(uint)]); Add(s_defaultSimpleConverters[typeof(ulong)]); return converters; void Add(JsonConverter? converter) { converters[converter.TypeToConvert] = converter; } } internal JsonConverter? DetermineConverter(Type? parentClassType, Type? runtimePropertyType, MemberInfo? memberInfo) { JsonConverter jsonConverter = null; if (memberInfo != null) { JsonConverterAttribute jsonConverterAttribute = (JsonConverterAttribute)GetAttributeThatCanHaveMultiple(parentClassType, typeof(JsonConverterAttribute), memberInfo); if (jsonConverterAttribute != null) { jsonConverter = GetConverterFromAttribute(jsonConverterAttribute, runtimePropertyType, parentClassType, memberInfo); } } if (jsonConverter == null) { jsonConverter = GetConverter(runtimePropertyType); } if (jsonConverter is JsonConverterFactory jsonConverterFactory) { jsonConverter = jsonConverterFactory.GetConverterInternal(runtimePropertyType, this); } if (runtimePropertyType.IsNullableType() && !jsonConverter.TypeToConvert.IsNullableType()) { ThrowHelper.ThrowInvalidOperationException_ConverterCanConvertNullableRedundant(runtimePropertyType, jsonConverter); } return jsonConverter; } public JsonConverter GetConverter(Type typeToConvert) { if (_converters.TryGetValue(typeToConvert, out JsonConverter value)) { return value; } foreach (JsonConverter converter in Converters) { if (converter.CanConvert(typeToConvert)) { value = converter; break; } } if (value == null) { JsonConverterAttribute jsonConverterAttribute = (JsonConverterAttribute)GetAttributeThatCanHaveMultiple(typeToConvert, typeof(JsonConverterAttribute)); if (jsonConverterAttribute != null) { value = GetConverterFromAttribute(jsonConverterAttribute, typeToConvert, typeToConvert, null); } } if (value == null) { if (s_defaultSimpleConverters.TryGetValue(typeToConvert, out JsonConverter value2)) { value = value2; } else { JsonConverter[] array = s_defaultFactoryConverters; foreach (JsonConverter jsonConverter in array) { if (jsonConverter.CanConvert(typeToConvert)) { value = jsonConverter; break; } } } } if (value is JsonConverterFactory jsonConverterFactory) { value = jsonConverterFactory.GetConverterInternal(typeToConvert, this); } Type typeToConvert2 = value.TypeToConvert; if (!typeToConvert2.IsAssignableFromInternal(typeToConvert) && !typeToConvert.IsAssignableFromInternal(typeToConvert2)) { ThrowHelper.ThrowInvalidOperationException_SerializationConverterNotCompatible(value.GetType(), typeToConvert); } if (_haveTypesBeenCreated) { _converters.TryAdd(typeToConvert, value); } return value; } private JsonConverter? GetConverterFromAttribute(JsonConverterAttribute? converterAttribute, Type? typeToConvert, Type? classTypeAttributeIsOn, MemberInfo? memberInfo) { Type converterType = converterAttribute.ConverterType; JsonConverter jsonConverter; if (converterType == null) { jsonConverter = converterAttribute.CreateConverter(typeToConvert); if (jsonConverter == null) { ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(classTypeAttributeIsOn, memberInfo, typeToConvert); } } else { ConstructorInfo constructor = converterType.GetConstructor(Type.EmptyTypes); if (!typeof(JsonConverter).IsAssignableFrom(converterType) || constructor == null || !constructor.IsPublic) { ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(classTypeAttributeIsOn, memberInfo); } jsonConverter = (JsonConverter)Activator.CreateInstance(converterType); } if (!jsonConverter.CanConvert(typeToConvert)) { Type underlyingType = Nullable.GetUnderlyingType(typeToConvert); if (underlyingType != null && jsonConverter.CanConvert(underlyingType)) { if (jsonConverter is JsonConverterFactory jsonConverterFactory) { jsonConverter = jsonConverterFactory.GetConverterInternal(underlyingType, this); } return NullableConverterFactory.CreateValueConverter(underlyingType, jsonConverter); } ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(classTypeAttributeIsOn, memberInfo, typeToConvert); } return jsonConverter; } private static Attribute? GetAttributeThatCanHaveMultiple(Type? classType, Type? attributeType, MemberInfo? memberInfo) { object[] customAttributes = memberInfo.GetCustomAttributes(attributeType, inherit: false); return GetAttributeThatCanHaveMultiple(attributeType, classType, memberInfo, customAttributes); } internal static Attribute? GetAttributeThatCanHaveMultiple(Type? classType, Type? attributeType) { object[] customAttributes = classType.GetCustomAttributes(attributeType, inherit: false); return GetAttributeThatCanHaveMultiple(attributeType, classType, null, customAttributes); } private static Attribute? GetAttributeThatCanHaveMultiple(Type? attributeType, Type? classType, MemberInfo? memberInfo, object?[]? attributes) { if (attributes.Length == 0) { return null; } if (attributes.Length == 1) { return (Attribute)attributes[0]; } ThrowHelper.ThrowInvalidOperationException_SerializationDuplicateAttribute(attributeType, classType, memberInfo); return null; } public JsonSerializerOptions() { Converters = new ConverterList(this); } public JsonSerializerOptions(JsonSerializerOptions options) { if (options == null) { throw new ArgumentNullException("options"); } _memberAccessorStrategy = options._memberAccessorStrategy; _dictionaryKeyPolicy = options._dictionaryKeyPolicy; _jsonPropertyNamingPolicy = options._jsonPropertyNamingPolicy; _readCommentHandling = options._readCommentHandling; _referenceHandler = options._referenceHandler; _encoder = options._encoder; _defaultIgnoreCondition = options._defaultIgnoreCondition; _numberHandling = options._numberHandling; _defaultBufferSize = options._defaultBufferSize; _maxDepth = options._maxDepth; _allowTrailingCommas = options._allowTrailingCommas; _ignoreNullValues = options._ignoreNullValues; _ignoreReadOnlyProperties = options._ignoreReadOnlyProperties; _ignoreReadonlyFields = options._ignoreReadonlyFields; _includeFields = options._includeFields; _propertyNameCaseInsensitive = options._propertyNameCaseInsensitive; _writeIndented = options._writeIndented; Converters = new ConverterList(this, (ConverterList)options.Converters); EffectiveMaxDepth = options.EffectiveMaxDepth; } public JsonSerializerOptions(JsonSerializerDefaults defaults) : this() { switch (defaults) { case JsonSerializerDefaults.Web: _propertyNameCaseInsensitive = true; _jsonPropertyNamingPolicy = JsonNamingPolicy.CamelCase; _numberHandling = JsonNumberHandling.AllowReadingFromString; break; default: throw new ArgumentOutOfRangeException("defaults"); case JsonSerializerDefaults.General: break; } } internal JsonClassInfo? GetOrAddClass(Type? type) { _haveTypesBeenCreated = true; if (!_classes.TryGetValue(type, out JsonClassInfo value)) { return _classes.GetOrAdd(type, new JsonClassInfo(type, this)); } return value; } internal JsonClassInfo? GetOrAddClassForRootType(Type? type) { JsonClassInfo jsonClassInfo = _lastClass; if (jsonClassInfo?.Type != type) { jsonClassInfo = (_lastClass = GetOrAddClass(type)); } return jsonClassInfo; } internal bool TypeIsCached(Type? type) { return _classes.ContainsKey(type); } internal JsonReaderOptions GetReaderOptions() { JsonReaderOptions result = default(JsonReaderOptions); result.AllowTrailingCommas = AllowTrailingCommas; result.CommentHandling = ReadCommentHandling; result.MaxDepth = MaxDepth; return result; } internal JsonWriterOptions GetWriterOptions() { JsonWriterOptions result = default(JsonWriterOptions); result.Encoder = Encoder; result.Indented = WriteIndented; result.SkipValidation = true; return result; } internal void VerifyMutable() { if (_haveTypesBeenCreated) { ThrowHelper.ThrowInvalidOperationException_SerializerOptionsImmutable(); } } } internal abstract class MemberAccessor { public abstract JsonClassInfo.ConstructorDelegate CreateConstructor(Type classType); public abstract JsonClassInfo.ParameterizedConstructorDelegate CreateParameterizedConstructor(ConstructorInfo constructor); public abstract JsonClassInfo.ParameterizedConstructorDelegate CreateParameterizedConstructor(ConstructorInfo constructor); public abstract Action CreateAddMethodDelegate(); public abstract Func, TCollection> CreateImmutableEnumerableCreateRangeDelegate(); public abstract Func>, TCollection> CreateImmutableDictionaryCreateRangeDelegate(); public abstract Func CreatePropertyGetter(PropertyInfo propertyInfo); public abstract Action CreatePropertySetter(PropertyInfo propertyInfo); public abstract Func CreateFieldGetter(FieldInfo fieldInfo); public abstract Action CreateFieldSetter(FieldInfo fieldInfo); } internal enum MetadataPropertyName { NoMetadata, Values, Id, Ref } internal readonly struct ParameterRef { public readonly ulong Key; public readonly JsonParameterInfo Info; public readonly byte[] NameFromJson; public ParameterRef(ulong key, JsonParameterInfo info, byte[] nameFromJson) { Key = key; Info = info; NameFromJson = nameFromJson; } } internal readonly struct PropertyRef { public readonly ulong Key; public readonly JsonPropertyInfo Info; public readonly byte[] NameFromJson; public PropertyRef(ulong key, JsonPropertyInfo info, byte[] nameFromJson) { Key = key; Info = info; NameFromJson = nameFromJson; } } [DebuggerDisplay("Path:{JsonPath()} Current: ClassType.{Current.JsonClassInfo.ClassType}, {Current.JsonClassInfo.Type.Name}")] internal struct ReadStack { internal static readonly char[] SpecialCharacters = new char[18] { '.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t', '\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029' }; private int _continuationCount; private int _count; private List _previous; private List _ctorArgStateCache; public long BytesConsumed; public ReadStackFrame Current; public bool ReadAhead; public ReferenceResolver ReferenceResolver; public bool SupportContinuation; public bool UseFastPath; public bool IsContinuation => _continuationCount != 0; public bool IsLastContinuation => _continuationCount == _count; private void AddCurrent() { if (_previous == null) { _previous = new List(); } if (_count > _previous.Count) { _previous.Add(Current); } else { _previous[_count - 1] = Current; } _count++; } public void Initialize(Type type, JsonSerializerOptions options, bool supportContinuation) { JsonClassInfo orAddClassForRootType = options.GetOrAddClassForRootType(type); Current.JsonClassInfo = orAddClassForRootType; Current.JsonPropertyInfo = orAddClassForRootType.PropertyInfoForClassInfo; Current.NumberHandling = Current.JsonPropertyInfo.NumberHandling; bool flag = options.ReferenceHandler != null; if (flag) { ReferenceResolver = options.ReferenceHandler.CreateResolver(writing: false); } SupportContinuation = supportContinuation; UseFastPath = !supportContinuation && !flag; } public void Push() { if (_continuationCount == 0) { if (_count == 0) { _count = 1; } else { JsonNumberHandling? numberHandling = Current.NumberHandling; JsonClassInfo jsonClassInfo = ((Current.JsonClassInfo.ClassType == ClassType.Object) ? ((Current.JsonPropertyInfo == null) ? Current.CtorArgumentState.JsonParameterInfo.RuntimeClassInfo : Current.JsonPropertyInfo.RuntimeClassInfo) : ((((ClassType)6 & Current.JsonClassInfo.ClassType) == 0) ? Current.JsonClassInfo.ElementClassInfo : Current.JsonPropertyInfo.RuntimeClassInfo)); AddCurrent(); Current.Reset(); Current.JsonClassInfo = jsonClassInfo; Current.JsonPropertyInfo = jsonClassInfo.PropertyInfoForClassInfo; Current.NumberHandling = numberHandling ?? Current.JsonPropertyInfo.NumberHandling; } } else if (_continuationCount == 1) { _continuationCount = 0; } else { Current = _previous[_count - 1]; if (_count == _continuationCount) { _continuationCount = 0; } else { _count++; } } SetConstructorArgumentState(); } public void Pop(bool success) { if (!success) { if (_continuationCount == 0) { if (_count == 1) { _continuationCount = 1; return; } AddCurrent(); _count--; _continuationCount = _count; _count--; Current = _previous[_count - 1]; return; } if (_continuationCount == 1) { return; } _previous[_count - 1] = Current; } if (_count > 1) { Current = _previous[--_count - 1]; } SetConstructorArgumentState(); } public string JsonPath() { StringBuilder stringBuilder = new StringBuilder("$"); int num = Math.Max(_count, _continuationCount); for (int i = 0; i < num - 1; i++) { ReadStackFrame frame2 = _previous[i]; AppendStackFrame(stringBuilder, in frame2); } if (_continuationCount == 0) { AppendStackFrame(stringBuilder, in Current); } return stringBuilder.ToString(); static void AppendPropertyName(StringBuilder sb, string propertyName) { if (propertyName != null) { if (propertyName.IndexOfAny(SpecialCharacters) != -1) { sb.Append("['"); sb.Append(propertyName); sb.Append("']"); } else { sb.Append('.'); sb.Append(propertyName); } } } static void AppendStackFrame(StringBuilder sb, in ReadStackFrame frame) { string propertyName2 = GetPropertyName(in frame); AppendPropertyName(sb, propertyName2); if (frame.JsonClassInfo != null && frame.IsProcessingEnumerable()) { IEnumerable enumerable2 = (IEnumerable)frame.ReturnValue; if (enumerable2 != null && (frame.ObjectState == StackFrameObjectState.None || frame.ObjectState == StackFrameObjectState.CreatedObject || frame.ObjectState == StackFrameObjectState.ReadElements)) { sb.Append('['); sb.Append(GetCount(enumerable2)); sb.Append(']'); } } } static int GetCount(IEnumerable enumerable) { if (enumerable is ICollection collection) { return collection.Count; } int num2 = 0; IEnumerator enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) { num2++; } return num2; } static string GetPropertyName(in ReadStackFrame frame) { string result = null; byte[] array = frame.JsonPropertyName; if (array == null) { if (frame.JsonPropertyNameAsString != null) { result = frame.JsonPropertyNameAsString; } else { array = frame.JsonPropertyInfo?.NameAsUtf8Bytes ?? frame.CtorArgumentState?.JsonParameterInfo?.NameAsUtf8Bytes; } } if (array != null) { result = JsonHelpers.Utf8GetString(array); } return result; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void SetConstructorArgumentState() { if (Current.JsonClassInfo.ParameterCount <= 0) { return; } if (Current.CtorArgumentStateIndex == 0) { if (_ctorArgStateCache == null) { _ctorArgStateCache = new List(); } ArgumentState argumentState = new ArgumentState(); _ctorArgStateCache.Add(argumentState); ref int ctorArgumentStateIndex = ref Current.CtorArgumentStateIndex; ref ArgumentState ctorArgumentState = ref Current.CtorArgumentState; int count = _ctorArgStateCache.Count; ArgumentState argumentState2 = argumentState; ctorArgumentStateIndex = count; ctorArgumentState = argumentState2; } else { Current.CtorArgumentState = _ctorArgStateCache[Current.CtorArgumentStateIndex - 1]; } } } [DebuggerDisplay("ClassType.{JsonClassInfo.ClassType}, {JsonClassInfo.Type.Name}")] internal struct ReadStackFrame { public JsonPropertyInfo JsonPropertyInfo; public StackFramePropertyState PropertyState; public bool UseExtensionProperty; public byte[] JsonPropertyName; public string JsonPropertyNameAsString; public object DictionaryKey; public int OriginalDepth; public JsonTokenType OriginalTokenType; public object ReturnValue; public JsonClassInfo JsonClassInfo; public StackFrameObjectState ObjectState; public bool ValidateEndTokenOnArray; public int PropertyIndex; public List PropertyRefCache; public int CtorArgumentStateIndex; public ArgumentState CtorArgumentState; public JsonNumberHandling? NumberHandling; public void EndConstructorParameter() { CtorArgumentState.JsonParameterInfo = null; JsonPropertyName = null; PropertyState = StackFramePropertyState.None; } public void EndProperty() { JsonPropertyInfo = null; JsonPropertyName = null; JsonPropertyNameAsString = null; PropertyState = StackFramePropertyState.None; ValidateEndTokenOnArray = false; } public void EndElement() { JsonPropertyNameAsString = null; PropertyState = StackFramePropertyState.None; } public bool IsProcessingDictionary() { return (JsonClassInfo.ClassType & ClassType.Dictionary) != 0; } public bool IsProcessingEnumerable() { return (JsonClassInfo.ClassType & ClassType.Enumerable) != 0; } public void Reset() { CtorArgumentStateIndex = 0; CtorArgumentState = null; JsonClassInfo = null; ObjectState = StackFrameObjectState.None; OriginalDepth = 0; OriginalTokenType = JsonTokenType.None; PropertyIndex = 0; PropertyRefCache = null; ReturnValue = null; EndProperty(); } } internal enum StackFrameObjectState : byte { None, StartToken, ReadAheadNameOrEndObject, ReadNameOrEndObject, ReadAheadIdValue, ReadAheadRefValue, ReadIdValue, ReadRefValue, ReadAheadRefEndObject, ReadRefEndObject, ReadAheadValuesName, ReadValuesName, ReadAheadValuesStartArray, ReadValuesStartArray, PropertyValue, CreatedObject, ReadElements, EndToken, EndTokenValidation } internal enum StackFramePropertyState : byte { None, ReadName, Name, ReadValue, ReadValueIsEnd, TryRead } [DebuggerDisplay("Path:{PropertyPath()} Current: ClassType.{Current.JsonClassInfo.ClassType}, {Current.JsonClassInfo.Type.Name}")] internal struct WriteStack { private int _continuationCount; private int _count; private List _previous; public WriteStackFrame Current; public int FlushThreshold; public ReferenceResolver ReferenceResolver; public bool SupportContinuation; public bool IsContinuation => _continuationCount != 0; private void AddCurrent() { if (_previous == null) { _previous = new List(); } if (_count > _previous.Count) { _previous.Add(Current); } else { _previous[_count - 1] = Current; } _count++; } public JsonConverter Initialize(Type type, JsonSerializerOptions options, bool supportContinuation) { JsonClassInfo orAddClassForRootType = options.GetOrAddClassForRootType(type); Current.JsonClassInfo = orAddClassForRootType; Current.DeclaredJsonPropertyInfo = orAddClassForRootType.PropertyInfoForClassInfo; Current.NumberHandling = Current.DeclaredJsonPropertyInfo.NumberHandling; if (options.ReferenceHandler != null) { ReferenceResolver = options.ReferenceHandler.CreateResolver(writing: true); } SupportContinuation = supportContinuation; return orAddClassForRootType.PropertyInfoForClassInfo.ConverterBase; } public void Push() { if (_continuationCount == 0) { if (_count == 0) { _count = 1; return; } JsonClassInfo runtimeClassInfo = Current.GetPolymorphicJsonPropertyInfo().RuntimeClassInfo; JsonNumberHandling? numberHandling = Current.NumberHandling; AddCurrent(); Current.Reset(); Current.JsonClassInfo = runtimeClassInfo; Current.DeclaredJsonPropertyInfo = runtimeClassInfo.PropertyInfoForClassInfo; Current.NumberHandling = numberHandling ?? Current.DeclaredJsonPropertyInfo.NumberHandling; } else if (_continuationCount == 1) { _continuationCount = 0; } else { Current = _previous[_count - 1]; if (_count == _continuationCount) { _continuationCount = 0; } else { _count++; } } } public void Pop(bool success) { if (!success) { if (_continuationCount == 0) { if (_count == 1) { _continuationCount = 1; _count = 1; return; } AddCurrent(); _count--; _continuationCount = _count; _count--; Current = _previous[_count - 1]; return; } if (_continuationCount == 1) { return; } _previous[_count - 1] = Current; } if (_count > 1) { Current = _previous[--_count - 1]; } } public string PropertyPath() { StringBuilder stringBuilder = new StringBuilder("$"); int num = Math.Max(_count, _continuationCount); for (int i = 0; i < num - 1; i++) { WriteStackFrame frame2 = _previous[i]; AppendStackFrame(stringBuilder, in frame2); } if (_continuationCount == 0) { AppendStackFrame(stringBuilder, in Current); } return stringBuilder.ToString(); static void AppendPropertyName(StringBuilder sb, string propertyName) { if (propertyName != null) { if (propertyName.IndexOfAny(ReadStack.SpecialCharacters) != -1) { sb.Append("['"); sb.Append(propertyName); sb.Append("']"); } else { sb.Append('.'); sb.Append(propertyName); } } } static void AppendStackFrame(StringBuilder sb, in WriteStackFrame frame) { string text = frame.DeclaredJsonPropertyInfo?.MemberInfo?.Name; if (text == null) { text = frame.JsonPropertyNameAsString; } AppendPropertyName(sb, text); } } } [DebuggerDisplay("ClassType.{JsonClassInfo.ClassType}, {JsonClassInfo.Type.Name}")] internal struct WriteStackFrame { public IEnumerator CollectionEnumerator; public JsonPropertyInfo DeclaredJsonPropertyInfo; public bool IgnoreDictionaryKeyPolicy; public JsonClassInfo JsonClassInfo; public int OriginalDepth; public bool ProcessedStartToken; public bool ProcessedEndToken; public StackFramePropertyState PropertyState; public int EnumeratorIndex; public string JsonPropertyNameAsString; public MetadataPropertyName MetadataPropertyName; public JsonPropertyInfo PolymorphicJsonPropertyInfo; public JsonNumberHandling? NumberHandling; public void EndDictionaryElement() { PropertyState = StackFramePropertyState.None; } public void EndProperty() { DeclaredJsonPropertyInfo = null; JsonPropertyNameAsString = null; PolymorphicJsonPropertyInfo = null; PropertyState = StackFramePropertyState.None; } public JsonPropertyInfo GetPolymorphicJsonPropertyInfo() { return PolymorphicJsonPropertyInfo ?? DeclaredJsonPropertyInfo; } public JsonConverter InitializeReEntry(Type type, JsonSerializerOptions options, string propertyName = null) { JsonClassInfo orAddClass = options.GetOrAddClass(type); JsonPropertyNameAsString = propertyName; PolymorphicJsonPropertyInfo = orAddClass.PropertyInfoForClassInfo; return PolymorphicJsonPropertyInfo.ConverterBase; } public void Reset() { CollectionEnumerator = null; EnumeratorIndex = 0; IgnoreDictionaryKeyPolicy = false; JsonClassInfo = null; OriginalDepth = 0; ProcessedStartToken = false; ProcessedEndToken = false; EndProperty(); } } internal enum ExceptionResource { ArrayDepthTooLarge, EndOfCommentNotFound, EndOfStringNotFound, RequiredDigitNotFoundAfterDecimal, RequiredDigitNotFoundAfterSign, RequiredDigitNotFoundEndOfData, ExpectedEndAfterSingleJson, ExpectedEndOfDigitNotFound, ExpectedFalse, ExpectedNextDigitEValueNotFound, ExpectedNull, ExpectedSeparatorAfterPropertyNameNotFound, ExpectedStartOfPropertyNotFound, ExpectedStartOfPropertyOrValueNotFound, ExpectedStartOfPropertyOrValueAfterComment, ExpectedStartOfValueNotFound, ExpectedTrue, ExpectedValueAfterPropertyNameNotFound, FoundInvalidCharacter, InvalidCharacterWithinString, InvalidCharacterAfterEscapeWithinString, InvalidHexCharacterWithinString, InvalidEndOfJsonNonPrimitive, MismatchedObjectArray, ObjectDepthTooLarge, ZeroDepthAtEnd, DepthTooLarge, CannotStartObjectArrayWithoutProperty, CannotStartObjectArrayAfterPrimitiveOrClose, CannotWriteValueWithinObject, CannotWriteValueAfterPrimitiveOrClose, CannotWritePropertyWithinArray, ExpectedJsonTokens, TrailingCommaNotAllowedBeforeArrayEnd, TrailingCommaNotAllowedBeforeObjectEnd, InvalidCharacterAtStartOfComment, UnexpectedEndOfDataWhileReadingComment, UnexpectedEndOfLineSeparator, ExpectedOneCompleteToken, NotEnoughData, InvalidLeadingZeroInNumber } internal enum NumericType { Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal } internal enum DataType { Boolean, DateTime, DateTimeOffset, Base64String, Guid } internal static class TypeExtensions { public static bool IsNullableValueType(this Type type) { return Nullable.GetUnderlyingType(type) != null; } public static bool IsNullableType(this Type type) { if (type.IsValueType) { return type.IsNullableValueType(); } return true; } public static bool IsAssignableFromInternal(this Type type, Type from) { if (from.IsNullableValueType() && type.IsInterface) { return type.IsAssignableFrom(from.GetGenericArguments()[0]); } return type.IsAssignableFrom(from); } } internal static class JsonWriterHelper { private static readonly StandardFormat s_dateTimeStandardFormat = new StandardFormat('O'); public const int LastAsciiCharacter = 127; private static readonly StandardFormat s_hexStandardFormat = new StandardFormat('X', 4); private static ReadOnlySpan AllowList => new byte[256] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public static void WriteIndentation(Span buffer, int indent) { if (indent < 8) { int num = 0; while (num < indent) { buffer[num++] = 32; buffer[num++] = 32; } } else { buffer.Slice(0, indent).Fill(32); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidateProperty(ReadOnlySpan propertyName) { if (propertyName.Length > 166666666) { ThrowHelper.ThrowArgumentException_PropertyNameTooLarge(propertyName.Length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidateValue(ReadOnlySpan value) { if (value.Length > 166666666) { ThrowHelper.ThrowArgumentException_ValueTooLarge(value.Length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidateBytes(ReadOnlySpan bytes) { if (bytes.Length > 125000000) { ThrowHelper.ThrowArgumentException_ValueTooLarge(bytes.Length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidateDouble(double value) { if (!JsonHelpers.IsFinite(value)) { ThrowHelper.ThrowArgumentException_ValueNotSupported(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidateSingle(float value) { if (!JsonHelpers.IsFinite(value)) { ThrowHelper.ThrowArgumentException_ValueNotSupported(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidateProperty(ReadOnlySpan propertyName) { if (propertyName.Length > 166666666) { ThrowHelper.ThrowArgumentException_PropertyNameTooLarge(propertyName.Length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidateValue(ReadOnlySpan value) { if (value.Length > 166666666) { ThrowHelper.ThrowArgumentException_ValueTooLarge(value.Length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidatePropertyAndValue(ReadOnlySpan propertyName, ReadOnlySpan value) { if (propertyName.Length > 166666666 || value.Length > 166666666) { ThrowHelper.ThrowArgumentException(propertyName, value); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidatePropertyAndValue(ReadOnlySpan propertyName, ReadOnlySpan value) { if (propertyName.Length > 166666666 || value.Length > 166666666) { ThrowHelper.ThrowArgumentException(propertyName, value); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidatePropertyAndValue(ReadOnlySpan propertyName, ReadOnlySpan value) { if (propertyName.Length > 166666666 || value.Length > 166666666) { ThrowHelper.ThrowArgumentException(propertyName, value); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidatePropertyAndValue(ReadOnlySpan propertyName, ReadOnlySpan value) { if (propertyName.Length > 166666666 || value.Length > 166666666) { ThrowHelper.ThrowArgumentException(propertyName, value); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidatePropertyAndBytes(ReadOnlySpan propertyName, ReadOnlySpan bytes) { if (propertyName.Length > 166666666 || bytes.Length > 125000000) { ThrowHelper.ThrowArgumentException(propertyName, bytes); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidatePropertyAndBytes(ReadOnlySpan propertyName, ReadOnlySpan bytes) { if (propertyName.Length > 166666666 || bytes.Length > 125000000) { ThrowHelper.ThrowArgumentException(propertyName, bytes); } } internal static void ValidateNumber(ReadOnlySpan utf8FormattedNumber) { int i = 0; if (utf8FormattedNumber[i] == 45) { i++; if (utf8FormattedNumber.Length <= i) { throw new ArgumentException(System.SR.RequiredDigitNotFoundEndOfData, "utf8FormattedNumber"); } } if (utf8FormattedNumber[i] == 48) { i++; } else { for (; i < utf8FormattedNumber.Length && JsonHelpers.IsDigit(utf8FormattedNumber[i]); i++) { } } if (i == utf8FormattedNumber.Length) { return; } byte b = utf8FormattedNumber[i]; if (b == 46) { i++; if (utf8FormattedNumber.Length <= i) { throw new ArgumentException(System.SR.RequiredDigitNotFoundEndOfData, "utf8FormattedNumber"); } for (; i < utf8FormattedNumber.Length && JsonHelpers.IsDigit(utf8FormattedNumber[i]); i++) { } if (i == utf8FormattedNumber.Length) { return; } b = utf8FormattedNumber[i]; } if (b == 101 || b == 69) { i++; if (utf8FormattedNumber.Length <= i) { throw new ArgumentException(System.SR.RequiredDigitNotFoundEndOfData, "utf8FormattedNumber"); } b = utf8FormattedNumber[i]; if (b == 43 || b == 45) { i++; } if (utf8FormattedNumber.Length <= i) { throw new ArgumentException(System.SR.RequiredDigitNotFoundEndOfData, "utf8FormattedNumber"); } for (; i < utf8FormattedNumber.Length && JsonHelpers.IsDigit(utf8FormattedNumber[i]); i++) { } if (i == utf8FormattedNumber.Length) { return; } throw new ArgumentException(System.SR.Format(System.SR.ExpectedEndOfDigitNotFound, ThrowHelper.GetPrintableString(utf8FormattedNumber[i])), "utf8FormattedNumber"); } throw new ArgumentException(System.SR.Format(System.SR.ExpectedEndOfDigitNotFound, ThrowHelper.GetPrintableString(b)), "utf8FormattedNumber"); } public static void WriteDateTimeTrimmed(Span buffer, DateTime value, out int bytesWritten) { Span destination = stackalloc byte[33]; bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten, s_dateTimeStandardFormat); TrimDateTimeOffset(destination.Slice(0, bytesWritten), out bytesWritten); destination.Slice(0, bytesWritten).CopyTo(buffer); } public static void WriteDateTimeOffsetTrimmed(Span buffer, DateTimeOffset value, out int bytesWritten) { Span destination = stackalloc byte[33]; bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten, s_dateTimeStandardFormat); TrimDateTimeOffset(destination.Slice(0, bytesWritten), out bytesWritten); destination.Slice(0, bytesWritten).CopyTo(buffer); } public static void TrimDateTimeOffset(Span buffer, out int bytesWritten) { uint num = (uint)(buffer[26] - 48); uint num2 = (uint)(buffer[25] - 48); uint num3 = (uint)(buffer[24] - 48); uint num4 = (uint)(buffer[23] - 48); uint num5 = (uint)(buffer[22] - 48); uint num6 = (uint)(buffer[21] - 48); uint num7 = (uint)(buffer[20] - 48); uint num8 = num7 * 1000000 + num6 * 100000 + num5 * 10000 + num4 * 1000 + num3 * 100 + num2 * 10 + num; int num9 = 19; if (num8 != 0) { int num10 = 7; while (true) { uint modulo; uint num11 = DivMod(num8, 10u, out modulo); if (modulo != 0) { break; } num8 = num11; num10--; } int num12 = 19 + num10; for (int num13 = num12; num13 > num9; num13--) { buffer[num13] = (byte)(num8 % 10 + 48); num8 /= 10; } num9 = num12 + 1; } bytesWritten = num9; if (buffer.Length > 27) { buffer[num9] = buffer[27]; bytesWritten = num9 + 1; if (buffer.Length == 33) { int num14 = num9 + 5; byte b = buffer[31]; byte b2 = buffer[29]; byte b3 = buffer[28]; buffer[num14] = buffer[32]; buffer[num14 - 1] = b; buffer[num14 - 2] = 58; buffer[num14 - 3] = b2; buffer[num14 - 4] = b3; bytesWritten = num14 + 1; } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint DivMod(uint numerator, uint denominator, out uint modulo) { uint num = numerator / denominator; modulo = numerator - num * denominator; return num; } private static bool NeedsEscaping(byte value) { return AllowList[value] == 0; } private static bool NeedsEscapingNoBoundsCheck(char value) { return AllowList[value] == 0; } public static int NeedsEscaping(ReadOnlySpan value, JavaScriptEncoder encoder) { return (encoder ?? JavaScriptEncoder.Default).FindFirstCharacterToEncodeUtf8((ReadOnlySpan)value); } public unsafe static int NeedsEscaping(ReadOnlySpan value, JavaScriptEncoder encoder) { if (value.IsEmpty) { return -1; } fixed (char* text = value) { return (encoder ?? JavaScriptEncoder.Default).FindFirstCharacterToEncode(text, value.Length); } } public static int GetMaxEscapedLength(int textLength, int firstIndexToEscape) { return firstIndexToEscape + 6 * (textLength - firstIndexToEscape); } private static void EscapeString(ReadOnlySpan value, Span destination, JavaScriptEncoder encoder, ref int written) { if (encoder.EncodeUtf8((ReadOnlySpan)value, (Span)destination, out var _, out var bytesWritten) != 0) { ThrowHelper.ThrowArgumentException_InvalidUTF8(value.Slice(bytesWritten)); } written += bytesWritten; } public static void EscapeString(ReadOnlySpan value, Span destination, int indexOfFirstByteToEscape, JavaScriptEncoder encoder, out int written) { value.Slice(0, indexOfFirstByteToEscape).CopyTo(destination); written = indexOfFirstByteToEscape; if (encoder != null) { destination = destination.Slice(indexOfFirstByteToEscape); value = value.Slice(indexOfFirstByteToEscape); EscapeString(value, destination, encoder, ref written); return; } while (indexOfFirstByteToEscape < value.Length) { byte b = value[indexOfFirstByteToEscape]; if (IsAsciiValue(b)) { if (NeedsEscaping(b)) { EscapeNextBytes(b, destination, ref written); indexOfFirstByteToEscape++; } else { destination[written] = b; written++; indexOfFirstByteToEscape++; } continue; } destination = destination.Slice(written); value = value.Slice(indexOfFirstByteToEscape); EscapeString(value, destination, JavaScriptEncoder.Default, ref written); break; } } private static void EscapeNextBytes(byte value, Span destination, ref int written) { destination[written++] = 92; switch (value) { case 34: destination[written++] = 117; destination[written++] = 48; destination[written++] = 48; destination[written++] = 50; destination[written++] = 50; break; case 10: destination[written++] = 110; break; case 13: destination[written++] = 114; break; case 9: destination[written++] = 116; break; case 92: destination[written++] = 92; break; case 8: destination[written++] = 98; break; case 12: destination[written++] = 102; break; default: { destination[written++] = 117; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, destination.Slice(written), out bytesWritten, s_hexStandardFormat); written += bytesWritten; break; } } } private static bool IsAsciiValue(byte value) { return value <= 127; } private static bool IsAsciiValue(char value) { return value <= '\u007f'; } private static void EscapeString(ReadOnlySpan value, Span destination, JavaScriptEncoder encoder, ref int written) { if (encoder.Encode((ReadOnlySpan)value, (Span)destination, out var _, out var charsWritten) != 0) { ThrowHelper.ThrowArgumentException_InvalidUTF16(value[charsWritten]); } written += charsWritten; } public static void EscapeString(ReadOnlySpan value, Span destination, int indexOfFirstByteToEscape, JavaScriptEncoder encoder, out int written) { value.Slice(0, indexOfFirstByteToEscape).CopyTo(destination); written = indexOfFirstByteToEscape; if (encoder != null) { destination = destination.Slice(indexOfFirstByteToEscape); value = value.Slice(indexOfFirstByteToEscape); EscapeString(value, destination, encoder, ref written); return; } while (indexOfFirstByteToEscape < value.Length) { char c = value[indexOfFirstByteToEscape]; if (IsAsciiValue(c)) { if (NeedsEscapingNoBoundsCheck(c)) { EscapeNextChars(c, destination, ref written); indexOfFirstByteToEscape++; } else { destination[written] = c; written++; indexOfFirstByteToEscape++; } continue; } destination = destination.Slice(written); value = value.Slice(indexOfFirstByteToEscape); EscapeString(value, destination, JavaScriptEncoder.Default, ref written); break; } } private static void EscapeNextChars(char value, Span destination, ref int written) { destination[written++] = '\\'; switch ((byte)value) { case 34: destination[written++] = 'u'; destination[written++] = '0'; destination[written++] = '0'; destination[written++] = '2'; destination[written++] = '2'; break; case 10: destination[written++] = 'n'; break; case 13: destination[written++] = 'r'; break; case 9: destination[written++] = 't'; break; case 92: destination[written++] = '\\'; break; case 8: destination[written++] = 'b'; break; case 12: destination[written++] = 'f'; break; default: destination[written++] = 'u'; written = WriteHex(value, destination, written); break; } } private static int WriteHex(int value, Span destination, int written) { destination[written++] = System.HexConverter.ToCharUpper(value >> 12); destination[written++] = System.HexConverter.ToCharUpper(value >> 8); destination[written++] = System.HexConverter.ToCharUpper(value >> 4); destination[written++] = System.HexConverter.ToCharUpper(value); return written; } public unsafe static OperationStatus ToUtf8(ReadOnlySpan utf16Source, Span utf8Destination, out int bytesConsumed, out int bytesWritten) { fixed (byte* ptr = &MemoryMarshal.GetReference(utf16Source)) { fixed (byte* ptr3 = &MemoryMarshal.GetReference(utf8Destination)) { char* ptr2 = (char*)ptr; byte* ptr4 = ptr3; char* ptr5 = (char*)(ptr + utf16Source.Length); byte* ptr6 = ptr4 + utf8Destination.Length; while (true) { IL_0205: if (ptr5 - ptr2 > 13) { int num = Math.Min(PtrDiff(ptr5, ptr2), PtrDiff(ptr6, ptr4)); char* ptr7 = ptr2 + num - 5; if (ptr2 < ptr7) { while (true) { int num2 = *ptr2; ptr2++; if (num2 > 127) { goto IL_012c; } *ptr4 = (byte)num2; ptr4++; if (((uint)(int)ptr2 & 2u) != 0) { num2 = *ptr2; ptr2++; if (num2 > 127) { goto IL_012c; } *ptr4 = (byte)num2; ptr4++; } while (ptr2 < ptr7) { num2 = *(int*)ptr2; int num3 = *(int*)(ptr2 + 2); if (((num2 | num3) & -8323200) == 0) { *ptr4 = (byte)num2; ptr4[1] = (byte)(num2 >> 16); ptr2 += 4; ptr4[2] = (byte)num3; ptr4[3] = (byte)(num3 >> 16); ptr4 += 4; continue; } goto IL_010a; } goto IL_01fc; IL_010a: num2 = (ushort)num2; ptr2++; if (num2 > 127) { goto IL_012c; } *ptr4 = (byte)num2; ptr4++; goto IL_01fc; IL_01fc: if (ptr2 < ptr7) { continue; } goto IL_0205; IL_012c: int num4; if (num2 <= 2047) { num4 = -64 | (num2 >> 6); } else { if (!JsonHelpers.IsInRangeInclusive(num2, 55296, 57343)) { num4 = -32 | (num2 >> 12); } else { if (num2 > 56319) { break; } num4 = *ptr2; if (!JsonHelpers.IsInRangeInclusive(num4, 56320, 57343)) { break; } ptr2++; num2 = num4 + (num2 << 10) + -56613888; *ptr4 = (byte)(0xFFFFFFF0u | (uint)(num2 >> 18)); ptr4++; num4 = -128 | ((num2 >> 12) & 0x3F); } *ptr4 = (byte)num4; ptr7--; ptr4++; num4 = -128 | ((num2 >> 6) & 0x3F); } *ptr4 = (byte)num4; ptr7--; ptr4[1] = (byte)(0xFFFFFF80u | ((uint)num2 & 0x3Fu)); ptr4 += 2; goto IL_01fc; } break; } } while (true) { int num5; int num6; if (ptr2 < ptr5) { num5 = *ptr2; ptr2++; if (num5 <= 127) { if (ptr6 - ptr4 > 0) { *ptr4 = (byte)num5; ptr4++; continue; } } else if (num5 <= 2047) { if (ptr6 - ptr4 > 1) { num6 = -64 | (num5 >> 6); goto IL_032b; } } else if (!JsonHelpers.IsInRangeInclusive(num5, 55296, 57343)) { if (ptr6 - ptr4 > 2) { num6 = -32 | (num5 >> 12); goto IL_0313; } } else if (ptr6 - ptr4 > 3) { if (num5 > 56319) { break; } if (ptr2 < ptr5) { num6 = *ptr2; if (!JsonHelpers.IsInRangeInclusive(num6, 56320, 57343)) { break; } ptr2++; num5 = num6 + (num5 << 10) + -56613888; *ptr4 = (byte)(0xFFFFFFF0u | (uint)(num5 >> 18)); ptr4++; num6 = -128 | ((num5 >> 12) & 0x3F); goto IL_0313; } bytesConsumed = (int)((byte*)(ptr2 - 1) - ptr); bytesWritten = (int)(ptr4 - ptr3); return OperationStatus.NeedMoreData; } bytesConsumed = (int)((byte*)(ptr2 - 1) - ptr); bytesWritten = (int)(ptr4 - ptr3); return OperationStatus.DestinationTooSmall; } bytesConsumed = (int)((byte*)ptr2 - ptr); bytesWritten = (int)(ptr4 - ptr3); return OperationStatus.Done; IL_0313: *ptr4 = (byte)num6; ptr4++; num6 = -128 | ((num5 >> 6) & 0x3F); goto IL_032b; IL_032b: *ptr4 = (byte)num6; ptr4[1] = (byte)(0xFFFFFF80u | ((uint)num5 & 0x3Fu)); ptr4 += 2; } break; } bytesConsumed = (int)((byte*)(ptr2 - 1) - ptr); bytesWritten = (int)(ptr4 - ptr3); return OperationStatus.InvalidData; } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe static int PtrDiff(char* a, char* b) { return (int)((uint)((byte*)a - (byte*)b) >> 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe static int PtrDiff(byte* a, byte* b) { return (int)(a - b); } } internal struct JsonWriterOptions { private int _optionsMask; private const int IndentBit = 1; private const int SkipValidationBit = 2; public JavaScriptEncoder? Encoder { get; set; } public bool Indented { get { return (_optionsMask & 1) != 0; } set { if (value) { _optionsMask |= 1; } else { _optionsMask &= -2; } } } public bool SkipValidation { get { return (_optionsMask & 2) != 0; } set { if (value) { _optionsMask |= 2; } else { _optionsMask &= -3; } } } internal bool IndentedOrNotSkipValidation => _optionsMask != 2; } [DebuggerDisplay("{DebuggerDisplay,nq}")] internal sealed class Utf8JsonWriter : IDisposable, IAsyncDisposable { private static readonly int s_newLineLength = Environment.NewLine.Length; private const int DefaultGrowthSize = 4096; private const int InitialGrowthSize = 256; private IBufferWriter _output; private Stream _stream; private ArrayBufferWriter _arrayBufferWriter; private Memory _memory; private bool _inObject; private JsonTokenType _tokenType; private BitStack _bitStack; private int _currentDepth; private JsonWriterOptions _options; private static readonly char[] s_singleLineCommentDelimiter = new char[2] { '*', '/' }; public int BytesPending { get; private set; } public long BytesCommitted { get; private set; } public JsonWriterOptions Options => _options; private int Indentation => CurrentDepth * 2; public int CurrentDepth => _currentDepth & 0x7FFFFFFF; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay => $"BytesCommitted = {BytesCommitted} BytesPending = {BytesPending} CurrentDepth = {CurrentDepth}"; private static ReadOnlySpan SingleLineCommentDelimiterUtf8 => "*/"u8; public Utf8JsonWriter(IBufferWriter bufferWriter, JsonWriterOptions options = default(JsonWriterOptions)) { _output = bufferWriter ?? throw new ArgumentNullException("bufferWriter"); _options = options; } public Utf8JsonWriter(Stream utf8Json, JsonWriterOptions options = default(JsonWriterOptions)) { if (utf8Json == null) { throw new ArgumentNullException("utf8Json"); } if (!utf8Json.CanWrite) { throw new ArgumentException(System.SR.StreamNotWritable); } _stream = utf8Json; _options = options; _arrayBufferWriter = new ArrayBufferWriter(); } public void Reset() { CheckNotDisposed(); _arrayBufferWriter?.Clear(); ResetHelper(); } public void Reset(Stream utf8Json) { CheckNotDisposed(); if (utf8Json == null) { throw new ArgumentNullException("utf8Json"); } if (!utf8Json.CanWrite) { throw new ArgumentException(System.SR.StreamNotWritable); } _stream = utf8Json; if (_arrayBufferWriter == null) { _arrayBufferWriter = new ArrayBufferWriter(); } else { _arrayBufferWriter.Clear(); } _output = null; ResetHelper(); } public void Reset(IBufferWriter bufferWriter) { CheckNotDisposed(); _output = bufferWriter ?? throw new ArgumentNullException("bufferWriter"); _stream = null; _arrayBufferWriter = null; ResetHelper(); } private void ResetHelper() { BytesPending = 0; BytesCommitted = 0L; _memory = default(Memory); _inObject = false; _tokenType = JsonTokenType.None; _currentDepth = 0; _bitStack = default(BitStack); } private void CheckNotDisposed() { if (_stream == null && _output == null) { throw new ObjectDisposedException("Utf8JsonWriter"); } } public void Flush() { CheckNotDisposed(); _memory = default(Memory); if (_stream != null) { if (BytesPending != 0) { _arrayBufferWriter.Advance(BytesPending); BytesPending = 0; ArraySegment segment; bool flag = MemoryMarshal.TryGetArray(_arrayBufferWriter.WrittenMemory, out segment); _stream.Write(segment.Array, segment.Offset, segment.Count); BytesCommitted += _arrayBufferWriter.WrittenCount; _arrayBufferWriter.Clear(); } _stream.Flush(); } else if (BytesPending != 0) { _output.Advance(BytesPending); BytesCommitted += BytesPending; BytesPending = 0; } } public void Dispose() { if (_stream != null || _output != null) { Flush(); ResetHelper(); _stream = null; _arrayBufferWriter = null; _output = null; } } public async ValueTask DisposeAsync() { if (_stream != null || _output != null) { await FlushAsync().ConfigureAwait(continueOnCapturedContext: false); ResetHelper(); _stream = null; _arrayBufferWriter = null; _output = null; } } public async Task FlushAsync(CancellationToken cancellationToken = default(CancellationToken)) { CheckNotDisposed(); _memory = default(Memory); if (_stream != null) { if (BytesPending != 0) { _arrayBufferWriter.Advance(BytesPending); BytesPending = 0; MemoryMarshal.TryGetArray(_arrayBufferWriter.WrittenMemory, out var segment); await _stream.WriteAsync(segment.Array, segment.Offset, segment.Count, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); BytesCommitted += _arrayBufferWriter.WrittenCount; _arrayBufferWriter.Clear(); } await _stream.FlushAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } else if (BytesPending != 0) { _output.Advance(BytesPending); BytesCommitted += BytesPending; BytesPending = 0; } } public void WriteStartArray() { WriteStart(91); _tokenType = JsonTokenType.StartArray; } public void WriteStartObject() { WriteStart(123); _tokenType = JsonTokenType.StartObject; } private void WriteStart(byte token) { if (CurrentDepth >= 1000) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.DepthTooLarge, _currentDepth, 0, JsonTokenType.None); } if (_options.IndentedOrNotSkipValidation) { WriteStartSlow(token); } else { WriteStartMinimized(token); } _currentDepth &= int.MaxValue; _currentDepth++; } private void WriteStartMinimized(byte token) { if (_memory.Length - BytesPending < 2) { Grow(2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = token; } private void WriteStartSlow(byte token) { if (_options.Indented) { if (!_options.SkipValidation) { ValidateStart(); UpdateBitStackOnStart(token); } WriteStartIndented(token); } else { ValidateStart(); UpdateBitStackOnStart(token); WriteStartMinimized(token); } } private void ValidateStart() { if (_inObject) { if (_tokenType != JsonTokenType.PropertyName) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.CannotStartObjectArrayWithoutProperty, 0, 0, _tokenType); } } else if (CurrentDepth == 0 && _tokenType != 0) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.CannotStartObjectArrayAfterPrimitiveOrClose, 0, 0, _tokenType); } } private void WriteStartIndented(byte token) { int indentation = Indentation; int num = indentation + 1; int num2 = num + 3; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; } span[BytesPending++] = token; } public void WriteStartArray(JsonEncodedText propertyName) { WriteStartHelper(propertyName.EncodedUtf8Bytes, 91); _tokenType = JsonTokenType.StartArray; } public void WriteStartObject(JsonEncodedText propertyName) { WriteStartHelper(propertyName.EncodedUtf8Bytes, 123); _tokenType = JsonTokenType.StartObject; } private void WriteStartHelper(ReadOnlySpan utf8PropertyName, byte token) { ValidateDepth(); WriteStartByOptions(utf8PropertyName, token); _currentDepth &= int.MaxValue; _currentDepth++; } public void WriteStartArray(ReadOnlySpan utf8PropertyName) { ValidatePropertyNameAndDepth(utf8PropertyName); WriteStartEscape(utf8PropertyName, 91); _currentDepth &= int.MaxValue; _currentDepth++; _tokenType = JsonTokenType.StartArray; } public void WriteStartObject(ReadOnlySpan utf8PropertyName) { ValidatePropertyNameAndDepth(utf8PropertyName); WriteStartEscape(utf8PropertyName, 123); _currentDepth &= int.MaxValue; _currentDepth++; _tokenType = JsonTokenType.StartObject; } private void WriteStartEscape(ReadOnlySpan utf8PropertyName, byte token) { int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); if (num != -1) { WriteStartEscapeProperty(utf8PropertyName, token, num); } else { WriteStartByOptions(utf8PropertyName, token); } } private void WriteStartByOptions(ReadOnlySpan utf8PropertyName, byte token) { ValidateWritingProperty(token); if (_options.Indented) { WritePropertyNameIndented(utf8PropertyName, token); } else { WritePropertyNameMinimized(utf8PropertyName, token); } } private void WriteStartEscapeProperty(ReadOnlySpan utf8PropertyName, byte token, int firstEscapeIndexProp) { byte[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteStartByOptions(destination.Slice(0, written), token); if (array != null) { ArrayPool.Shared.Return(array); } } public void WriteStartArray(string propertyName) { WriteStartArray(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName"))); } public void WriteStartObject(string propertyName) { WriteStartObject(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName"))); } public void WriteStartArray(ReadOnlySpan propertyName) { ValidatePropertyNameAndDepth(propertyName); WriteStartEscape(propertyName, 91); _currentDepth &= int.MaxValue; _currentDepth++; _tokenType = JsonTokenType.StartArray; } public void WriteStartObject(ReadOnlySpan propertyName) { ValidatePropertyNameAndDepth(propertyName); WriteStartEscape(propertyName, 123); _currentDepth &= int.MaxValue; _currentDepth++; _tokenType = JsonTokenType.StartObject; } private void WriteStartEscape(ReadOnlySpan propertyName, byte token) { int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); if (num != -1) { WriteStartEscapeProperty(propertyName, token, num); } else { WriteStartByOptions(propertyName, token); } } private void WriteStartByOptions(ReadOnlySpan propertyName, byte token) { ValidateWritingProperty(token); if (_options.Indented) { WritePropertyNameIndented(propertyName, token); } else { WritePropertyNameMinimized(propertyName, token); } } private void WriteStartEscapeProperty(ReadOnlySpan propertyName, byte token, int firstEscapeIndexProp) { char[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteStartByOptions(destination.Slice(0, written), token); if (array != null) { ArrayPool.Shared.Return(array); } } public void WriteEndArray() { WriteEnd(93); _tokenType = JsonTokenType.EndArray; } public void WriteEndObject() { WriteEnd(125); _tokenType = JsonTokenType.EndObject; } private void WriteEnd(byte token) { if (_options.IndentedOrNotSkipValidation) { WriteEndSlow(token); } else { WriteEndMinimized(token); } SetFlagToAddListSeparatorBeforeNextItem(); if (CurrentDepth != 0) { _currentDepth--; } } private void WriteEndMinimized(byte token) { if (_memory.Length - BytesPending < 1) { Grow(1); } _memory.Span[BytesPending++] = token; } private void WriteEndSlow(byte token) { if (_options.Indented) { if (!_options.SkipValidation) { ValidateEnd(token); } WriteEndIndented(token); } else { ValidateEnd(token); WriteEndMinimized(token); } } private void ValidateEnd(byte token) { if (_bitStack.CurrentDepth <= 0 || _tokenType == JsonTokenType.PropertyName) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.MismatchedObjectArray, 0, token, _tokenType); } if (token == 93) { if (_inObject) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.MismatchedObjectArray, 0, token, _tokenType); } } else if (!_inObject) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.MismatchedObjectArray, 0, token, _tokenType); } _inObject = _bitStack.Pop(); } private void WriteEndIndented(byte token) { if (_tokenType == JsonTokenType.StartObject || _tokenType == JsonTokenType.StartArray) { WriteEndMinimized(token); return; } int num = Indentation; if (num != 0) { num -= 2; } int num2 = num + 3; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; WriteNewLine(span); JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), num); BytesPending += num; span[BytesPending++] = token; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void WriteNewLine(Span output) { if (s_newLineLength == 2) { output[BytesPending++] = 13; } output[BytesPending++] = 10; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void UpdateBitStackOnStart(byte token) { if (token == 91) { _bitStack.PushFalse(); _inObject = false; } else { _bitStack.PushTrue(); _inObject = true; } } private void Grow(int requiredSize) { if (_memory.Length == 0) { FirstCallToGetMemory(requiredSize); return; } int num = Math.Max(4096, requiredSize); if (_stream != null) { _memory = _arrayBufferWriter.GetMemory(checked(BytesPending + num)); return; } _output.Advance(BytesPending); BytesCommitted += BytesPending; BytesPending = 0; _memory = _output.GetMemory(num); if (_memory.Length < num) { ThrowHelper.ThrowInvalidOperationException_NeedLargerSpan(); } } private void FirstCallToGetMemory(int requiredSize) { int num = Math.Max(256, requiredSize); if (_stream != null) { _memory = _arrayBufferWriter.GetMemory(num); return; } _memory = _output.GetMemory(num); if (_memory.Length < num) { ThrowHelper.ThrowInvalidOperationException_NeedLargerSpan(); } } private void SetFlagToAddListSeparatorBeforeNextItem() { _currentDepth |= int.MinValue; } public void WriteBase64String(JsonEncodedText propertyName, ReadOnlySpan bytes) { ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; JsonWriterHelper.ValidateBytes(bytes); WriteBase64ByOptions(encodedUtf8Bytes, bytes); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteBase64String(string propertyName, ReadOnlySpan bytes) { WriteBase64String(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName")), bytes); } public void WriteBase64String(ReadOnlySpan propertyName, ReadOnlySpan bytes) { JsonWriterHelper.ValidatePropertyAndBytes(propertyName, bytes); WriteBase64Escape(propertyName, bytes); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteBase64String(ReadOnlySpan utf8PropertyName, ReadOnlySpan bytes) { JsonWriterHelper.ValidatePropertyAndBytes(utf8PropertyName, bytes); WriteBase64Escape(utf8PropertyName, bytes); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } private void WriteBase64Escape(ReadOnlySpan propertyName, ReadOnlySpan bytes) { int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); if (num != -1) { WriteBase64EscapeProperty(propertyName, bytes, num); } else { WriteBase64ByOptions(propertyName, bytes); } } private void WriteBase64Escape(ReadOnlySpan utf8PropertyName, ReadOnlySpan bytes) { int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); if (num != -1) { WriteBase64EscapeProperty(utf8PropertyName, bytes, num); } else { WriteBase64ByOptions(utf8PropertyName, bytes); } } private void WriteBase64EscapeProperty(ReadOnlySpan propertyName, ReadOnlySpan bytes, int firstEscapeIndexProp) { char[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteBase64ByOptions(destination.Slice(0, written), bytes); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteBase64EscapeProperty(ReadOnlySpan utf8PropertyName, ReadOnlySpan bytes, int firstEscapeIndexProp) { byte[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteBase64ByOptions(destination.Slice(0, written), bytes); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteBase64ByOptions(ReadOnlySpan propertyName, ReadOnlySpan bytes) { ValidateWritingProperty(); if (_options.Indented) { WriteBase64Indented(propertyName, bytes); } else { WriteBase64Minimized(propertyName, bytes); } } private void WriteBase64ByOptions(ReadOnlySpan utf8PropertyName, ReadOnlySpan bytes) { ValidateWritingProperty(); if (_options.Indented) { WriteBase64Indented(utf8PropertyName, bytes); } else { WriteBase64Minimized(utf8PropertyName, bytes); } } private void WriteBase64Minimized(ReadOnlySpan escapedPropertyName, ReadOnlySpan bytes) { int maxEncodedToUtf8Length = Base64.GetMaxEncodedToUtf8Length(bytes.Length); int num = escapedPropertyName.Length * 3 + maxEncodedToUtf8Length + 6; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 34; Base64EncodeAndWrite(bytes, span, maxEncodedToUtf8Length); span[BytesPending++] = 34; } private void WriteBase64Minimized(ReadOnlySpan escapedPropertyName, ReadOnlySpan bytes) { int maxEncodedToUtf8Length = Base64.GetMaxEncodedToUtf8Length(bytes.Length); int num = escapedPropertyName.Length + maxEncodedToUtf8Length + 6; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 34; Base64EncodeAndWrite(bytes, span, maxEncodedToUtf8Length); span[BytesPending++] = 34; } private void WriteBase64Indented(ReadOnlySpan escapedPropertyName, ReadOnlySpan bytes) { int indentation = Indentation; int maxEncodedToUtf8Length = Base64.GetMaxEncodedToUtf8Length(bytes.Length); int num = indentation + escapedPropertyName.Length * 3 + maxEncodedToUtf8Length + 7 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; span[BytesPending++] = 34; Base64EncodeAndWrite(bytes, span, maxEncodedToUtf8Length); span[BytesPending++] = 34; } private void WriteBase64Indented(ReadOnlySpan escapedPropertyName, ReadOnlySpan bytes) { int indentation = Indentation; int maxEncodedToUtf8Length = Base64.GetMaxEncodedToUtf8Length(bytes.Length); int num = indentation + escapedPropertyName.Length + maxEncodedToUtf8Length + 7 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; span[BytesPending++] = 34; Base64EncodeAndWrite(bytes, span, maxEncodedToUtf8Length); span[BytesPending++] = 34; } public void WriteString(JsonEncodedText propertyName, DateTime value) { ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; WriteStringByOptions(encodedUtf8Bytes, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteString(string propertyName, DateTime value) { WriteString(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName")), value); } public void WriteString(ReadOnlySpan propertyName, DateTime value) { JsonWriterHelper.ValidateProperty(propertyName); WriteStringEscape(propertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteString(ReadOnlySpan utf8PropertyName, DateTime value) { JsonWriterHelper.ValidateProperty(utf8PropertyName); WriteStringEscape(utf8PropertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } private void WriteStringEscape(ReadOnlySpan propertyName, DateTime value) { int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); if (num != -1) { WriteStringEscapeProperty(propertyName, value, num); } else { WriteStringByOptions(propertyName, value); } } private void WriteStringEscape(ReadOnlySpan utf8PropertyName, DateTime value) { int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); if (num != -1) { WriteStringEscapeProperty(utf8PropertyName, value, num); } else { WriteStringByOptions(utf8PropertyName, value); } } private void WriteStringEscapeProperty(ReadOnlySpan propertyName, DateTime value, int firstEscapeIndexProp) { char[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteStringByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteStringEscapeProperty(ReadOnlySpan utf8PropertyName, DateTime value, int firstEscapeIndexProp) { byte[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteStringByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteStringByOptions(ReadOnlySpan propertyName, DateTime value) { ValidateWritingProperty(); if (_options.Indented) { WriteStringIndented(propertyName, value); } else { WriteStringMinimized(propertyName, value); } } private void WriteStringByOptions(ReadOnlySpan utf8PropertyName, DateTime value) { ValidateWritingProperty(); if (_options.Indented) { WriteStringIndented(utf8PropertyName, value); } else { WriteStringMinimized(utf8PropertyName, value); } } private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, DateTime value) { int num = escapedPropertyName.Length * 3 + 33 + 6; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 34; JsonWriterHelper.WriteDateTimeTrimmed(span.Slice(BytesPending), value, out var bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, DateTime value) { int num = escapedPropertyName.Length + 33 + 5; int num2 = num + 1; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 34; JsonWriterHelper.WriteDateTimeTrimmed(span.Slice(BytesPending), value, out var bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } private void WriteStringIndented(ReadOnlySpan escapedPropertyName, DateTime value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length * 3 + 33 + 7 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; span[BytesPending++] = 34; JsonWriterHelper.WriteDateTimeTrimmed(span.Slice(BytesPending), value, out var bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } private void WriteStringIndented(ReadOnlySpan escapedPropertyName, DateTime value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length + 33 + 6; int num2 = num + 1 + s_newLineLength; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; span[BytesPending++] = 34; JsonWriterHelper.WriteDateTimeTrimmed(span.Slice(BytesPending), value, out var bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } internal void WritePropertyName(DateTime value) { Span buffer = stackalloc byte[33]; JsonWriterHelper.WriteDateTimeTrimmed(buffer, value, out var bytesWritten); WritePropertyNameUnescaped(buffer.Slice(0, bytesWritten)); } public void WriteString(JsonEncodedText propertyName, DateTimeOffset value) { ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; WriteStringByOptions(encodedUtf8Bytes, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteString(string propertyName, DateTimeOffset value) { WriteString(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName")), value); } public void WriteString(ReadOnlySpan propertyName, DateTimeOffset value) { JsonWriterHelper.ValidateProperty(propertyName); WriteStringEscape(propertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteString(ReadOnlySpan utf8PropertyName, DateTimeOffset value) { JsonWriterHelper.ValidateProperty(utf8PropertyName); WriteStringEscape(utf8PropertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } private void WriteStringEscape(ReadOnlySpan propertyName, DateTimeOffset value) { int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); if (num != -1) { WriteStringEscapeProperty(propertyName, value, num); } else { WriteStringByOptions(propertyName, value); } } private void WriteStringEscape(ReadOnlySpan utf8PropertyName, DateTimeOffset value) { int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); if (num != -1) { WriteStringEscapeProperty(utf8PropertyName, value, num); } else { WriteStringByOptions(utf8PropertyName, value); } } private void WriteStringEscapeProperty(ReadOnlySpan propertyName, DateTimeOffset value, int firstEscapeIndexProp) { char[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteStringByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteStringEscapeProperty(ReadOnlySpan utf8PropertyName, DateTimeOffset value, int firstEscapeIndexProp) { byte[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteStringByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteStringByOptions(ReadOnlySpan propertyName, DateTimeOffset value) { ValidateWritingProperty(); if (_options.Indented) { WriteStringIndented(propertyName, value); } else { WriteStringMinimized(propertyName, value); } } private void WriteStringByOptions(ReadOnlySpan utf8PropertyName, DateTimeOffset value) { ValidateWritingProperty(); if (_options.Indented) { WriteStringIndented(utf8PropertyName, value); } else { WriteStringMinimized(utf8PropertyName, value); } } private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, DateTimeOffset value) { int num = escapedPropertyName.Length * 3 + 33 + 6; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 34; JsonWriterHelper.WriteDateTimeOffsetTrimmed(span.Slice(BytesPending), value, out var bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, DateTimeOffset value) { int num = escapedPropertyName.Length + 33 + 5; int num2 = num + 1; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 34; JsonWriterHelper.WriteDateTimeOffsetTrimmed(span.Slice(BytesPending), value, out var bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } private void WriteStringIndented(ReadOnlySpan escapedPropertyName, DateTimeOffset value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length * 3 + 33 + 7 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; span[BytesPending++] = 34; JsonWriterHelper.WriteDateTimeOffsetTrimmed(span.Slice(BytesPending), value, out var bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } private void WriteStringIndented(ReadOnlySpan escapedPropertyName, DateTimeOffset value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length + 33 + 6; int num2 = num + 1 + s_newLineLength; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; span[BytesPending++] = 34; JsonWriterHelper.WriteDateTimeOffsetTrimmed(span.Slice(BytesPending), value, out var bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } internal void WritePropertyName(DateTimeOffset value) { Span buffer = stackalloc byte[33]; JsonWriterHelper.WriteDateTimeOffsetTrimmed(buffer, value, out var bytesWritten); WritePropertyNameUnescaped(buffer.Slice(0, bytesWritten)); } public void WriteNumber(JsonEncodedText propertyName, decimal value) { ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; WriteNumberByOptions(encodedUtf8Bytes, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } public void WriteNumber(string propertyName, decimal value) { WriteNumber(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName")), value); } public void WriteNumber(ReadOnlySpan propertyName, decimal value) { JsonWriterHelper.ValidateProperty(propertyName); WriteNumberEscape(propertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } public void WriteNumber(ReadOnlySpan utf8PropertyName, decimal value) { JsonWriterHelper.ValidateProperty(utf8PropertyName); WriteNumberEscape(utf8PropertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } private void WriteNumberEscape(ReadOnlySpan propertyName, decimal value) { int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); if (num != -1) { WriteNumberEscapeProperty(propertyName, value, num); } else { WriteNumberByOptions(propertyName, value); } } private void WriteNumberEscape(ReadOnlySpan utf8PropertyName, decimal value) { int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); if (num != -1) { WriteNumberEscapeProperty(utf8PropertyName, value, num); } else { WriteNumberByOptions(utf8PropertyName, value); } } private void WriteNumberEscapeProperty(ReadOnlySpan propertyName, decimal value, int firstEscapeIndexProp) { char[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteNumberByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyName, decimal value, int firstEscapeIndexProp) { byte[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteNumberByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteNumberByOptions(ReadOnlySpan propertyName, decimal value) { ValidateWritingProperty(); if (_options.Indented) { WriteNumberIndented(propertyName, value); } else { WriteNumberMinimized(propertyName, value); } } private void WriteNumberByOptions(ReadOnlySpan utf8PropertyName, decimal value) { ValidateWritingProperty(); if (_options.Indented) { WriteNumberIndented(utf8PropertyName, value); } else { WriteNumberMinimized(utf8PropertyName, value); } } private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, decimal value) { int num = escapedPropertyName.Length * 3 + 31 + 4; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, decimal value) { int num = escapedPropertyName.Length + 31 + 3; int num2 = num + 1; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, decimal value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length * 3 + 31 + 5 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, decimal value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length + 31 + 4; int num2 = num + 1 + s_newLineLength; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } internal void WritePropertyName(decimal value) { Span destination = stackalloc byte[31]; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten); WritePropertyNameUnescaped(destination.Slice(0, bytesWritten)); } public void WriteNumber(JsonEncodedText propertyName, double value) { ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; JsonWriterHelper.ValidateDouble(value); WriteNumberByOptions(encodedUtf8Bytes, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } public void WriteNumber(string propertyName, double value) { WriteNumber(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName")), value); } public void WriteNumber(ReadOnlySpan propertyName, double value) { JsonWriterHelper.ValidateProperty(propertyName); JsonWriterHelper.ValidateDouble(value); WriteNumberEscape(propertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } public void WriteNumber(ReadOnlySpan utf8PropertyName, double value) { JsonWriterHelper.ValidateProperty(utf8PropertyName); JsonWriterHelper.ValidateDouble(value); WriteNumberEscape(utf8PropertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } private void WriteNumberEscape(ReadOnlySpan propertyName, double value) { int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); if (num != -1) { WriteNumberEscapeProperty(propertyName, value, num); } else { WriteNumberByOptions(propertyName, value); } } private void WriteNumberEscape(ReadOnlySpan utf8PropertyName, double value) { int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); if (num != -1) { WriteNumberEscapeProperty(utf8PropertyName, value, num); } else { WriteNumberByOptions(utf8PropertyName, value); } } private void WriteNumberEscapeProperty(ReadOnlySpan propertyName, double value, int firstEscapeIndexProp) { char[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteNumberByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyName, double value, int firstEscapeIndexProp) { byte[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteNumberByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteNumberByOptions(ReadOnlySpan propertyName, double value) { ValidateWritingProperty(); if (_options.Indented) { WriteNumberIndented(propertyName, value); } else { WriteNumberMinimized(propertyName, value); } } private void WriteNumberByOptions(ReadOnlySpan utf8PropertyName, double value) { ValidateWritingProperty(); if (_options.Indented) { WriteNumberIndented(utf8PropertyName, value); } else { WriteNumberMinimized(utf8PropertyName, value); } } private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, double value) { int num = escapedPropertyName.Length * 3 + 128 + 4; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; int bytesWritten; bool flag = TryFormatDouble(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, double value) { int num = escapedPropertyName.Length + 128 + 3; int num2 = num + 1; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; int bytesWritten; bool flag = TryFormatDouble(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, double value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length * 3 + 128 + 5 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; int bytesWritten; bool flag = TryFormatDouble(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, double value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length + 128 + 4; int num2 = num + 1 + s_newLineLength; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; int bytesWritten; bool flag = TryFormatDouble(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } internal void WritePropertyName(double value) { JsonWriterHelper.ValidateDouble(value); Span destination = stackalloc byte[128]; int bytesWritten; bool flag = TryFormatDouble(value, destination, out bytesWritten); WritePropertyNameUnescaped(destination.Slice(0, bytesWritten)); } public void WriteNumber(JsonEncodedText propertyName, float value) { ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; JsonWriterHelper.ValidateSingle(value); WriteNumberByOptions(encodedUtf8Bytes, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } public void WriteNumber(string propertyName, float value) { WriteNumber(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName")), value); } public void WriteNumber(ReadOnlySpan propertyName, float value) { JsonWriterHelper.ValidateProperty(propertyName); JsonWriterHelper.ValidateSingle(value); WriteNumberEscape(propertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } public void WriteNumber(ReadOnlySpan utf8PropertyName, float value) { JsonWriterHelper.ValidateProperty(utf8PropertyName); JsonWriterHelper.ValidateSingle(value); WriteNumberEscape(utf8PropertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } private void WriteNumberEscape(ReadOnlySpan propertyName, float value) { int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); if (num != -1) { WriteNumberEscapeProperty(propertyName, value, num); } else { WriteNumberByOptions(propertyName, value); } } private void WriteNumberEscape(ReadOnlySpan utf8PropertyName, float value) { int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); if (num != -1) { WriteNumberEscapeProperty(utf8PropertyName, value, num); } else { WriteNumberByOptions(utf8PropertyName, value); } } private void WriteNumberEscapeProperty(ReadOnlySpan propertyName, float value, int firstEscapeIndexProp) { char[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteNumberByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyName, float value, int firstEscapeIndexProp) { byte[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteNumberByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteNumberByOptions(ReadOnlySpan propertyName, float value) { ValidateWritingProperty(); if (_options.Indented) { WriteNumberIndented(propertyName, value); } else { WriteNumberMinimized(propertyName, value); } } private void WriteNumberByOptions(ReadOnlySpan utf8PropertyName, float value) { ValidateWritingProperty(); if (_options.Indented) { WriteNumberIndented(utf8PropertyName, value); } else { WriteNumberMinimized(utf8PropertyName, value); } } private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, float value) { int num = escapedPropertyName.Length * 3 + 128 + 4; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; int bytesWritten; bool flag = TryFormatSingle(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, float value) { int num = escapedPropertyName.Length + 128 + 3; int num2 = num + 1; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; int bytesWritten; bool flag = TryFormatSingle(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, float value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length * 3 + 128 + 5 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; int bytesWritten; bool flag = TryFormatSingle(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, float value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length + 128 + 4; int num2 = num + 1 + s_newLineLength; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; int bytesWritten; bool flag = TryFormatSingle(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } internal void WritePropertyName(float value) { Span destination = stackalloc byte[128]; int bytesWritten; bool flag = TryFormatSingle(value, destination, out bytesWritten); WritePropertyNameUnescaped(destination.Slice(0, bytesWritten)); } internal void WriteNumber(ReadOnlySpan propertyName, ReadOnlySpan utf8FormattedNumber) { JsonWriterHelper.ValidateProperty(propertyName); JsonWriterHelper.ValidateValue(utf8FormattedNumber); JsonWriterHelper.ValidateNumber(utf8FormattedNumber); WriteNumberEscape(propertyName, utf8FormattedNumber); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } internal void WriteNumber(ReadOnlySpan utf8PropertyName, ReadOnlySpan utf8FormattedNumber) { JsonWriterHelper.ValidateProperty(utf8PropertyName); JsonWriterHelper.ValidateValue(utf8FormattedNumber); JsonWriterHelper.ValidateNumber(utf8FormattedNumber); WriteNumberEscape(utf8PropertyName, utf8FormattedNumber); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } internal void WriteNumber(JsonEncodedText propertyName, ReadOnlySpan utf8FormattedNumber) { JsonWriterHelper.ValidateValue(utf8FormattedNumber); JsonWriterHelper.ValidateNumber(utf8FormattedNumber); WriteNumberByOptions(propertyName.EncodedUtf8Bytes, utf8FormattedNumber); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } private void WriteNumberEscape(ReadOnlySpan propertyName, ReadOnlySpan value) { int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); if (num != -1) { WriteNumberEscapeProperty(propertyName, value, num); } else { WriteNumberByOptions(propertyName, value); } } private void WriteNumberEscape(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) { int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); if (num != -1) { WriteNumberEscapeProperty(utf8PropertyName, value, num); } else { WriteNumberByOptions(utf8PropertyName, value); } } private void WriteNumberEscapeProperty(ReadOnlySpan propertyName, ReadOnlySpan value, int firstEscapeIndexProp) { char[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteNumberByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyName, ReadOnlySpan value, int firstEscapeIndexProp) { byte[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteNumberByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteNumberByOptions(ReadOnlySpan propertyName, ReadOnlySpan value) { ValidateWritingProperty(); if (_options.Indented) { WriteLiteralIndented(propertyName, value); } else { WriteLiteralMinimized(propertyName, value); } } private void WriteNumberByOptions(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) { ValidateWritingProperty(); if (_options.Indented) { WriteLiteralIndented(utf8PropertyName, value); } else { WriteLiteralMinimized(utf8PropertyName, value); } } public void WriteString(JsonEncodedText propertyName, Guid value) { ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; WriteStringByOptions(encodedUtf8Bytes, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteString(string propertyName, Guid value) { WriteString(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName")), value); } public void WriteString(ReadOnlySpan propertyName, Guid value) { JsonWriterHelper.ValidateProperty(propertyName); WriteStringEscape(propertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteString(ReadOnlySpan utf8PropertyName, Guid value) { JsonWriterHelper.ValidateProperty(utf8PropertyName); WriteStringEscape(utf8PropertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } private void WriteStringEscape(ReadOnlySpan propertyName, Guid value) { int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); if (num != -1) { WriteStringEscapeProperty(propertyName, value, num); } else { WriteStringByOptions(propertyName, value); } } private void WriteStringEscape(ReadOnlySpan utf8PropertyName, Guid value) { int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); if (num != -1) { WriteStringEscapeProperty(utf8PropertyName, value, num); } else { WriteStringByOptions(utf8PropertyName, value); } } private void WriteStringEscapeProperty(ReadOnlySpan propertyName, Guid value, int firstEscapeIndexProp) { char[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteStringByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteStringEscapeProperty(ReadOnlySpan utf8PropertyName, Guid value, int firstEscapeIndexProp) { byte[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteStringByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteStringByOptions(ReadOnlySpan propertyName, Guid value) { ValidateWritingProperty(); if (_options.Indented) { WriteStringIndented(propertyName, value); } else { WriteStringMinimized(propertyName, value); } } private void WriteStringByOptions(ReadOnlySpan utf8PropertyName, Guid value) { ValidateWritingProperty(); if (_options.Indented) { WriteStringIndented(utf8PropertyName, value); } else { WriteStringMinimized(utf8PropertyName, value); } } private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, Guid value) { int num = escapedPropertyName.Length * 3 + 36 + 6; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 34; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, Guid value) { int num = escapedPropertyName.Length + 36 + 5; int num2 = num + 1; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 34; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } private void WriteStringIndented(ReadOnlySpan escapedPropertyName, Guid value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length * 3 + 36 + 7 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; span[BytesPending++] = 34; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } private void WriteStringIndented(ReadOnlySpan escapedPropertyName, Guid value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length + 36 + 6; int num2 = num + 1 + s_newLineLength; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; span[BytesPending++] = 34; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } internal void WritePropertyName(Guid value) { Span destination = stackalloc byte[36]; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten); WritePropertyNameUnescaped(destination.Slice(0, bytesWritten)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ValidatePropertyNameAndDepth(ReadOnlySpan propertyName) { if (propertyName.Length > 166666666 || CurrentDepth >= 1000) { ThrowHelper.ThrowInvalidOperationOrArgumentException(propertyName, _currentDepth); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ValidatePropertyNameAndDepth(ReadOnlySpan utf8PropertyName) { if (utf8PropertyName.Length > 166666666 || CurrentDepth >= 1000) { ThrowHelper.ThrowInvalidOperationOrArgumentException(utf8PropertyName, _currentDepth); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ValidateDepth() { if (CurrentDepth >= 1000) { ThrowHelper.ThrowInvalidOperationException(_currentDepth); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ValidateWritingProperty() { if (!_options.SkipValidation && (!_inObject || _tokenType == JsonTokenType.PropertyName)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.CannotWritePropertyWithinArray, 0, 0, _tokenType); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ValidateWritingProperty(byte token) { if (!_options.SkipValidation) { if (!_inObject || _tokenType == JsonTokenType.PropertyName) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.CannotWritePropertyWithinArray, 0, 0, _tokenType); } UpdateBitStackOnStart(token); } } private void WritePropertyNameMinimized(ReadOnlySpan escapedPropertyName, byte token) { int num = escapedPropertyName.Length + 4; int num2 = num + 1; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = token; } private void WritePropertyNameIndented(ReadOnlySpan escapedPropertyName, byte token) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length + 5; int num2 = num + 1 + s_newLineLength; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; span[BytesPending++] = token; } private void WritePropertyNameMinimized(ReadOnlySpan escapedPropertyName, byte token) { int num = escapedPropertyName.Length * 3 + 5; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = token; } private void WritePropertyNameIndented(ReadOnlySpan escapedPropertyName, byte token) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length * 3 + 6 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; span[BytesPending++] = token; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void TranscodeAndWrite(ReadOnlySpan escapedPropertyName, Span output) { ReadOnlySpan utf16Source = MemoryMarshal.AsBytes(escapedPropertyName); int bytesConsumed; int bytesWritten; OperationStatus operationStatus = JsonWriterHelper.ToUtf8(utf16Source, output.Slice(BytesPending), out bytesConsumed, out bytesWritten); BytesPending += bytesWritten; } public void WriteNull(JsonEncodedText propertyName) { WriteLiteralHelper(propertyName.EncodedUtf8Bytes, JsonConstants.NullValue); _tokenType = JsonTokenType.Null; } internal void WriteNullSection(ReadOnlySpan escapedPropertyNameSection) { if (_options.Indented) { ReadOnlySpan utf8PropertyName = escapedPropertyNameSection.Slice(1, escapedPropertyNameSection.Length - 3); WriteLiteralHelper(utf8PropertyName, JsonConstants.NullValue); _tokenType = JsonTokenType.Null; } else { ReadOnlySpan nullValue = JsonConstants.NullValue; WriteLiteralSection(escapedPropertyNameSection, nullValue); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Null; } } private void WriteLiteralHelper(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) { WriteLiteralByOptions(utf8PropertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); } public void WriteNull(string propertyName) { WriteNull(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName"))); } public void WriteNull(ReadOnlySpan propertyName) { JsonWriterHelper.ValidateProperty(propertyName); ReadOnlySpan nullValue = JsonConstants.NullValue; WriteLiteralEscape(propertyName, nullValue); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Null; } public void WriteNull(ReadOnlySpan utf8PropertyName) { JsonWriterHelper.ValidateProperty(utf8PropertyName); ReadOnlySpan nullValue = JsonConstants.NullValue; WriteLiteralEscape(utf8PropertyName, nullValue); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Null; } public void WriteBoolean(JsonEncodedText propertyName, bool value) { if (value) { WriteLiteralHelper(propertyName.EncodedUtf8Bytes, JsonConstants.TrueValue); _tokenType = JsonTokenType.True; } else { WriteLiteralHelper(propertyName.EncodedUtf8Bytes, JsonConstants.FalseValue); _tokenType = JsonTokenType.False; } } public void WriteBoolean(string propertyName, bool value) { WriteBoolean(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName")), value); } public void WriteBoolean(ReadOnlySpan propertyName, bool value) { JsonWriterHelper.ValidateProperty(propertyName); ReadOnlySpan value2 = (value ? JsonConstants.TrueValue : JsonConstants.FalseValue); WriteLiteralEscape(propertyName, value2); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = (value ? JsonTokenType.True : JsonTokenType.False); } public void WriteBoolean(ReadOnlySpan utf8PropertyName, bool value) { JsonWriterHelper.ValidateProperty(utf8PropertyName); ReadOnlySpan value2 = (value ? JsonConstants.TrueValue : JsonConstants.FalseValue); WriteLiteralEscape(utf8PropertyName, value2); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = (value ? JsonTokenType.True : JsonTokenType.False); } private void WriteLiteralEscape(ReadOnlySpan propertyName, ReadOnlySpan value) { int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); if (num != -1) { WriteLiteralEscapeProperty(propertyName, value, num); } else { WriteLiteralByOptions(propertyName, value); } } private void WriteLiteralEscape(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) { int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); if (num != -1) { WriteLiteralEscapeProperty(utf8PropertyName, value, num); } else { WriteLiteralByOptions(utf8PropertyName, value); } } private void WriteLiteralEscapeProperty(ReadOnlySpan propertyName, ReadOnlySpan value, int firstEscapeIndexProp) { char[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteLiteralByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteLiteralEscapeProperty(ReadOnlySpan utf8PropertyName, ReadOnlySpan value, int firstEscapeIndexProp) { byte[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteLiteralByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteLiteralByOptions(ReadOnlySpan propertyName, ReadOnlySpan value) { ValidateWritingProperty(); if (_options.Indented) { WriteLiteralIndented(propertyName, value); } else { WriteLiteralMinimized(propertyName, value); } } private void WriteLiteralByOptions(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) { ValidateWritingProperty(); if (_options.Indented) { WriteLiteralIndented(utf8PropertyName, value); } else { WriteLiteralMinimized(utf8PropertyName, value); } } private void WriteLiteralMinimized(ReadOnlySpan escapedPropertyName, ReadOnlySpan value) { int num = escapedPropertyName.Length * 3 + value.Length + 4; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; value.CopyTo(span.Slice(BytesPending)); BytesPending += value.Length; } private void WriteLiteralMinimized(ReadOnlySpan escapedPropertyName, ReadOnlySpan value) { int num = escapedPropertyName.Length + value.Length + 3; int num2 = num + 1; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; value.CopyTo(span.Slice(BytesPending)); BytesPending += value.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void WriteLiteralSection(ReadOnlySpan escapedPropertyNameSection, ReadOnlySpan value) { int num = escapedPropertyNameSection.Length + value.Length; int num2 = num + 1; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } escapedPropertyNameSection.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyNameSection.Length; value.CopyTo(span.Slice(BytesPending)); BytesPending += value.Length; } private void WriteLiteralIndented(ReadOnlySpan escapedPropertyName, ReadOnlySpan value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length * 3 + value.Length + 5 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; value.CopyTo(span.Slice(BytesPending)); BytesPending += value.Length; } private void WriteLiteralIndented(ReadOnlySpan escapedPropertyName, ReadOnlySpan value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length + value.Length + 4; int num2 = num + 1 + s_newLineLength; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; value.CopyTo(span.Slice(BytesPending)); BytesPending += value.Length; } internal void WritePropertyName(bool value) { Span destination = stackalloc byte[5]; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten); WritePropertyNameUnescaped(destination.Slice(0, bytesWritten)); } public void WriteNumber(JsonEncodedText propertyName, long value) { ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; WriteNumberByOptions(encodedUtf8Bytes, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } public void WriteNumber(string propertyName, long value) { WriteNumber(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName")), value); } public void WriteNumber(ReadOnlySpan propertyName, long value) { JsonWriterHelper.ValidateProperty(propertyName); WriteNumberEscape(propertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } public void WriteNumber(ReadOnlySpan utf8PropertyName, long value) { JsonWriterHelper.ValidateProperty(utf8PropertyName); WriteNumberEscape(utf8PropertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } public void WriteNumber(JsonEncodedText propertyName, int value) { WriteNumber(propertyName, (long)value); } public void WriteNumber(string propertyName, int value) { WriteNumber(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName")), (long)value); } public void WriteNumber(ReadOnlySpan propertyName, int value) { WriteNumber(propertyName, (long)value); } public void WriteNumber(ReadOnlySpan utf8PropertyName, int value) { WriteNumber(utf8PropertyName, (long)value); } private void WriteNumberEscape(ReadOnlySpan propertyName, long value) { int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); if (num != -1) { WriteNumberEscapeProperty(propertyName, value, num); } else { WriteNumberByOptions(propertyName, value); } } private void WriteNumberEscape(ReadOnlySpan utf8PropertyName, long value) { int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); if (num != -1) { WriteNumberEscapeProperty(utf8PropertyName, value, num); } else { WriteNumberByOptions(utf8PropertyName, value); } } private void WriteNumberEscapeProperty(ReadOnlySpan propertyName, long value, int firstEscapeIndexProp) { char[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteNumberByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyName, long value, int firstEscapeIndexProp) { byte[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteNumberByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteNumberByOptions(ReadOnlySpan propertyName, long value) { ValidateWritingProperty(); if (_options.Indented) { WriteNumberIndented(propertyName, value); } else { WriteNumberMinimized(propertyName, value); } } private void WriteNumberByOptions(ReadOnlySpan utf8PropertyName, long value) { ValidateWritingProperty(); if (_options.Indented) { WriteNumberIndented(utf8PropertyName, value); } else { WriteNumberMinimized(utf8PropertyName, value); } } private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, long value) { int num = escapedPropertyName.Length * 3 + 20 + 4; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, long value) { int num = escapedPropertyName.Length + 20 + 3; int num2 = num + 1; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, long value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length * 3 + 20 + 5 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, long value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length + 20 + 4; int num2 = num + 1 + s_newLineLength; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } internal void WritePropertyName(int value) { WritePropertyName((long)value); } internal void WritePropertyName(long value) { Span destination = stackalloc byte[20]; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten); WritePropertyNameUnescaped(destination.Slice(0, bytesWritten)); } public void WritePropertyName(JsonEncodedText propertyName) { WritePropertyNameHelper(propertyName.EncodedUtf8Bytes); } internal void WritePropertyNameSection(ReadOnlySpan escapedPropertyNameSection) { if (_options.Indented) { ReadOnlySpan utf8PropertyName = escapedPropertyNameSection.Slice(1, escapedPropertyNameSection.Length - 3); WritePropertyNameHelper(utf8PropertyName); } else { WriteStringPropertyNameSection(escapedPropertyNameSection); _currentDepth &= int.MaxValue; _tokenType = JsonTokenType.PropertyName; } } private void WritePropertyNameHelper(ReadOnlySpan utf8PropertyName) { WriteStringByOptionsPropertyName(utf8PropertyName); _currentDepth &= int.MaxValue; _tokenType = JsonTokenType.PropertyName; } public void WritePropertyName(string propertyName) { WritePropertyName(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName"))); } public void WritePropertyName(ReadOnlySpan propertyName) { JsonWriterHelper.ValidateProperty(propertyName); int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); if (num != -1) { WriteStringEscapeProperty(propertyName, num); } else { WriteStringByOptionsPropertyName(propertyName); } _currentDepth &= int.MaxValue; _tokenType = JsonTokenType.PropertyName; } private unsafe void WriteStringEscapeProperty(ReadOnlySpan propertyName, int firstEscapeIndexProp) { char[] array = null; if (firstEscapeIndexProp != -1) { int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); Span destination; if (maxEscapedLength > 256) { array = ArrayPool.Shared.Rent(maxEscapedLength); destination = array; } else { char* pointer = stackalloc char[maxEscapedLength]; destination = new Span(pointer, maxEscapedLength); } JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); propertyName = destination.Slice(0, written); } WriteStringByOptionsPropertyName(propertyName); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteStringByOptionsPropertyName(ReadOnlySpan propertyName) { ValidateWritingProperty(); if (_options.Indented) { WriteStringIndentedPropertyName(propertyName); } else { WriteStringMinimizedPropertyName(propertyName); } } private void WriteStringMinimizedPropertyName(ReadOnlySpan escapedPropertyName) { int num = escapedPropertyName.Length * 3 + 4; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; } private void WriteStringIndentedPropertyName(ReadOnlySpan escapedPropertyName) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length * 3 + 5 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; } public void WritePropertyName(ReadOnlySpan utf8PropertyName) { JsonWriterHelper.ValidateProperty(utf8PropertyName); int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); if (num != -1) { WriteStringEscapeProperty(utf8PropertyName, num); } else { WriteStringByOptionsPropertyName(utf8PropertyName); } _currentDepth &= int.MaxValue; _tokenType = JsonTokenType.PropertyName; } private void WritePropertyNameUnescaped(ReadOnlySpan utf8PropertyName) { JsonWriterHelper.ValidateProperty(utf8PropertyName); WriteStringByOptionsPropertyName(utf8PropertyName); _currentDepth &= int.MaxValue; _tokenType = JsonTokenType.PropertyName; } private unsafe void WriteStringEscapeProperty(ReadOnlySpan utf8PropertyName, int firstEscapeIndexProp) { byte[] array = null; if (firstEscapeIndexProp != -1) { int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); Span destination; if (maxEscapedLength > 256) { array = ArrayPool.Shared.Rent(maxEscapedLength); destination = array; } else { byte* pointer = stackalloc byte[(int)(uint)maxEscapedLength]; destination = new Span(pointer, maxEscapedLength); } JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); utf8PropertyName = destination.Slice(0, written); } WriteStringByOptionsPropertyName(utf8PropertyName); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteStringByOptionsPropertyName(ReadOnlySpan utf8PropertyName) { ValidateWritingProperty(); if (_options.Indented) { WriteStringIndentedPropertyName(utf8PropertyName); } else { WriteStringMinimizedPropertyName(utf8PropertyName); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void WriteStringMinimizedPropertyName(ReadOnlySpan escapedPropertyName) { int num = escapedPropertyName.Length + 3; int num2 = num + 1; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void WriteStringPropertyNameSection(ReadOnlySpan escapedPropertyNameSection) { int num = escapedPropertyNameSection.Length + 1; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } escapedPropertyNameSection.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyNameSection.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void WriteStringIndentedPropertyName(ReadOnlySpan escapedPropertyName) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length + 4; int num2 = num + 1 + s_newLineLength; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; } public void WriteString(JsonEncodedText propertyName, JsonEncodedText value) { WriteStringHelper(propertyName.EncodedUtf8Bytes, value.EncodedUtf8Bytes); } private void WriteStringHelper(ReadOnlySpan utf8PropertyName, ReadOnlySpan utf8Value) { WriteStringByOptions(utf8PropertyName, utf8Value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteString(string propertyName, JsonEncodedText value) { WriteString(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName")), value); } public void WriteString(string propertyName, string? value) { if (propertyName == null) { throw new ArgumentNullException("propertyName"); } if (value == null) { WriteNull(MemoryExtensions.AsSpan(propertyName)); } else { WriteString(MemoryExtensions.AsSpan(propertyName), MemoryExtensions.AsSpan(value)); } } public void WriteString(ReadOnlySpan propertyName, ReadOnlySpan value) { JsonWriterHelper.ValidatePropertyAndValue(propertyName, value); WriteStringEscape(propertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteString(ReadOnlySpan utf8PropertyName, ReadOnlySpan utf8Value) { JsonWriterHelper.ValidatePropertyAndValue(utf8PropertyName, utf8Value); WriteStringEscape(utf8PropertyName, utf8Value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteString(JsonEncodedText propertyName, string? value) { if (value == null) { WriteNull(propertyName); } else { WriteString(propertyName, MemoryExtensions.AsSpan(value)); } } public void WriteString(JsonEncodedText propertyName, ReadOnlySpan value) { WriteStringHelperEscapeValue(propertyName.EncodedUtf8Bytes, value); } private void WriteStringHelperEscapeValue(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) { JsonWriterHelper.ValidateValue(value); int num = JsonWriterHelper.NeedsEscaping(value, _options.Encoder); if (num != -1) { WriteStringEscapeValueOnly(utf8PropertyName, value, num); } else { WriteStringByOptions(utf8PropertyName, value); } SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteString(string propertyName, ReadOnlySpan value) { WriteString(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName")), value); } public void WriteString(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) { JsonWriterHelper.ValidatePropertyAndValue(utf8PropertyName, value); WriteStringEscape(utf8PropertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteString(JsonEncodedText propertyName, ReadOnlySpan utf8Value) { WriteStringHelperEscapeValue(propertyName.EncodedUtf8Bytes, utf8Value); } private void WriteStringHelperEscapeValue(ReadOnlySpan utf8PropertyName, ReadOnlySpan utf8Value) { JsonWriterHelper.ValidateValue(utf8Value); int num = JsonWriterHelper.NeedsEscaping(utf8Value, _options.Encoder); if (num != -1) { WriteStringEscapeValueOnly(utf8PropertyName, utf8Value, num); } else { WriteStringByOptions(utf8PropertyName, utf8Value); } SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteString(string propertyName, ReadOnlySpan utf8Value) { WriteString(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName")), utf8Value); } public void WriteString(ReadOnlySpan propertyName, ReadOnlySpan utf8Value) { JsonWriterHelper.ValidatePropertyAndValue(propertyName, utf8Value); WriteStringEscape(propertyName, utf8Value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteString(ReadOnlySpan propertyName, JsonEncodedText value) { WriteStringHelperEscapeProperty(propertyName, value.EncodedUtf8Bytes); } private void WriteStringHelperEscapeProperty(ReadOnlySpan propertyName, ReadOnlySpan utf8Value) { JsonWriterHelper.ValidateProperty(propertyName); int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); if (num != -1) { WriteStringEscapePropertyOnly(propertyName, utf8Value, num); } else { WriteStringByOptions(propertyName, utf8Value); } SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteString(ReadOnlySpan propertyName, string? value) { if (value == null) { WriteNull(propertyName); } else { WriteString(propertyName, MemoryExtensions.AsSpan(value)); } } public void WriteString(ReadOnlySpan utf8PropertyName, JsonEncodedText value) { WriteStringHelperEscapeProperty(utf8PropertyName, value.EncodedUtf8Bytes); } private void WriteStringHelperEscapeProperty(ReadOnlySpan utf8PropertyName, ReadOnlySpan utf8Value) { JsonWriterHelper.ValidateProperty(utf8PropertyName); int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); if (num != -1) { WriteStringEscapePropertyOnly(utf8PropertyName, utf8Value, num); } else { WriteStringByOptions(utf8PropertyName, utf8Value); } SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteString(ReadOnlySpan utf8PropertyName, string? value) { if (value == null) { WriteNull(utf8PropertyName); } else { WriteString(utf8PropertyName, MemoryExtensions.AsSpan(value)); } } private void WriteStringEscapeValueOnly(ReadOnlySpan escapedPropertyName, ReadOnlySpan utf8Value, int firstEscapeIndex) { byte[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8Value.Length, firstEscapeIndex); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(utf8Value, destination, firstEscapeIndex, _options.Encoder, out var written); WriteStringByOptions(escapedPropertyName, destination.Slice(0, written)); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteStringEscapeValueOnly(ReadOnlySpan escapedPropertyName, ReadOnlySpan value, int firstEscapeIndex) { char[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(value.Length, firstEscapeIndex); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(value, destination, firstEscapeIndex, _options.Encoder, out var written); WriteStringByOptions(escapedPropertyName, destination.Slice(0, written)); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteStringEscapePropertyOnly(ReadOnlySpan propertyName, ReadOnlySpan escapedValue, int firstEscapeIndex) { char[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndex); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndex, _options.Encoder, out var written); WriteStringByOptions(destination.Slice(0, written), escapedValue); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteStringEscapePropertyOnly(ReadOnlySpan utf8PropertyName, ReadOnlySpan escapedValue, int firstEscapeIndex) { byte[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndex); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndex, _options.Encoder, out var written); WriteStringByOptions(destination.Slice(0, written), escapedValue); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteStringEscape(ReadOnlySpan propertyName, ReadOnlySpan value) { int num = JsonWriterHelper.NeedsEscaping(value, _options.Encoder); int num2 = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); if (num + num2 != -2) { WriteStringEscapePropertyOrValue(propertyName, value, num2, num); } else { WriteStringByOptions(propertyName, value); } } private void WriteStringEscape(ReadOnlySpan utf8PropertyName, ReadOnlySpan utf8Value) { int num = JsonWriterHelper.NeedsEscaping(utf8Value, _options.Encoder); int num2 = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); if (num + num2 != -2) { WriteStringEscapePropertyOrValue(utf8PropertyName, utf8Value, num2, num); } else { WriteStringByOptions(utf8PropertyName, utf8Value); } } private void WriteStringEscape(ReadOnlySpan propertyName, ReadOnlySpan utf8Value) { int num = JsonWriterHelper.NeedsEscaping(utf8Value, _options.Encoder); int num2 = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); if (num + num2 != -2) { WriteStringEscapePropertyOrValue(propertyName, utf8Value, num2, num); } else { WriteStringByOptions(propertyName, utf8Value); } } private void WriteStringEscape(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) { int num = JsonWriterHelper.NeedsEscaping(value, _options.Encoder); int num2 = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); if (num + num2 != -2) { WriteStringEscapePropertyOrValue(utf8PropertyName, value, num2, num); } else { WriteStringByOptions(utf8PropertyName, value); } } private unsafe void WriteStringEscapePropertyOrValue(ReadOnlySpan propertyName, ReadOnlySpan value, int firstEscapeIndexProp, int firstEscapeIndexVal) { char[] array = null; char[] array2 = null; if (firstEscapeIndexVal != -1) { int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(value.Length, firstEscapeIndexVal); Span destination; if (maxEscapedLength > 256) { array = ArrayPool.Shared.Rent(maxEscapedLength); destination = array; } else { char* pointer = stackalloc char[maxEscapedLength]; destination = new Span(pointer, maxEscapedLength); } JsonWriterHelper.EscapeString(value, destination, firstEscapeIndexVal, _options.Encoder, out var written); value = destination.Slice(0, written); } if (firstEscapeIndexProp != -1) { int maxEscapedLength2 = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); Span destination2; if (maxEscapedLength2 > 256) { array2 = ArrayPool.Shared.Rent(maxEscapedLength2); destination2 = array2; } else { char* pointer2 = stackalloc char[maxEscapedLength2]; destination2 = new Span(pointer2, maxEscapedLength2); } JsonWriterHelper.EscapeString(propertyName, destination2, firstEscapeIndexProp, _options.Encoder, out var written2); propertyName = destination2.Slice(0, written2); } WriteStringByOptions(propertyName, value); if (array != null) { ArrayPool.Shared.Return(array); } if (array2 != null) { ArrayPool.Shared.Return(array2); } } private unsafe void WriteStringEscapePropertyOrValue(ReadOnlySpan utf8PropertyName, ReadOnlySpan utf8Value, int firstEscapeIndexProp, int firstEscapeIndexVal) { byte[] array = null; byte[] array2 = null; if (firstEscapeIndexVal != -1) { int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8Value.Length, firstEscapeIndexVal); Span destination; if (maxEscapedLength > 256) { array = ArrayPool.Shared.Rent(maxEscapedLength); destination = array; } else { byte* pointer = stackalloc byte[(int)(uint)maxEscapedLength]; destination = new Span(pointer, maxEscapedLength); } JsonWriterHelper.EscapeString(utf8Value, destination, firstEscapeIndexVal, _options.Encoder, out var written); utf8Value = destination.Slice(0, written); } if (firstEscapeIndexProp != -1) { int maxEscapedLength2 = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); Span destination2; if (maxEscapedLength2 > 256) { array2 = ArrayPool.Shared.Rent(maxEscapedLength2); destination2 = array2; } else { byte* pointer2 = stackalloc byte[(int)(uint)maxEscapedLength2]; destination2 = new Span(pointer2, maxEscapedLength2); } JsonWriterHelper.EscapeString(utf8PropertyName, destination2, firstEscapeIndexProp, _options.Encoder, out var written2); utf8PropertyName = destination2.Slice(0, written2); } WriteStringByOptions(utf8PropertyName, utf8Value); if (array != null) { ArrayPool.Shared.Return(array); } if (array2 != null) { ArrayPool.Shared.Return(array2); } } private unsafe void WriteStringEscapePropertyOrValue(ReadOnlySpan propertyName, ReadOnlySpan utf8Value, int firstEscapeIndexProp, int firstEscapeIndexVal) { byte[] array = null; char[] array2 = null; if (firstEscapeIndexVal != -1) { int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8Value.Length, firstEscapeIndexVal); Span destination; if (maxEscapedLength > 256) { array = ArrayPool.Shared.Rent(maxEscapedLength); destination = array; } else { byte* pointer = stackalloc byte[(int)(uint)maxEscapedLength]; destination = new Span(pointer, maxEscapedLength); } JsonWriterHelper.EscapeString(utf8Value, destination, firstEscapeIndexVal, _options.Encoder, out var written); utf8Value = destination.Slice(0, written); } if (firstEscapeIndexProp != -1) { int maxEscapedLength2 = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); Span destination2; if (maxEscapedLength2 > 256) { array2 = ArrayPool.Shared.Rent(maxEscapedLength2); destination2 = array2; } else { char* pointer2 = stackalloc char[maxEscapedLength2]; destination2 = new Span(pointer2, maxEscapedLength2); } JsonWriterHelper.EscapeString(propertyName, destination2, firstEscapeIndexProp, _options.Encoder, out var written2); propertyName = destination2.Slice(0, written2); } WriteStringByOptions(propertyName, utf8Value); if (array != null) { ArrayPool.Shared.Return(array); } if (array2 != null) { ArrayPool.Shared.Return(array2); } } private unsafe void WriteStringEscapePropertyOrValue(ReadOnlySpan utf8PropertyName, ReadOnlySpan value, int firstEscapeIndexProp, int firstEscapeIndexVal) { char[] array = null; byte[] array2 = null; if (firstEscapeIndexVal != -1) { int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(value.Length, firstEscapeIndexVal); Span destination; if (maxEscapedLength > 256) { array = ArrayPool.Shared.Rent(maxEscapedLength); destination = array; } else { char* pointer = stackalloc char[maxEscapedLength]; destination = new Span(pointer, maxEscapedLength); } JsonWriterHelper.EscapeString(value, destination, firstEscapeIndexVal, _options.Encoder, out var written); value = destination.Slice(0, written); } if (firstEscapeIndexProp != -1) { int maxEscapedLength2 = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); Span destination2; if (maxEscapedLength2 > 256) { array2 = ArrayPool.Shared.Rent(maxEscapedLength2); destination2 = array2; } else { byte* pointer2 = stackalloc byte[(int)(uint)maxEscapedLength2]; destination2 = new Span(pointer2, maxEscapedLength2); } JsonWriterHelper.EscapeString(utf8PropertyName, destination2, firstEscapeIndexProp, _options.Encoder, out var written2); utf8PropertyName = destination2.Slice(0, written2); } WriteStringByOptions(utf8PropertyName, value); if (array != null) { ArrayPool.Shared.Return(array); } if (array2 != null) { ArrayPool.Shared.Return(array2); } } private void WriteStringByOptions(ReadOnlySpan propertyName, ReadOnlySpan value) { ValidateWritingProperty(); if (_options.Indented) { WriteStringIndented(propertyName, value); } else { WriteStringMinimized(propertyName, value); } } private void WriteStringByOptions(ReadOnlySpan utf8PropertyName, ReadOnlySpan utf8Value) { ValidateWritingProperty(); if (_options.Indented) { WriteStringIndented(utf8PropertyName, utf8Value); } else { WriteStringMinimized(utf8PropertyName, utf8Value); } } private void WriteStringByOptions(ReadOnlySpan propertyName, ReadOnlySpan utf8Value) { ValidateWritingProperty(); if (_options.Indented) { WriteStringIndented(propertyName, utf8Value); } else { WriteStringMinimized(propertyName, utf8Value); } } private void WriteStringByOptions(ReadOnlySpan utf8PropertyName, ReadOnlySpan value) { ValidateWritingProperty(); if (_options.Indented) { WriteStringIndented(utf8PropertyName, value); } else { WriteStringMinimized(utf8PropertyName, value); } } private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, ReadOnlySpan escapedValue) { int num = (escapedPropertyName.Length + escapedValue.Length) * 3 + 6; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 34; TranscodeAndWrite(escapedValue, span); span[BytesPending++] = 34; } private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, ReadOnlySpan escapedValue) { int num = escapedPropertyName.Length + escapedValue.Length + 5; int num2 = num + 1; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 34; escapedValue.CopyTo(span.Slice(BytesPending)); BytesPending += escapedValue.Length; span[BytesPending++] = 34; } private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, ReadOnlySpan escapedValue) { int num = escapedPropertyName.Length * 3 + escapedValue.Length + 6; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 34; escapedValue.CopyTo(span.Slice(BytesPending)); BytesPending += escapedValue.Length; span[BytesPending++] = 34; } private void WriteStringMinimized(ReadOnlySpan escapedPropertyName, ReadOnlySpan escapedValue) { int num = escapedValue.Length * 3 + escapedPropertyName.Length + 6; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 34; TranscodeAndWrite(escapedValue, span); span[BytesPending++] = 34; } private void WriteStringIndented(ReadOnlySpan escapedPropertyName, ReadOnlySpan escapedValue) { int indentation = Indentation; int num = indentation + (escapedPropertyName.Length + escapedValue.Length) * 3 + 7 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; span[BytesPending++] = 34; TranscodeAndWrite(escapedValue, span); span[BytesPending++] = 34; } private void WriteStringIndented(ReadOnlySpan escapedPropertyName, ReadOnlySpan escapedValue) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length + escapedValue.Length + 6; int num2 = num + 1 + s_newLineLength; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; span[BytesPending++] = 34; escapedValue.CopyTo(span.Slice(BytesPending)); BytesPending += escapedValue.Length; span[BytesPending++] = 34; } private void WriteStringIndented(ReadOnlySpan escapedPropertyName, ReadOnlySpan escapedValue) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length * 3 + escapedValue.Length + 7 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; span[BytesPending++] = 34; escapedValue.CopyTo(span.Slice(BytesPending)); BytesPending += escapedValue.Length; span[BytesPending++] = 34; } private void WriteStringIndented(ReadOnlySpan escapedPropertyName, ReadOnlySpan escapedValue) { int indentation = Indentation; int num = indentation + escapedValue.Length * 3 + escapedPropertyName.Length + 7 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; span[BytesPending++] = 34; TranscodeAndWrite(escapedValue, span); span[BytesPending++] = 34; } [CLSCompliant(false)] public void WriteNumber(JsonEncodedText propertyName, ulong value) { ReadOnlySpan encodedUtf8Bytes = propertyName.EncodedUtf8Bytes; WriteNumberByOptions(encodedUtf8Bytes, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } [CLSCompliant(false)] public void WriteNumber(string propertyName, ulong value) { WriteNumber(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName")), value); } [CLSCompliant(false)] public void WriteNumber(ReadOnlySpan propertyName, ulong value) { JsonWriterHelper.ValidateProperty(propertyName); WriteNumberEscape(propertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } [CLSCompliant(false)] public void WriteNumber(ReadOnlySpan utf8PropertyName, ulong value) { JsonWriterHelper.ValidateProperty(utf8PropertyName); WriteNumberEscape(utf8PropertyName, value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } [CLSCompliant(false)] public void WriteNumber(JsonEncodedText propertyName, uint value) { WriteNumber(propertyName, (ulong)value); } [CLSCompliant(false)] public void WriteNumber(string propertyName, uint value) { WriteNumber(MemoryExtensions.AsSpan(propertyName ?? throw new ArgumentNullException("propertyName")), (ulong)value); } [CLSCompliant(false)] public void WriteNumber(ReadOnlySpan propertyName, uint value) { WriteNumber(propertyName, (ulong)value); } [CLSCompliant(false)] public void WriteNumber(ReadOnlySpan utf8PropertyName, uint value) { WriteNumber(utf8PropertyName, (ulong)value); } private void WriteNumberEscape(ReadOnlySpan propertyName, ulong value) { int num = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder); if (num != -1) { WriteNumberEscapeProperty(propertyName, value, num); } else { WriteNumberByOptions(propertyName, value); } } private void WriteNumberEscape(ReadOnlySpan utf8PropertyName, ulong value) { int num = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder); if (num != -1) { WriteNumberEscapeProperty(utf8PropertyName, value, num); } else { WriteNumberByOptions(utf8PropertyName, value); } } private void WriteNumberEscapeProperty(ReadOnlySpan propertyName, ulong value, int firstEscapeIndexProp) { char[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(propertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteNumberByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyName, ulong value, int firstEscapeIndexProp) { byte[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(utf8PropertyName, destination, firstEscapeIndexProp, _options.Encoder, out var written); WriteNumberByOptions(destination.Slice(0, written), value); if (array != null) { ArrayPool.Shared.Return(array); } } private void WriteNumberByOptions(ReadOnlySpan propertyName, ulong value) { ValidateWritingProperty(); if (_options.Indented) { WriteNumberIndented(propertyName, value); } else { WriteNumberMinimized(propertyName, value); } } private void WriteNumberByOptions(ReadOnlySpan utf8PropertyName, ulong value) { ValidateWritingProperty(); if (_options.Indented) { WriteNumberIndented(utf8PropertyName, value); } else { WriteNumberMinimized(utf8PropertyName, value); } } private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, ulong value) { int num = escapedPropertyName.Length * 3 + 20 + 4; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberMinimized(ReadOnlySpan escapedPropertyName, ulong value) { int num = escapedPropertyName.Length + 20 + 3; int num2 = num + 1; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, ulong value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length * 3 + 20 + 5 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; TranscodeAndWrite(escapedPropertyName, span); span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberIndented(ReadOnlySpan escapedPropertyName, ulong value) { int indentation = Indentation; int num = indentation + escapedPropertyName.Length + 20 + 4; int num2 = num + 1 + s_newLineLength; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 34; escapedPropertyName.CopyTo(span.Slice(BytesPending)); BytesPending += escapedPropertyName.Length; span[BytesPending++] = 34; span[BytesPending++] = 58; span[BytesPending++] = 32; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } internal void WritePropertyName(uint value) { WritePropertyName((ulong)value); } internal void WritePropertyName(ulong value) { Span destination = stackalloc byte[20]; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten); WritePropertyNameUnescaped(destination.Slice(0, bytesWritten)); } public void WriteBase64StringValue(ReadOnlySpan bytes) { JsonWriterHelper.ValidateBytes(bytes); WriteBase64ByOptions(bytes); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } private void WriteBase64ByOptions(ReadOnlySpan bytes) { if (!_options.SkipValidation) { ValidateWritingValue(); } if (_options.Indented) { WriteBase64Indented(bytes); } else { WriteBase64Minimized(bytes); } } private void WriteBase64Minimized(ReadOnlySpan bytes) { int maxEncodedToUtf8Length = Base64.GetMaxEncodedToUtf8Length(bytes.Length); int num = maxEncodedToUtf8Length + 3; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; Base64EncodeAndWrite(bytes, span, maxEncodedToUtf8Length); span[BytesPending++] = 34; } private void WriteBase64Indented(ReadOnlySpan bytes) { int indentation = Indentation; int maxEncodedToUtf8Length = Base64.GetMaxEncodedToUtf8Length(bytes.Length); int num = indentation + maxEncodedToUtf8Length + 3 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; } span[BytesPending++] = 34; Base64EncodeAndWrite(bytes, span, maxEncodedToUtf8Length); span[BytesPending++] = 34; } public void WriteCommentValue(string value) { WriteCommentValue(MemoryExtensions.AsSpan(value ?? throw new ArgumentNullException("value"))); } public void WriteCommentValue(ReadOnlySpan value) { JsonWriterHelper.ValidateValue(value); if (value.IndexOf(s_singleLineCommentDelimiter) != -1) { ThrowHelper.ThrowArgumentException_InvalidCommentValue(); } WriteCommentByOptions(value); } private void WriteCommentByOptions(ReadOnlySpan value) { if (_options.Indented) { WriteCommentIndented(value); } else { WriteCommentMinimized(value); } } private void WriteCommentMinimized(ReadOnlySpan value) { int num = value.Length * 3 + 4; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; span[BytesPending++] = 47; int bytesConsumed = BytesPending++; span[bytesConsumed] = 42; ReadOnlySpan utf16Source = MemoryMarshal.AsBytes(value); int bytesWritten; OperationStatus operationStatus = JsonWriterHelper.ToUtf8(utf16Source, span.Slice(BytesPending), out bytesConsumed, out bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 42; span[BytesPending++] = 47; } private void WriteCommentIndented(ReadOnlySpan value) { int indentation = Indentation; int num = indentation + value.Length * 3 + 4 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; span[BytesPending++] = 47; int bytesConsumed = BytesPending++; span[bytesConsumed] = 42; ReadOnlySpan utf16Source = MemoryMarshal.AsBytes(value); int bytesWritten; OperationStatus operationStatus = JsonWriterHelper.ToUtf8(utf16Source, span.Slice(BytesPending), out bytesConsumed, out bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 42; span[BytesPending++] = 47; } public void WriteCommentValue(ReadOnlySpan utf8Value) { JsonWriterHelper.ValidateValue(utf8Value); if (utf8Value.IndexOf(SingleLineCommentDelimiterUtf8) != -1) { ThrowHelper.ThrowArgumentException_InvalidCommentValue(); } WriteCommentByOptions(utf8Value); } private void WriteCommentByOptions(ReadOnlySpan utf8Value) { if (_options.Indented) { WriteCommentIndented(utf8Value); } else { WriteCommentMinimized(utf8Value); } } private void WriteCommentMinimized(ReadOnlySpan utf8Value) { int num = utf8Value.Length + 4; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; span[BytesPending++] = 47; span[BytesPending++] = 42; utf8Value.CopyTo(span.Slice(BytesPending)); BytesPending += utf8Value.Length; span[BytesPending++] = 42; span[BytesPending++] = 47; } private void WriteCommentIndented(ReadOnlySpan utf8Value) { int indentation = Indentation; int num = indentation + utf8Value.Length + 4; int num2 = num + s_newLineLength; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; } span[BytesPending++] = 47; span[BytesPending++] = 42; utf8Value.CopyTo(span.Slice(BytesPending)); BytesPending += utf8Value.Length; span[BytesPending++] = 42; span[BytesPending++] = 47; } public void WriteStringValue(DateTime value) { if (!_options.SkipValidation) { ValidateWritingValue(); } if (_options.Indented) { WriteStringValueIndented(value); } else { WriteStringValueMinimized(value); } SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } private void WriteStringValueMinimized(DateTime value) { int num = 36; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; JsonWriterHelper.WriteDateTimeTrimmed(span.Slice(BytesPending), value, out var bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } private void WriteStringValueIndented(DateTime value) { int indentation = Indentation; int num = indentation + 33 + 3 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; } span[BytesPending++] = 34; JsonWriterHelper.WriteDateTimeTrimmed(span.Slice(BytesPending), value, out var bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } public void WriteStringValue(DateTimeOffset value) { if (!_options.SkipValidation) { ValidateWritingValue(); } if (_options.Indented) { WriteStringValueIndented(value); } else { WriteStringValueMinimized(value); } SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } private void WriteStringValueMinimized(DateTimeOffset value) { int num = 36; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; JsonWriterHelper.WriteDateTimeOffsetTrimmed(span.Slice(BytesPending), value, out var bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } private void WriteStringValueIndented(DateTimeOffset value) { int indentation = Indentation; int num = indentation + 33 + 3 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; } span[BytesPending++] = 34; JsonWriterHelper.WriteDateTimeOffsetTrimmed(span.Slice(BytesPending), value, out var bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } public void WriteNumberValue(decimal value) { if (!_options.SkipValidation) { ValidateWritingValue(); } if (_options.Indented) { WriteNumberValueIndented(value); } else { WriteNumberValueMinimized(value); } SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } private void WriteNumberValueMinimized(decimal value) { int num = 32; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberValueIndented(decimal value) { int indentation = Indentation; int num = indentation + 31 + 1 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; } int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } internal void WriteNumberValueAsString(decimal value) { Span destination = stackalloc byte[31]; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten); WriteNumberValueAsStringUnescaped(destination.Slice(0, bytesWritten)); } public void WriteNumberValue(double value) { JsonWriterHelper.ValidateDouble(value); if (!_options.SkipValidation) { ValidateWritingValue(); } if (_options.Indented) { WriteNumberValueIndented(value); } else { WriteNumberValueMinimized(value); } SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } private void WriteNumberValueMinimized(double value) { int num = 129; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } int bytesWritten; bool flag = TryFormatDouble(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberValueIndented(double value) { int indentation = Indentation; int num = indentation + 128 + 1 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; } int bytesWritten; bool flag = TryFormatDouble(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private static bool TryFormatDouble(double value, Span destination, out int bytesWritten) { string text = value.ToString("G17", CultureInfo.InvariantCulture); if (text.Length > destination.Length) { bytesWritten = 0; return false; } try { byte[] bytes = Encoding.UTF8.GetBytes(text); if (bytes.Length > destination.Length) { bytesWritten = 0; return false; } bytes.CopyTo(destination); bytesWritten = bytes.Length; return true; } catch { bytesWritten = 0; return false; } } internal void WriteNumberValueAsString(double value) { Span destination = stackalloc byte[128]; int bytesWritten; bool flag = TryFormatDouble(value, destination, out bytesWritten); WriteNumberValueAsStringUnescaped(destination.Slice(0, bytesWritten)); } internal void WriteFloatingPointConstant(double value) { if (double.IsNaN(value)) { WriteNumberValueAsStringUnescaped(JsonConstants.NaNValue); } else if (double.IsPositiveInfinity(value)) { WriteNumberValueAsStringUnescaped(JsonConstants.PositiveInfinityValue); } else if (double.IsNegativeInfinity(value)) { WriteNumberValueAsStringUnescaped(JsonConstants.NegativeInfinityValue); } else { WriteNumberValue(value); } } public void WriteNumberValue(float value) { JsonWriterHelper.ValidateSingle(value); if (!_options.SkipValidation) { ValidateWritingValue(); } if (_options.Indented) { WriteNumberValueIndented(value); } else { WriteNumberValueMinimized(value); } SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } private void WriteNumberValueMinimized(float value) { int num = 129; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } int bytesWritten; bool flag = TryFormatSingle(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberValueIndented(float value) { int indentation = Indentation; int num = indentation + 128 + 1 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; } int bytesWritten; bool flag = TryFormatSingle(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private static bool TryFormatSingle(float value, Span destination, out int bytesWritten) { string text = value.ToString("G9", CultureInfo.InvariantCulture); if (text.Length > destination.Length) { bytesWritten = 0; return false; } try { byte[] bytes = Encoding.UTF8.GetBytes(text); if (bytes.Length > destination.Length) { bytesWritten = 0; return false; } bytes.CopyTo(destination); bytesWritten = bytes.Length; return true; } catch { bytesWritten = 0; return false; } } internal void WriteNumberValueAsString(float value) { Span destination = stackalloc byte[128]; int bytesWritten; bool flag = TryFormatSingle(value, destination, out bytesWritten); WriteNumberValueAsStringUnescaped(destination.Slice(0, bytesWritten)); } internal void WriteFloatingPointConstant(float value) { if (float.IsNaN(value)) { WriteNumberValueAsStringUnescaped(JsonConstants.NaNValue); } else if (float.IsPositiveInfinity(value)) { WriteNumberValueAsStringUnescaped(JsonConstants.PositiveInfinityValue); } else if (float.IsNegativeInfinity(value)) { WriteNumberValueAsStringUnescaped(JsonConstants.NegativeInfinityValue); } else { WriteNumberValue(value); } } internal void WriteNumberValue(ReadOnlySpan utf8FormattedNumber) { JsonWriterHelper.ValidateValue(utf8FormattedNumber); JsonWriterHelper.ValidateNumber(utf8FormattedNumber); if (!_options.SkipValidation) { ValidateWritingValue(); } if (_options.Indented) { WriteNumberValueIndented(utf8FormattedNumber); } else { WriteNumberValueMinimized(utf8FormattedNumber); } SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } private void WriteNumberValueMinimized(ReadOnlySpan utf8Value) { int num = utf8Value.Length + 1; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } utf8Value.CopyTo(span.Slice(BytesPending)); BytesPending += utf8Value.Length; } private void WriteNumberValueIndented(ReadOnlySpan utf8Value) { int indentation = Indentation; int num = indentation + utf8Value.Length + 1 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; } utf8Value.CopyTo(span.Slice(BytesPending)); BytesPending += utf8Value.Length; } public void WriteStringValue(Guid value) { if (!_options.SkipValidation) { ValidateWritingValue(); } if (_options.Indented) { WriteStringValueIndented(value); } else { WriteStringValueMinimized(value); } SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } private void WriteStringValueMinimized(Guid value) { int num = 39; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } private void WriteStringValueIndented(Guid value) { int indentation = Indentation; int num = indentation + 36 + 3 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; } span[BytesPending++] = 34; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; span[BytesPending++] = 34; } private void ValidateWritingValue() { if (_inObject) { if (_tokenType != JsonTokenType.PropertyName) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.CannotWriteValueWithinObject, 0, 0, _tokenType); } } else if (CurrentDepth == 0 && _tokenType != 0) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.CannotWriteValueAfterPrimitiveOrClose, 0, 0, _tokenType); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void Base64EncodeAndWrite(ReadOnlySpan bytes, Span output, int encodingLength) { byte[] array = null; Span span = ((encodingLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(encodingLength))) : stackalloc byte[encodingLength]); Span utf = span; int bytesConsumed; int bytesWritten; OperationStatus operationStatus = Base64.EncodeToUtf8(bytes, utf, out bytesConsumed, out bytesWritten); utf = utf.Slice(0, bytesWritten); Span destination = output.Slice(BytesPending); utf.Slice(0, bytesWritten).CopyTo(destination); BytesPending += bytesWritten; if (array != null) { ArrayPool.Shared.Return(array); } } public void WriteNullValue() { WriteLiteralByOptions(JsonConstants.NullValue); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Null; } public void WriteBooleanValue(bool value) { if (value) { WriteLiteralByOptions(JsonConstants.TrueValue); _tokenType = JsonTokenType.True; } else { WriteLiteralByOptions(JsonConstants.FalseValue); _tokenType = JsonTokenType.False; } SetFlagToAddListSeparatorBeforeNextItem(); } private void WriteLiteralByOptions(ReadOnlySpan utf8Value) { if (!_options.SkipValidation) { ValidateWritingValue(); } if (_options.Indented) { WriteLiteralIndented(utf8Value); } else { WriteLiteralMinimized(utf8Value); } } private void WriteLiteralMinimized(ReadOnlySpan utf8Value) { int num = utf8Value.Length + 1; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } utf8Value.CopyTo(span.Slice(BytesPending)); BytesPending += utf8Value.Length; } private void WriteLiteralIndented(ReadOnlySpan utf8Value) { int indentation = Indentation; int num = indentation + utf8Value.Length + 1 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; } utf8Value.CopyTo(span.Slice(BytesPending)); BytesPending += utf8Value.Length; } public void WriteNumberValue(int value) { WriteNumberValue((long)value); } public void WriteNumberValue(long value) { if (!_options.SkipValidation) { ValidateWritingValue(); } if (_options.Indented) { WriteNumberValueIndented(value); } else { WriteNumberValueMinimized(value); } SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } private void WriteNumberValueMinimized(long value) { int num = 21; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberValueIndented(long value) { int indentation = Indentation; int num = indentation + 20 + 1 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; } int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } internal void WriteNumberValueAsString(long value) { Span destination = stackalloc byte[20]; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten); WriteNumberValueAsStringUnescaped(destination.Slice(0, bytesWritten)); } public void WriteStringValue(JsonEncodedText value) { ReadOnlySpan encodedUtf8Bytes = value.EncodedUtf8Bytes; WriteStringByOptions(encodedUtf8Bytes); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } public void WriteStringValue(string? value) { if (value == null) { WriteNullValue(); } else { WriteStringValue(MemoryExtensions.AsSpan(value)); } } public void WriteStringValue(ReadOnlySpan value) { JsonWriterHelper.ValidateValue(value); WriteStringEscape(value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } private void WriteStringEscape(ReadOnlySpan value) { int num = JsonWriterHelper.NeedsEscaping(value, _options.Encoder); if (num != -1) { WriteStringEscapeValue(value, num); } else { WriteStringByOptions(value); } } private void WriteStringByOptions(ReadOnlySpan value) { if (!_options.SkipValidation) { ValidateWritingValue(); } if (_options.Indented) { WriteStringIndented(value); } else { WriteStringMinimized(value); } } private void WriteStringMinimized(ReadOnlySpan escapedValue) { int num = escapedValue.Length * 3 + 3; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; TranscodeAndWrite(escapedValue, span); span[BytesPending++] = 34; } private void WriteStringIndented(ReadOnlySpan escapedValue) { int indentation = Indentation; int num = indentation + escapedValue.Length * 3 + 3 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; } span[BytesPending++] = 34; TranscodeAndWrite(escapedValue, span); span[BytesPending++] = 34; } private void WriteStringEscapeValue(ReadOnlySpan value, int firstEscapeIndexVal) { char[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(value.Length, firstEscapeIndexVal); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc char[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(value, destination, firstEscapeIndexVal, _options.Encoder, out var written); WriteStringByOptions(destination.Slice(0, written)); if (array != null) { ArrayPool.Shared.Return(array); } } public void WriteStringValue(ReadOnlySpan utf8Value) { JsonWriterHelper.ValidateValue(utf8Value); WriteStringEscape(utf8Value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } private void WriteStringEscape(ReadOnlySpan utf8Value) { int num = JsonWriterHelper.NeedsEscaping(utf8Value, _options.Encoder); if (num != -1) { WriteStringEscapeValue(utf8Value, num); } else { WriteStringByOptions(utf8Value); } } private void WriteStringByOptions(ReadOnlySpan utf8Value) { if (!_options.SkipValidation) { ValidateWritingValue(); } if (_options.Indented) { WriteStringIndented(utf8Value); } else { WriteStringMinimized(utf8Value); } } private void WriteStringMinimized(ReadOnlySpan escapedValue) { int num = escapedValue.Length + 2; int num2 = num + 1; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } span[BytesPending++] = 34; escapedValue.CopyTo(span.Slice(BytesPending)); BytesPending += escapedValue.Length; span[BytesPending++] = 34; } private void WriteStringIndented(ReadOnlySpan escapedValue) { int indentation = Indentation; int num = indentation + escapedValue.Length + 2; int num2 = num + 1 + s_newLineLength; if (_memory.Length - BytesPending < num2) { Grow(num2); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; } span[BytesPending++] = 34; escapedValue.CopyTo(span.Slice(BytesPending)); BytesPending += escapedValue.Length; span[BytesPending++] = 34; } private void WriteStringEscapeValue(ReadOnlySpan utf8Value, int firstEscapeIndexVal) { byte[] array = null; int maxEscapedLength = JsonWriterHelper.GetMaxEscapedLength(utf8Value.Length, firstEscapeIndexVal); Span span = ((maxEscapedLength > 256) ? ((Span)(array = ArrayPool.Shared.Rent(maxEscapedLength))) : stackalloc byte[maxEscapedLength]); Span destination = span; JsonWriterHelper.EscapeString(utf8Value, destination, firstEscapeIndexVal, _options.Encoder, out var written); WriteStringByOptions(destination.Slice(0, written)); if (array != null) { ArrayPool.Shared.Return(array); } } internal void WriteNumberValueAsStringUnescaped(ReadOnlySpan utf8Value) { WriteStringByOptions(utf8Value); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } [CLSCompliant(false)] public void WriteNumberValue(uint value) { WriteNumberValue((ulong)value); } [CLSCompliant(false)] public void WriteNumberValue(ulong value) { if (!_options.SkipValidation) { ValidateWritingValue(); } if (_options.Indented) { WriteNumberValueIndented(value); } else { WriteNumberValueMinimized(value); } SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } private void WriteNumberValueMinimized(ulong value) { int num = 21; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } private void WriteNumberValueIndented(ulong value) { int indentation = Indentation; int num = indentation + 20 + 1 + s_newLineLength; if (_memory.Length - BytesPending < num) { Grow(num); } Span span = _memory.Span; if (_currentDepth < 0) { span[BytesPending++] = 44; } if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != 0) { WriteNewLine(span); } JsonWriterHelper.WriteIndentation(span.Slice(BytesPending), indentation); BytesPending += indentation; } int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, span.Slice(BytesPending), out bytesWritten); BytesPending += bytesWritten; } internal void WriteNumberValueAsString(ulong value) { Span destination = stackalloc byte[20]; int bytesWritten; bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten); WriteNumberValueAsStringUnescaped(destination.Slice(0, bytesWritten)); } } } namespace System.Text.Json.Serialization { internal abstract class JsonAttribute : Attribute { } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)] internal sealed class JsonConstructorAttribute : JsonAttribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] internal class JsonConverterAttribute : JsonAttribute { [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] public Type? ConverterType { get; private set; } public JsonConverterAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type converterType) { ConverterType = converterType; } protected JsonConverterAttribute() { } public virtual JsonConverter? CreateConverter(Type typeToConvert) { return null; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] internal sealed class JsonExtensionDataAttribute : JsonAttribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] internal sealed class JsonIgnoreAttribute : JsonAttribute { public JsonIgnoreCondition Condition { get; set; } = JsonIgnoreCondition.Always; } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] internal sealed class JsonIncludeAttribute : JsonAttribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] internal sealed class JsonNumberHandlingAttribute : JsonAttribute { public JsonNumberHandling Handling { get; } public JsonNumberHandlingAttribute(JsonNumberHandling handling) { if (!JsonSerializer.IsValidNumberHandlingValue(handling)) { throw new ArgumentOutOfRangeException("handling"); } Handling = handling; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] internal sealed class JsonPropertyNameAttribute : JsonAttribute { public string Name { get; } public JsonPropertyNameAttribute(string name) { Name = name; } } internal sealed class ConverterList : IList, ICollection, IEnumerable, IEnumerable { private readonly List _list = new List(); private readonly JsonSerializerOptions _options; public JsonConverter this[int index] { get { return _list[index]; } set { if (value == null) { throw new ArgumentNullException("value"); } _options.VerifyMutable(); _list[index] = value; } } public int Count => _list.Count; public bool IsReadOnly => false; public ConverterList(JsonSerializerOptions options) { _options = options; } public ConverterList(JsonSerializerOptions options, ConverterList source) { _options = options; _list = new List(source._list); } public void Add(JsonConverter item) { if (item == null) { throw new ArgumentNullException("item"); } _options.VerifyMutable(); _list.Add(item); } public void Clear() { _options.VerifyMutable(); _list.Clear(); } public bool Contains(JsonConverter item) { return _list.Contains(item); } public void CopyTo(JsonConverter[] array, int arrayIndex) { _list.CopyTo(array, arrayIndex); } public IEnumerator GetEnumerator() { return _list.GetEnumerator(); } public int IndexOf(JsonConverter item) { return _list.IndexOf(item); } public void Insert(int index, JsonConverter item) { if (item == null) { throw new ArgumentNullException("item"); } _options.VerifyMutable(); _list.Insert(index, item); } public bool Remove(JsonConverter item) { _options.VerifyMutable(); return _list.Remove(item); } public void RemoveAt(int index) { _options.VerifyMutable(); _list.RemoveAt(index); } IEnumerator IEnumerable.GetEnumerator() { return _list.GetEnumerator(); } } internal static class IEnumerableConverterFactoryHelpers { private const string ImmutableArrayGenericTypeName = "System.Collections.Immutable.ImmutableArray`1"; private const string ImmutableListGenericTypeName = "System.Collections.Immutable.ImmutableList`1"; private const string ImmutableListGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableList`1"; private const string ImmutableStackGenericTypeName = "System.Collections.Immutable.ImmutableStack`1"; private const string ImmutableStackGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableStack`1"; private const string ImmutableQueueGenericTypeName = "System.Collections.Immutable.ImmutableQueue`1"; private const string ImmutableQueueGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableQueue`1"; private const string ImmutableSortedSetGenericTypeName = "System.Collections.Immutable.ImmutableSortedSet`1"; private const string ImmutableHashSetGenericTypeName = "System.Collections.Immutable.ImmutableHashSet`1"; private const string ImmutableSetGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableSet`1"; private const string ImmutableDictionaryGenericTypeName = "System.Collections.Immutable.ImmutableDictionary`2"; private const string ImmutableDictionaryGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableDictionary`2"; private const string ImmutableSortedDictionaryGenericTypeName = "System.Collections.Immutable.ImmutableSortedDictionary`2"; private const string ImmutableArrayTypeName = "System.Collections.Immutable.ImmutableArray"; private const string ImmutableListTypeName = "System.Collections.Immutable.ImmutableList"; private const string ImmutableStackTypeName = "System.Collections.Immutable.ImmutableStack"; private const string ImmutableQueueTypeName = "System.Collections.Immutable.ImmutableQueue"; private const string ImmutableSortedSetTypeName = "System.Collections.Immutable.ImmutableSortedSet"; private const string ImmutableHashSetTypeName = "System.Collections.Immutable.ImmutableHashSet"; private const string ImmutableDictionaryTypeName = "System.Collections.Immutable.ImmutableDictionary"; private const string ImmutableSortedDictionaryTypeName = "System.Collections.Immutable.ImmutableSortedDictionary"; private const string CreateRangeMethodName = "CreateRange"; private const string CreateRangeMethodNameForEnumerable = "CreateRange`1"; private const string CreateRangeMethodNameForDictionary = "CreateRange`2"; private const string ImmutableCollectionsAssembly = "System.Collections.Immutable"; internal static Type GetCompatibleGenericBaseClass(this Type type, Type baseType) { Type type2 = type; while (type2 != null && type2 != JsonClassInfo.ObjectType) { if (type2.IsGenericType) { Type genericTypeDefinition = type2.GetGenericTypeDefinition(); if (genericTypeDefinition == baseType) { return type2; } } type2 = type2.BaseType; } return null; } internal static Type GetCompatibleGenericInterface(this Type type, Type interfaceType) { Type type2 = type; if (type2.IsGenericType) { type2 = type2.GetGenericTypeDefinition(); } if (type2 == interfaceType) { return type; } Type[] interfaces = type.GetInterfaces(); foreach (Type type3 in interfaces) { if (type3.IsGenericType) { Type genericTypeDefinition = type3.GetGenericTypeDefinition(); if (genericTypeDefinition == interfaceType) { return type3; } } } return null; } public static bool IsImmutableDictionaryType(this Type type) { if (!type.IsGenericType || !type.Assembly.FullName.StartsWith("System.Collections.Immutable,", StringComparison.Ordinal)) { return false; } switch (type.GetGenericTypeDefinition().FullName) { case "System.Collections.Immutable.ImmutableDictionary`2": case "System.Collections.Immutable.IImmutableDictionary`2": case "System.Collections.Immutable.ImmutableSortedDictionary`2": return true; default: return false; } } public static bool IsImmutableEnumerableType(this Type type) { if (!type.IsGenericType || !type.Assembly.FullName.StartsWith("System.Collections.Immutable,", StringComparison.Ordinal)) { return false; } switch (type.GetGenericTypeDefinition().FullName) { case "System.Collections.Immutable.ImmutableArray`1": case "System.Collections.Immutable.ImmutableList`1": case "System.Collections.Immutable.IImmutableList`1": case "System.Collections.Immutable.ImmutableStack`1": case "System.Collections.Immutable.IImmutableStack`1": case "System.Collections.Immutable.ImmutableQueue`1": case "System.Collections.Immutable.IImmutableQueue`1": case "System.Collections.Immutable.ImmutableSortedSet`1": case "System.Collections.Immutable.ImmutableHashSet`1": case "System.Collections.Immutable.IImmutableSet`1": return true; default: return false; } } [DynamicDependency("CreateRange`1", "System.Collections.Immutable.ImmutableArray", "System.Collections.Immutable")] [DynamicDependency("CreateRange`1", "System.Collections.Immutable.ImmutableList", "System.Collections.Immutable")] [DynamicDependency("CreateRange`1", "System.Collections.Immutable.ImmutableStack", "System.Collections.Immutable")] [DynamicDependency("CreateRange`1", "System.Collections.Immutable.ImmutableQueue", "System.Collections.Immutable")] [DynamicDependency("CreateRange`1", "System.Collections.Immutable.ImmutableSortedSet", "System.Collections.Immutable")] [DynamicDependency("CreateRange`1", "System.Collections.Immutable.ImmutableHashSet", "System.Collections.Immutable")] public static MethodInfo GetImmutableEnumerableCreateRangeMethod(this Type type, Type elementType) { Type immutableEnumerableConstructingType = GetImmutableEnumerableConstructingType(type); if (immutableEnumerableConstructingType != null) { MethodInfo[] methods = immutableEnumerableConstructingType.GetMethods(); MethodInfo[] array = methods; foreach (MethodInfo methodInfo in array) { if (methodInfo.Name == "CreateRange" && methodInfo.GetParameters().Length == 1 && methodInfo.IsGenericMethod && methodInfo.GetGenericArguments().Length == 1) { return methodInfo.MakeGenericMethod(elementType); } } } ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(type); return null; } [DynamicDependency("CreateRange`2", "System.Collections.Immutable.ImmutableDictionary", "System.Collections.Immutable")] [DynamicDependency("CreateRange`2", "System.Collections.Immutable.ImmutableSortedDictionary", "System.Collections.Immutable")] public static MethodInfo GetImmutableDictionaryCreateRangeMethod(this Type type, Type keyType, Type valueType) { Type immutableDictionaryConstructingType = GetImmutableDictionaryConstructingType(type); if (immutableDictionaryConstructingType != null) { MethodInfo[] methods = immutableDictionaryConstructingType.GetMethods(); MethodInfo[] array = methods; foreach (MethodInfo methodInfo in array) { if (methodInfo.Name == "CreateRange" && methodInfo.GetParameters().Length == 1 && methodInfo.IsGenericMethod && methodInfo.GetGenericArguments().Length == 2) { return methodInfo.MakeGenericMethod(keyType, valueType); } } } ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(type); return null; } private static Type GetImmutableEnumerableConstructingType(Type type) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); string name; switch (genericTypeDefinition.FullName) { case "System.Collections.Immutable.ImmutableArray`1": name = "System.Collections.Immutable.ImmutableArray"; break; case "System.Collections.Immutable.ImmutableList`1": case "System.Collections.Immutable.IImmutableList`1": name = "System.Collections.Immutable.ImmutableList"; break; case "System.Collections.Immutable.ImmutableStack`1": case "System.Collections.Immutable.IImmutableStack`1": name = "System.Collections.Immutable.ImmutableStack"; break; case "System.Collections.Immutable.ImmutableQueue`1": case "System.Collections.Immutable.IImmutableQueue`1": name = "System.Collections.Immutable.ImmutableQueue"; break; case "System.Collections.Immutable.ImmutableSortedSet`1": name = "System.Collections.Immutable.ImmutableSortedSet"; break; case "System.Collections.Immutable.ImmutableHashSet`1": case "System.Collections.Immutable.IImmutableSet`1": name = "System.Collections.Immutable.ImmutableHashSet"; break; default: return null; } return genericTypeDefinition.Assembly.GetType(name); } private static Type GetImmutableDictionaryConstructingType(Type type) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); string name; switch (genericTypeDefinition.FullName) { case "System.Collections.Immutable.ImmutableDictionary`2": case "System.Collections.Immutable.IImmutableDictionary`2": name = "System.Collections.Immutable.ImmutableDictionary"; break; case "System.Collections.Immutable.ImmutableSortedDictionary`2": name = "System.Collections.Immutable.ImmutableSortedDictionary"; break; default: return null; } return genericTypeDefinition.Assembly.GetType(name); } public static bool IsNonGenericStackOrQueue(this Type type) { Type typeIfExists = GetTypeIfExists("System.Collections.Stack, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); if ((object)typeIfExists != null && typeIfExists.IsAssignableFrom(type)) { return true; } Type typeIfExists2 = GetTypeIfExists("System.Collections.Queue, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); if ((object)typeIfExists2 != null && typeIfExists2.IsAssignableFrom(type)) { return true; } return false; } private static Type GetTypeIfExists(string name) { return Type.GetType(name, throwOnError: false); } } internal abstract class JsonCollectionConverter : JsonResumableConverter { internal sealed override ClassType ClassType => ClassType.Enumerable; internal override Type ElementType => typeof(TElement); } internal abstract class JsonDictionaryConverter : JsonResumableConverter { internal sealed override ClassType ClassType => ClassType.Dictionary; protected internal abstract bool OnWriteResume(Utf8JsonWriter writer, T dictionary, JsonSerializerOptions options, ref WriteStack state); } internal abstract class JsonObjectConverter : JsonResumableConverter { internal sealed override ClassType ClassType => ClassType.Object; internal sealed override Type ElementType => null; } internal abstract class JsonConverter { internal bool IsInternalConverterForNumberType; internal abstract ClassType ClassType { get; } internal bool CanUseDirectReadOrWrite { get; set; } internal virtual bool CanHaveIdMetadata => true; internal bool CanBePolymorphic { get; set; } internal abstract Type? ElementType { get; } internal bool IsValueType { get; set; } internal bool IsInternalConverter { get; set; } internal virtual Type RuntimeType => TypeToConvert; internal abstract Type TypeToConvert { get; } internal virtual bool ConstructorIsParameterized { get; } internal ConstructorInfo? ConstructorInfo { get; set; } internal JsonConverter() { } public abstract bool CanConvert(Type typeToConvert); internal abstract JsonPropertyInfo CreateJsonPropertyInfo(); internal abstract JsonParameterInfo CreateJsonParameterInfo(); internal abstract object ReadCoreAsObject(ref Utf8JsonReader reader, JsonSerializerOptions options, ref ReadStack state); internal bool ShouldFlush(Utf8JsonWriter writer, ref WriteStack state) { if (state.FlushThreshold > 0) { return writer.BytesPending > state.FlushThreshold; } return false; } internal abstract bool TryReadAsObject(ref Utf8JsonReader reader, JsonSerializerOptions options, ref ReadStack state, out object value); internal abstract bool TryWriteAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state); internal abstract bool WriteCoreAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state); internal abstract void WriteWithQuotesAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state); internal virtual void Initialize(JsonSerializerOptions options) { } internal virtual void CreateInstanceForReferenceResolver(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool SingleValueReadWithReadAhead(ClassType classType, ref Utf8JsonReader reader, ref ReadStack state) { if (!state.ReadAhead || (classType & (ClassType)6) == 0) { return reader.Read(); } return DoSingleValueReadWithReadAhead(ref reader, ref state); } internal static bool DoSingleValueReadWithReadAhead(ref Utf8JsonReader reader, ref ReadStack state) { JsonReaderState currentState = reader.CurrentState; long bytesConsumed = reader.BytesConsumed; if (!reader.Read()) { return false; } JsonTokenType tokenType = reader.TokenType; if (tokenType == JsonTokenType.StartObject || tokenType == JsonTokenType.StartArray) { bool flag = reader.TrySkip(); reader = new Utf8JsonReader(reader.OriginalSpan.Slice(checked((int)bytesConsumed)), reader.IsFinalBlock, currentState); state.BytesConsumed += bytesConsumed; if (!flag) { return false; } reader.ReadWithVerify(); } return true; } } internal abstract class JsonConverterFactory : JsonConverter { internal sealed override ClassType ClassType => ClassType.None; internal sealed override Type? ElementType => null; internal sealed override Type TypeToConvert => null; public abstract JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options); internal override JsonPropertyInfo CreateJsonPropertyInfo() { throw new InvalidOperationException(); } internal override JsonParameterInfo CreateJsonParameterInfo() { throw new InvalidOperationException(); } internal JsonConverter GetConverterInternal(Type typeToConvert, JsonSerializerOptions options) { JsonConverter jsonConverter = CreateConverter(typeToConvert, options); if (jsonConverter == null) { ThrowHelper.ThrowInvalidOperationException_SerializerConverterFactoryReturnsNull(GetType()); } return jsonConverter; } internal sealed override object ReadCoreAsObject(ref Utf8JsonReader reader, JsonSerializerOptions options, ref ReadStack state) { throw new InvalidOperationException(); } internal sealed override bool TryReadAsObject(ref Utf8JsonReader reader, JsonSerializerOptions options, ref ReadStack state, out object value) { throw new InvalidOperationException(); } internal sealed override bool TryWriteAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state) { throw new InvalidOperationException(); } internal sealed override bool WriteCoreAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state) { throw new InvalidOperationException(); } internal sealed override void WriteWithQuotesAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state) { throw new InvalidOperationException(); } } internal abstract class JsonConverter : JsonConverter { internal override ClassType ClassType => ClassType.Value; internal override Type? ElementType => null; public virtual bool HandleNull { get { HandleNullOnRead = !CanBeNull; HandleNullOnWrite = false; return false; } } internal bool HandleNullOnRead { get; private set; } internal bool HandleNullOnWrite { get; private set; } internal bool CanBeNull { get; } internal sealed override Type TypeToConvert => typeof(T); internal sealed override object ReadCoreAsObject(ref Utf8JsonReader reader, JsonSerializerOptions options, ref ReadStack state) { return ReadCore(ref reader, options, ref state); } internal T ReadCore(ref Utf8JsonReader reader, JsonSerializerOptions options, ref ReadStack state) { try { if (!state.IsContinuation) { if (!JsonConverter.SingleValueReadWithReadAhead(ClassType, ref reader, ref state)) { if (state.SupportContinuation) { state.BytesConsumed += reader.BytesConsumed; if (state.Current.ReturnValue == null) { return default(T); } return (T)state.Current.ReturnValue; } state.BytesConsumed += reader.BytesConsumed; return default(T); } } else if (!JsonConverter.SingleValueReadWithReadAhead(ClassType.Value, ref reader, ref state)) { state.BytesConsumed += reader.BytesConsumed; return default(T); } JsonPropertyInfo propertyInfoForClassInfo = state.Current.JsonClassInfo.PropertyInfoForClassInfo; if (TryRead(ref reader, propertyInfoForClassInfo.RuntimePropertyType, options, ref state, out var value) && !reader.Read() && !reader.IsFinalBlock) { state.Current.ReturnValue = value; } state.BytesConsumed += reader.BytesConsumed; return value; } catch (JsonReaderException ex) { ThrowHelper.ReThrowWithPath(in state, ex); return default(T); } catch (FormatException ex2) when (ex2.Source == "System.Text.Json.Rethrowable") { ThrowHelper.ReThrowWithPath(in state, in reader, ex2); return default(T); } catch (InvalidOperationException ex3) when (ex3.Source == "System.Text.Json.Rethrowable") { ThrowHelper.ReThrowWithPath(in state, in reader, ex3); return default(T); } catch (JsonException ex4) { ThrowHelper.AddJsonExceptionInformation(in state, in reader, ex4); throw; } catch (NotSupportedException ex5) { if (ex5.Message.Contains(" Path: ")) { throw; } ThrowHelper.ThrowNotSupportedException(in state, in reader, ex5); return default(T); } } internal sealed override bool WriteCoreAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state) { if (value == null && base.IsValueType && Nullable.GetUnderlyingType(TypeToConvert) == null) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } T value2 = (T)value; return WriteCore(writer, in value2, options, ref state); } internal bool WriteCore(Utf8JsonWriter writer, in T value, JsonSerializerOptions options, ref WriteStack state) { try { return TryWrite(writer, in value, options, ref state); } catch (InvalidOperationException ex) when (ex.Source == "System.Text.Json.Rethrowable") { ThrowHelper.ReThrowWithPath(in state, ex); throw; } catch (JsonException ex2) { ThrowHelper.AddJsonExceptionInformation(in state, ex2); throw; } catch (NotSupportedException ex3) { if (ex3.Message.Contains(" Path: ")) { throw; } ThrowHelper.ThrowNotSupportedException(in state, ex3); return false; } } protected internal JsonConverter() { base.CanBePolymorphic = TypeToConvert == JsonClassInfo.ObjectType; base.IsValueType = TypeToConvert.IsValueType; CanBeNull = !base.IsValueType || Nullable.GetUnderlyingType(TypeToConvert) != null; base.IsInternalConverter = GetType().Assembly == typeof(JsonConverter).Assembly; if (HandleNull) { HandleNullOnRead = true; HandleNullOnWrite = true; } base.CanUseDirectReadOrWrite = !base.CanBePolymorphic && base.IsInternalConverter && ClassType == ClassType.Value; } public override bool CanConvert(Type typeToConvert) { return typeToConvert == typeof(T); } internal sealed override JsonPropertyInfo CreateJsonPropertyInfo() { return new JsonPropertyInfo(); } internal sealed override JsonParameterInfo CreateJsonParameterInfo() { return new JsonParameterInfo(); } internal sealed override bool TryWriteAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state) { T value2 = (T)value; return TryWrite(writer, in value2, options, ref state); } internal virtual bool OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state) { Write(writer, value, options); return true; } internal virtual bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, out T value) { value = Read(ref reader, typeToConvert, options); return true; } public abstract T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options); internal bool TryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, out T value) { if (ClassType == ClassType.Value) { if (reader.TokenType == JsonTokenType.Null && !HandleNullOnRead) { if (!CanBeNull) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } value = default(T); return true; } if (base.IsInternalConverter) { if (IsInternalConverterForNumberType && state.Current.NumberHandling.HasValue) { value = ReadNumberWithCustomHandling(ref reader, state.Current.NumberHandling.Value); } else { value = Read(ref reader, typeToConvert, options); } } else { JsonTokenType tokenType = reader.TokenType; int currentDepth = reader.CurrentDepth; long bytesConsumed = reader.BytesConsumed; if (IsInternalConverterForNumberType && state.Current.NumberHandling.HasValue) { value = ReadNumberWithCustomHandling(ref reader, state.Current.NumberHandling.Value); } else { value = Read(ref reader, typeToConvert, options); } VerifyRead(tokenType, currentDepth, bytesConsumed, isValueConverter: true, ref reader); } if (base.CanBePolymorphic && options.ReferenceHandler != null) { T val = value; if (val is JsonElement) { object obj = val; JsonElement element = (JsonElement)((obj is JsonElement) ? obj : null); if (JsonSerializer.TryGetReferenceFromJsonElement(ref state, element, out object referenceValue)) { value = (T)referenceValue; } } } return true; } bool isContinuation = state.IsContinuation; state.Push(); bool flag; if (base.IsInternalConverter) { if (reader.TokenType == JsonTokenType.Null && !HandleNullOnRead && !isContinuation) { if (!CanBeNull) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } value = default(T); flag = true; } else { flag = OnTryRead(ref reader, typeToConvert, options, ref state, out value); } } else { if (!isContinuation) { if (reader.TokenType == JsonTokenType.Null && !HandleNullOnRead) { if (!CanBeNull) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } value = default(T); state.Pop(success: true); return true; } state.Current.OriginalTokenType = reader.TokenType; state.Current.OriginalDepth = reader.CurrentDepth; } flag = OnTryRead(ref reader, typeToConvert, options, ref state, out value); if (flag) { if (state.IsContinuation) { ThrowHelper.ThrowJsonException_SerializationConverterRead(this); } VerifyRead(state.Current.OriginalTokenType, state.Current.OriginalDepth, 0L, isValueConverter: false, ref reader); } } state.Pop(flag); return flag; } internal sealed override bool TryReadAsObject(ref Utf8JsonReader reader, JsonSerializerOptions options, ref ReadStack state, out object value) { T value2; bool result = TryRead(ref reader, TypeToConvert, options, ref state, out value2); value = value2; return result; } internal bool TryWrite(Utf8JsonWriter writer, in T value, JsonSerializerOptions options, ref WriteStack state) { if (writer.CurrentDepth >= options.EffectiveMaxDepth) { ThrowHelper.ThrowJsonException_SerializerCycleDetected(options.EffectiveMaxDepth); } if (base.CanBePolymorphic) { if (value == null) { if (!HandleNullOnWrite) { writer.WriteNullValue(); } else { int currentDepth = writer.CurrentDepth; Write(writer, value, options); VerifyWrite(currentDepth, writer); } return true; } Type type = value.GetType(); if (type == JsonClassInfo.ObjectType) { writer.WriteStartObject(); writer.WriteEndObject(); return true; } if (type != TypeToConvert && base.IsInternalConverter) { JsonConverter jsonConverter = state.Current.InitializeReEntry(type, options); if (jsonConverter != this) { return jsonConverter.TryWriteAsObject(writer, value, options, ref state); } } } else if (value == null && !HandleNullOnWrite) { writer.WriteNullValue(); return true; } if (ClassType == ClassType.Value) { int currentDepth2 = writer.CurrentDepth; if (IsInternalConverterForNumberType && state.Current.NumberHandling.HasValue) { WriteNumberWithCustomHandling(writer, value, state.Current.NumberHandling.Value); } else { Write(writer, value, options); } VerifyWrite(currentDepth2, writer); return true; } bool isContinuation = state.IsContinuation; state.Push(); if (!isContinuation) { state.Current.OriginalDepth = writer.CurrentDepth; } bool flag = OnTryWrite(writer, value, options, ref state); if (flag) { VerifyWrite(state.Current.OriginalDepth, writer); } state.Pop(flag); return flag; } internal bool TryWriteDataExtensionProperty(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state) { if (!base.IsInternalConverter) { return TryWrite(writer, in value, options, ref state); } if (writer.CurrentDepth >= options.EffectiveMaxDepth) { ThrowHelper.ThrowJsonException_SerializerCycleDetected(options.EffectiveMaxDepth); } JsonDictionaryConverter jsonDictionaryConverter = (JsonDictionaryConverter)this; bool isContinuation = state.IsContinuation; state.Push(); if (!isContinuation) { state.Current.OriginalDepth = writer.CurrentDepth; } state.Current.IgnoreDictionaryKeyPolicy = true; bool flag = jsonDictionaryConverter.OnWriteResume(writer, value, options, ref state); if (flag) { VerifyWrite(state.Current.OriginalDepth, writer); } state.Pop(flag); return flag; } internal void VerifyRead(JsonTokenType tokenType, int depth, long bytesConsumed, bool isValueConverter, ref Utf8JsonReader reader) { switch (tokenType) { case JsonTokenType.StartArray: if (reader.TokenType != JsonTokenType.EndArray) { ThrowHelper.ThrowJsonException_SerializationConverterRead(this); } else if (depth != reader.CurrentDepth) { ThrowHelper.ThrowJsonException_SerializationConverterRead(this); } break; case JsonTokenType.StartObject: if (reader.TokenType != JsonTokenType.EndObject) { ThrowHelper.ThrowJsonException_SerializationConverterRead(this); } else if (depth != reader.CurrentDepth) { ThrowHelper.ThrowJsonException_SerializationConverterRead(this); } break; default: if (!isValueConverter || reader.BytesConsumed != bytesConsumed) { ThrowHelper.ThrowJsonException_SerializationConverterRead(this); } break; } } internal void VerifyWrite(int originalDepth, Utf8JsonWriter writer) { if (originalDepth != writer.CurrentDepth) { ThrowHelper.ThrowJsonException_SerializationConverterWrite(this); } } public abstract void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options); internal virtual T ReadWithQuotes(ref Utf8JsonReader reader) { throw new InvalidOperationException(); } internal virtual void WriteWithQuotes(Utf8JsonWriter writer, [DisallowNull] T value, JsonSerializerOptions options, ref WriteStack state) { throw new InvalidOperationException(); } internal sealed override void WriteWithQuotesAsObject(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state) { WriteWithQuotes(writer, (T)value, options, ref state); } internal virtual T ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling) { throw new InvalidOperationException(); } internal virtual void WriteNumberWithCustomHandling(Utf8JsonWriter writer, T value, JsonNumberHandling handling) { throw new InvalidOperationException(); } } internal enum JsonIgnoreCondition { Never, Always, WhenWritingDefault, WhenWritingNull } [Flags] internal enum JsonNumberHandling { Strict = 0, AllowReadingFromString = 1, WriteAsString = 2, AllowNamedFloatingPointLiterals = 4 } internal abstract class JsonResumableConverter : JsonConverter { public sealed override bool HandleNull => false; public sealed override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (options == null) { throw new ArgumentNullException("options"); } ReadStack state = default(ReadStack); state.Initialize(typeToConvert, options, supportContinuation: false); TryRead(ref reader, typeToConvert, options, ref state, out var value); return value; } public sealed override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { if (options == null) { throw new ArgumentNullException("options"); } WriteStack state = default(WriteStack); state.Initialize(typeof(T), options, supportContinuation: false); TryWrite(writer, in value, options, ref state); } } internal sealed class JsonStringEnumConverter : JsonConverterFactory { private readonly JsonNamingPolicy _namingPolicy; private readonly EnumConverterOptions _converterOptions; public JsonStringEnumConverter() : this(null, allowIntegerValues: true) { } public JsonStringEnumConverter(JsonNamingPolicy? namingPolicy = null, bool allowIntegerValues = true) { _namingPolicy = namingPolicy; _converterOptions = ((!allowIntegerValues) ? EnumConverterOptions.AllowStrings : (EnumConverterOptions.AllowStrings | EnumConverterOptions.AllowNumbers)); } public override bool CanConvert(Type typeToConvert) { return typeToConvert.IsEnum; } public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { return (JsonConverter)Activator.CreateInstance(typeof(EnumConverter<>).MakeGenericType(typeToConvert), BindingFlags.Instance | BindingFlags.Public, null, new object[3] { _converterOptions, _namingPolicy, options }, null); } } internal sealed class PreserveReferenceHandler : ReferenceHandler { public override ReferenceResolver CreateResolver() { throw new InvalidOperationException(); } internal override ReferenceResolver CreateResolver(bool writing) { return new PreserveReferenceResolver(writing); } } internal sealed class PreserveReferenceResolver : ReferenceResolver { private uint _referenceCount; private readonly Dictionary _referenceIdToObjectMap; private readonly Dictionary _objectToReferenceIdMap; public PreserveReferenceResolver(bool writing) { if (writing) { _objectToReferenceIdMap = new Dictionary(ReferenceEqualityComparer.Instance); } else { _referenceIdToObjectMap = new Dictionary(); } } public override void AddReference(string referenceId, object value) { if (!JsonHelpers.TryAdd(_referenceIdToObjectMap, in referenceId, in value)) { ThrowHelper.ThrowJsonException_MetadataDuplicateIdFound(referenceId); } } public override string GetReference(object value, out bool alreadyExists) { if (_objectToReferenceIdMap.TryGetValue(value, out var value2)) { alreadyExists = true; } else { _referenceCount++; value2 = _referenceCount.ToString(); _objectToReferenceIdMap.Add(value, value2); alreadyExists = false; } return value2; } public override object ResolveReference(string referenceId) { if (!_referenceIdToObjectMap.TryGetValue(referenceId, out var value)) { ThrowHelper.ThrowJsonException_MetadataReferenceNotFound(referenceId); } return value; } } internal abstract class ReferenceHandler { public static ReferenceHandler Preserve { get; } = new PreserveReferenceHandler(); public abstract ReferenceResolver CreateResolver(); internal virtual ReferenceResolver CreateResolver(bool writing) { return CreateResolver(); } } internal sealed class ReferenceHandler : ReferenceHandler where T : ReferenceResolver, new() { public override ReferenceResolver CreateResolver() { return new T(); } } internal abstract class ReferenceResolver { public abstract void AddReference(string referenceId, object value); public abstract string GetReference(object value, out bool alreadyExists); public abstract object ResolveReference(string referenceId); } internal sealed class ReflectionMemberAccessor : MemberAccessor { public override JsonClassInfo.ConstructorDelegate CreateConstructor(Type type) { ConstructorInfo constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null); if (type.IsAbstract) { return null; } if (constructor == null && !type.IsValueType) { return null; } return () => Activator.CreateInstance(type, nonPublic: false); } public override JsonClassInfo.ParameterizedConstructorDelegate CreateParameterizedConstructor(ConstructorInfo constructor) { Type typeFromHandle = typeof(T); int parameterCount = constructor.GetParameters().Length; if (parameterCount > 64) { return null; } return delegate(object[] arguments) { object[] array = new object[parameterCount]; for (int i = 0; i < parameterCount; i++) { array[i] = arguments[i]; } try { return (T)constructor.Invoke(array); } catch (TargetInvocationException ex) { throw ex.InnerException ?? ex; } }; } public override JsonClassInfo.ParameterizedConstructorDelegate CreateParameterizedConstructor(ConstructorInfo constructor) { Type typeFromHandle = typeof(T); int parameterCount = constructor.GetParameters().Length; return delegate(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3) { object[] array = new object[parameterCount]; for (int i = 0; i < parameterCount; i++) { switch (i) { case 0: array[0] = arg0; break; case 1: array[1] = arg1; break; case 2: array[2] = arg2; break; case 3: array[3] = arg3; break; default: throw new InvalidOperationException(); } } return (T)constructor.Invoke(array); }; } public override Action CreateAddMethodDelegate() { Type typeFromHandle = typeof(TCollection); Type objectType = JsonClassInfo.ObjectType; MethodInfo addMethod = typeFromHandle.GetMethod("Push") ?? typeFromHandle.GetMethod("Enqueue"); return delegate(TCollection collection, object element) { addMethod.Invoke(collection, new object[1] { element }); }; } public override Func, TCollection> CreateImmutableEnumerableCreateRangeDelegate() { MethodInfo immutableEnumerableCreateRangeMethod = typeof(TCollection).GetImmutableEnumerableCreateRangeMethod(typeof(TElement)); return (Func, TCollection>)immutableEnumerableCreateRangeMethod.CreateDelegate(typeof(Func, TCollection>)); } public override Func>, TCollection> CreateImmutableDictionaryCreateRangeDelegate() { MethodInfo immutableDictionaryCreateRangeMethod = typeof(TCollection).GetImmutableDictionaryCreateRangeMethod(typeof(TKey), typeof(TValue)); return (Func>, TCollection>)immutableDictionaryCreateRangeMethod.CreateDelegate(typeof(Func>, TCollection>)); } public override Func CreatePropertyGetter(PropertyInfo propertyInfo) { MethodInfo getMethodInfo = propertyInfo.GetMethod; return (object obj) => (TProperty)getMethodInfo.Invoke(obj, null); } public override Action CreatePropertySetter(PropertyInfo propertyInfo) { MethodInfo setMethodInfo = propertyInfo.SetMethod; return delegate(object obj, TProperty value) { setMethodInfo.Invoke(obj, new object[1] { value }); }; } public override Func CreateFieldGetter(FieldInfo fieldInfo) { return (object obj) => (TProperty)fieldInfo.GetValue(obj); } public override Action CreateFieldSetter(FieldInfo fieldInfo) { return delegate(object obj, TProperty value) { fieldInfo.SetValue(obj, value); }; } } } namespace System.Text.Json.Serialization.Converters { internal sealed class ArrayConverter : IEnumerableDefaultConverter where TCollection : IEnumerable { internal override bool CanHaveIdMetadata => false; protected override void Add(in TElement value, ref ReadStack state) { ((List)state.Current.ReturnValue).Add(value); } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { state.Current.ReturnValue = new List(); } protected override void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) { List list = (List)state.Current.ReturnValue; state.Current.ReturnValue = list.ToArray(); } protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { TElement[] array = (TElement[])(object)value; int i = state.Current.EnumeratorIndex; JsonConverter elementConverter = IEnumerableDefaultConverter.GetElementConverter(ref state); if (elementConverter.CanUseDirectReadOrWrite && !state.Current.NumberHandling.HasValue) { for (; i < array.Length; i++) { elementConverter.Write(writer, array[i], options); } } else { for (; i < array.Length; i++) { TElement value2 = array[i]; if (!elementConverter.TryWrite(writer, in value2, options, ref state)) { state.Current.EnumeratorIndex = i; return false; } if (ShouldFlush(writer, ref state)) { i = (state.Current.EnumeratorIndex = i + 1); return false; } } } return true; } } internal sealed class ConcurrentQueueOfTConverter : IEnumerableDefaultConverter where TCollection : ConcurrentQueue { protected override void Add(in TElement value, ref ReadStack state) { ((TCollection)state.Current.ReturnValue).Enqueue(value); } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { if (state.Current.JsonClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(state.Current.JsonClassInfo.Type); } state.Current.ReturnValue = state.Current.JsonClassInfo.CreateObject(); } protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IEnumerator enumerator; if (state.Current.CollectionEnumerator == null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) { return true; } } else { enumerator = (IEnumerator)state.Current.CollectionEnumerator; } JsonConverter elementConverter = IEnumerableDefaultConverter.GetElementConverter(ref state); do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } TElement value2 = enumerator.Current; if (!elementConverter.TryWrite(writer, in value2, options, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } } while (enumerator.MoveNext()); return true; } } internal sealed class ConcurrentStackOfTConverter : IEnumerableDefaultConverter where TCollection : ConcurrentStack { protected override void Add(in TElement value, ref ReadStack state) { ((TCollection)state.Current.ReturnValue).Push(value); } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { if (state.Current.JsonClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(state.Current.JsonClassInfo.Type); } state.Current.ReturnValue = state.Current.JsonClassInfo.CreateObject(); } protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IEnumerator enumerator; if (state.Current.CollectionEnumerator == null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) { return true; } } else { enumerator = (IEnumerator)state.Current.CollectionEnumerator; } JsonConverter elementConverter = IEnumerableDefaultConverter.GetElementConverter(ref state); do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } TElement value2 = enumerator.Current; if (!elementConverter.TryWrite(writer, in value2, options, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } } while (enumerator.MoveNext()); return true; } } internal abstract class DictionaryDefaultConverter : JsonDictionaryConverter { private static Type s_valueType = typeof(TValue); protected Type KeyType = typeof(TKey); protected bool IsStringKey = typeof(TKey) == typeof(string); protected JsonConverter _keyConverter; protected JsonConverter _valueConverter; internal override Type ElementType => s_valueType; protected abstract void Add(TKey key, in TValue value, JsonSerializerOptions options, ref ReadStack state); protected virtual void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) { } protected virtual void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state) { } protected static JsonConverter GetValueConverter(JsonClassInfo elementClassInfo) { return (JsonConverter)elementClassInfo.PropertyInfoForClassInfo.ConverterBase; } protected static JsonConverter GetKeyConverter(Type keyType, JsonSerializerOptions options) { return (JsonConverter)options.GetDictionaryKeyConverter(keyType); } internal sealed override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, [MaybeNullWhen(false)] out TCollection value) { JsonClassInfo elementClassInfo = state.Current.JsonClassInfo.ElementClassInfo; if (state.UseFastPath) { if (reader.TokenType != JsonTokenType.StartObject) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } CreateCollection(ref reader, ref state); JsonConverter jsonConverter = _valueConverter ?? (_valueConverter = GetValueConverter(elementClassInfo)); if (jsonConverter.CanUseDirectReadOrWrite && !state.Current.NumberHandling.HasValue) { while (true) { reader.ReadWithVerify(); if (reader.TokenType == JsonTokenType.EndObject) { break; } TKey key = ReadDictionaryKey(ref reader, ref state); reader.ReadWithVerify(); TValue value2 = jsonConverter.Read(ref reader, s_valueType, options); Add(key, in value2, options, ref state); } } else { while (true) { reader.ReadWithVerify(); if (reader.TokenType == JsonTokenType.EndObject) { break; } TKey key2 = ReadDictionaryKey(ref reader, ref state); reader.ReadWithVerify(); jsonConverter.TryRead(ref reader, s_valueType, options, ref state, out var value3); Add(key2, in value3, options, ref state); } } } else { if (state.Current.ObjectState == StackFrameObjectState.None) { if (reader.TokenType != JsonTokenType.StartObject) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } state.Current.ObjectState = StackFrameObjectState.StartToken; } bool flag = options.ReferenceHandler != null; if (flag && (int)state.Current.ObjectState < 14) { if (!JsonSerializer.ResolveMetadataForJsonObject(ref reader, ref state, options)) { value = default(TCollection); return false; } if (state.Current.ObjectState == StackFrameObjectState.ReadRefEndObject) { value = (TCollection)state.Current.ReturnValue; return true; } } if ((int)state.Current.ObjectState < 15) { CreateCollection(ref reader, ref state); state.Current.ObjectState = StackFrameObjectState.CreatedObject; } JsonConverter jsonConverter2 = _valueConverter ?? (_valueConverter = GetValueConverter(elementClassInfo)); while (true) { if (state.Current.PropertyState == StackFramePropertyState.None) { state.Current.PropertyState = StackFramePropertyState.ReadName; if (!reader.Read()) { value = default(TCollection); return false; } } if ((int)state.Current.PropertyState < 2) { if (reader.TokenType == JsonTokenType.EndObject) { break; } state.Current.PropertyState = StackFramePropertyState.Name; if (flag) { ReadOnlySpan span = reader.GetSpan(); if (span.Length > 0 && span[0] == 36) { ThrowHelper.ThrowUnexpectedMetadataException(span, ref reader, ref state); } } state.Current.DictionaryKey = ReadDictionaryKey(ref reader, ref state); } if ((int)state.Current.PropertyState < 3) { state.Current.PropertyState = StackFramePropertyState.ReadValue; if (!JsonConverter.SingleValueReadWithReadAhead(jsonConverter2.ClassType, ref reader, ref state)) { value = default(TCollection); return false; } } if ((int)state.Current.PropertyState < 5) { if (!jsonConverter2.TryRead(ref reader, typeof(TValue), options, ref state, out var value4)) { value = default(TCollection); return false; } TKey key3 = (TKey)state.Current.DictionaryKey; Add(key3, in value4, options, ref state); state.Current.EndElement(); } } } ConvertCollection(ref state, options); value = (TCollection)state.Current.ReturnValue; return true; TKey ReadDictionaryKey(ref Utf8JsonReader reader, ref ReadStack state) { string @string; TKey result; if (IsStringKey) { @string = reader.GetString(); result = (TKey)(object)@string; } else { JsonConverter jsonConverter3 = _keyConverter ?? (_keyConverter = GetKeyConverter(KeyType, options)); result = jsonConverter3.ReadWithQuotes(ref reader); @string = reader.GetString(); } state.Current.JsonPropertyNameAsString = @string; return result; } } internal sealed override bool OnTryWrite(Utf8JsonWriter writer, TCollection dictionary, JsonSerializerOptions options, ref WriteStack state) { if (dictionary == null) { writer.WriteNullValue(); return true; } if (!state.Current.ProcessedStartToken) { state.Current.ProcessedStartToken = true; writer.WriteStartObject(); if (options.ReferenceHandler != null && JsonSerializer.WriteReferenceForObject(this, dictionary, ref state, writer) == MetadataPropertyName.Ref) { return true; } state.Current.DeclaredJsonPropertyInfo = state.Current.JsonClassInfo.ElementClassInfo.PropertyInfoForClassInfo; } bool flag = OnWriteResume(writer, dictionary, options, ref state); if (flag && !state.Current.ProcessedEndToken) { state.Current.ProcessedEndToken = true; writer.WriteEndObject(); } return flag; } internal sealed override void CreateInstanceForReferenceResolver(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { CreateCollection(ref reader, ref state); } } internal sealed class DictionaryOfTKeyTValueConverter : DictionaryDefaultConverter where TCollection : Dictionary { protected override void Add(TKey key, in TValue value, JsonSerializerOptions options, ref ReadStack state) { ((TCollection)state.Current.ReturnValue)[key] = value; } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state) { if (state.Current.JsonClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(state.Current.JsonClassInfo.Type); } state.Current.ReturnValue = state.Current.JsonClassInfo.CreateObject(); } protected internal override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { Dictionary.Enumerator enumerator; if (state.Current.CollectionEnumerator == null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) { return true; } } else { enumerator = (Dictionary.Enumerator)(object)state.Current.CollectionEnumerator; } JsonClassInfo elementClassInfo = state.Current.JsonClassInfo.ElementClassInfo; JsonConverter jsonConverter = _keyConverter ?? (_keyConverter = DictionaryDefaultConverter.GetKeyConverter(KeyType, options)); JsonConverter jsonConverter2 = _valueConverter ?? (_valueConverter = DictionaryDefaultConverter.GetValueConverter(elementClassInfo)); if (!state.SupportContinuation && jsonConverter2.CanUseDirectReadOrWrite && !state.Current.NumberHandling.HasValue) { do { TKey key = enumerator.Current.Key; jsonConverter.WriteWithQuotes(writer, key, options, ref state); jsonConverter2.Write(writer, enumerator.Current.Value, options); } while (enumerator.MoveNext()); } else { do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } if ((int)state.Current.PropertyState < 2) { state.Current.PropertyState = StackFramePropertyState.Name; TKey key2 = enumerator.Current.Key; jsonConverter.WriteWithQuotes(writer, key2, options, ref state); } TValue value2 = enumerator.Current.Value; if (!jsonConverter2.TryWrite(writer, in value2, options, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } state.Current.EndDictionaryElement(); } while (enumerator.MoveNext()); } return true; } } internal sealed class ICollectionOfTConverter : IEnumerableDefaultConverter where TCollection : ICollection { internal override Type RuntimeType { get { if (TypeToConvert.IsAbstract || TypeToConvert.IsInterface) { return typeof(List); } return TypeToConvert; } } protected override void Add(in TElement value, ref ReadStack state) { ((ICollection)state.Current.ReturnValue).Add(value); } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { JsonClassInfo jsonClassInfo = state.Current.JsonClassInfo; if (TypeToConvert.IsInterface || TypeToConvert.IsAbstract) { if (!TypeToConvert.IsAssignableFrom(RuntimeType)) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = new List(); return; } if (jsonClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(TypeToConvert, ref reader, ref state); } TCollection val = (TCollection)jsonClassInfo.CreateObject(); if (val.IsReadOnly) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = val; } protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IEnumerator enumerator; if (state.Current.CollectionEnumerator == null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) { return true; } } else { enumerator = (IEnumerator)state.Current.CollectionEnumerator; } JsonConverter elementConverter = IEnumerableDefaultConverter.GetElementConverter(ref state); do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } TElement value2 = enumerator.Current; if (!elementConverter.TryWrite(writer, in value2, options, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } } while (enumerator.MoveNext()); return true; } } internal sealed class IDictionaryConverter : DictionaryDefaultConverter where TCollection : IDictionary { private JsonConverter _objectConverter; internal override Type RuntimeType { get { if (TypeToConvert.IsAbstract || TypeToConvert.IsInterface) { return typeof(Dictionary); } return TypeToConvert; } } protected override void Add(string key, in object value, JsonSerializerOptions options, ref ReadStack state) { ((IDictionary)state.Current.ReturnValue)[key] = value; } private static JsonConverter GetObjectKeyConverter(JsonSerializerOptions options) { return (JsonConverter)options.GetDictionaryKeyConverter(typeof(object)); } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state) { JsonClassInfo jsonClassInfo = state.Current.JsonClassInfo; if (TypeToConvert.IsInterface || TypeToConvert.IsAbstract) { if (!TypeToConvert.IsAssignableFrom(RuntimeType)) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = new Dictionary(); return; } if (jsonClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(TypeToConvert, ref reader, ref state); } TCollection val = (TCollection)jsonClassInfo.CreateObject(); if (val.IsReadOnly) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = val; } protected internal override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IDictionaryEnumerator dictionaryEnumerator; if (state.Current.CollectionEnumerator == null) { dictionaryEnumerator = value.GetEnumerator(); if (!dictionaryEnumerator.MoveNext()) { return true; } } else { dictionaryEnumerator = (IDictionaryEnumerator)state.Current.CollectionEnumerator; } JsonConverter jsonConverter = _valueConverter ?? (_valueConverter = DictionaryDefaultConverter.GetValueConverter(state.Current.JsonClassInfo.ElementClassInfo)); do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = dictionaryEnumerator; return false; } if ((int)state.Current.PropertyState < 2) { state.Current.PropertyState = StackFramePropertyState.Name; object key = dictionaryEnumerator.Key; if (key is string value2) { JsonConverter jsonConverter2 = _keyConverter ?? (_keyConverter = DictionaryDefaultConverter.GetKeyConverter(KeyType, options)); jsonConverter2.WriteWithQuotes(writer, value2, options, ref state); } else { JsonConverter jsonConverter3 = _objectConverter ?? (_objectConverter = GetObjectKeyConverter(options)); jsonConverter3.WriteWithQuotes(writer, key, options, ref state); } } object value3 = dictionaryEnumerator.Value; if (!jsonConverter.TryWrite(writer, in value3, options, ref state)) { state.Current.CollectionEnumerator = dictionaryEnumerator; return false; } state.Current.EndDictionaryElement(); } while (dictionaryEnumerator.MoveNext()); return true; } } internal sealed class IDictionaryOfTKeyTValueConverter : DictionaryDefaultConverter where TCollection : IDictionary { internal override Type RuntimeType { get { if (TypeToConvert.IsAbstract || TypeToConvert.IsInterface) { return typeof(Dictionary); } return TypeToConvert; } } protected override void Add(TKey key, in TValue value, JsonSerializerOptions options, ref ReadStack state) { TCollection val = (TCollection)state.Current.ReturnValue; val[key] = value; } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state) { JsonClassInfo jsonClassInfo = state.Current.JsonClassInfo; if (TypeToConvert.IsInterface || TypeToConvert.IsAbstract) { if (!TypeToConvert.IsAssignableFrom(RuntimeType)) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = new Dictionary(); return; } if (jsonClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(TypeToConvert, ref reader, ref state); } TCollection val = (TCollection)jsonClassInfo.CreateObject(); if (val.IsReadOnly) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = val; } protected internal override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IEnumerator> enumerator; if (state.Current.CollectionEnumerator == null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) { return true; } } else { enumerator = (IEnumerator>)state.Current.CollectionEnumerator; } JsonConverter jsonConverter = _keyConverter ?? (_keyConverter = DictionaryDefaultConverter.GetKeyConverter(KeyType, options)); JsonConverter jsonConverter2 = _valueConverter ?? (_valueConverter = DictionaryDefaultConverter.GetValueConverter(state.Current.JsonClassInfo.ElementClassInfo)); do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } if ((int)state.Current.PropertyState < 2) { state.Current.PropertyState = StackFramePropertyState.Name; TKey key = enumerator.Current.Key; jsonConverter.WriteWithQuotes(writer, key, options, ref state); } TValue value2 = enumerator.Current.Value; if (!jsonConverter2.TryWrite(writer, in value2, options, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } state.Current.EndDictionaryElement(); } while (enumerator.MoveNext()); return true; } } internal sealed class IEnumerableConverter : IEnumerableDefaultConverter where TCollection : IEnumerable { internal override Type RuntimeType => typeof(List); protected override void Add(in object value, ref ReadStack state) { ((List)state.Current.ReturnValue).Add(value); } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { if (!TypeToConvert.IsAssignableFrom(RuntimeType)) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = new List(); } protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IEnumerator enumerator; if (state.Current.CollectionEnumerator == null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) { return true; } } else { enumerator = state.Current.CollectionEnumerator; } JsonConverter elementConverter = IEnumerableDefaultConverter.GetElementConverter(ref state); do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } object value2 = enumerator.Current; if (!elementConverter.TryWrite(writer, in value2, options, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } } while (enumerator.MoveNext()); return true; } } internal class IEnumerableConverterFactory : JsonConverterFactory { private static readonly IDictionaryConverter s_converterForIDictionary = new IDictionaryConverter(); private static readonly IEnumerableConverter s_converterForIEnumerable = new IEnumerableConverter(); private static readonly IListConverter s_converterForIList = new IListConverter(); public override bool CanConvert(Type typeToConvert) { return typeof(IEnumerable).IsAssignableFrom(typeToConvert); } public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { Type type = null; Type type2 = null; Type typeFromHandle; Type compatibleGenericBaseClass; if (typeToConvert.IsArray) { if (typeToConvert.GetArrayRank() > 1) { ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(typeToConvert); } typeFromHandle = typeof(ArrayConverter<, >); type = typeToConvert.GetElementType(); } else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericBaseClass(typeof(List<>))) != null) { typeFromHandle = typeof(ListOfTConverter<, >); type = compatibleGenericBaseClass.GetGenericArguments()[0]; } else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericBaseClass(typeof(Dictionary<, >))) != null) { Type[] genericArguments = compatibleGenericBaseClass.GetGenericArguments(); typeFromHandle = typeof(DictionaryOfTKeyTValueConverter<, , >); type2 = genericArguments[0]; type = genericArguments[1]; } else if (typeToConvert.IsImmutableDictionaryType()) { Type[] genericArguments = typeToConvert.GetGenericArguments(); typeFromHandle = typeof(ImmutableDictionaryOfTKeyTValueConverter<, , >); type2 = genericArguments[0]; type = genericArguments[1]; } else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericInterface(typeof(IDictionary<, >))) != null) { Type[] genericArguments = compatibleGenericBaseClass.GetGenericArguments(); typeFromHandle = typeof(IDictionaryOfTKeyTValueConverter<, , >); type2 = genericArguments[0]; type = genericArguments[1]; } else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericInterface(typeof(IReadOnlyDictionary<, >))) != null) { Type[] genericArguments = compatibleGenericBaseClass.GetGenericArguments(); typeFromHandle = typeof(IReadOnlyDictionaryOfTKeyTValueConverter<, , >); type2 = genericArguments[0]; type = genericArguments[1]; } else if (typeToConvert.IsImmutableEnumerableType()) { typeFromHandle = typeof(ImmutableEnumerableOfTConverter<, >); type = typeToConvert.GetGenericArguments()[0]; } else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericInterface(typeof(IList<>))) != null) { typeFromHandle = typeof(IListOfTConverter<, >); type = compatibleGenericBaseClass.GetGenericArguments()[0]; } else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericInterface(typeof(ISet<>))) != null) { typeFromHandle = typeof(ISetOfTConverter<, >); type = compatibleGenericBaseClass.GetGenericArguments()[0]; } else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericInterface(typeof(ICollection<>))) != null) { typeFromHandle = typeof(ICollectionOfTConverter<, >); type = compatibleGenericBaseClass.GetGenericArguments()[0]; } else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericBaseClass(typeof(Stack<>))) != null) { typeFromHandle = typeof(StackOfTConverter<, >); type = compatibleGenericBaseClass.GetGenericArguments()[0]; } else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericBaseClass(typeof(Queue<>))) != null) { typeFromHandle = typeof(QueueOfTConverter<, >); type = compatibleGenericBaseClass.GetGenericArguments()[0]; } else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericBaseClass(typeof(ConcurrentStack<>))) != null) { typeFromHandle = typeof(ConcurrentStackOfTConverter<, >); type = compatibleGenericBaseClass.GetGenericArguments()[0]; } else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericBaseClass(typeof(ConcurrentQueue<>))) != null) { typeFromHandle = typeof(ConcurrentQueueOfTConverter<, >); type = compatibleGenericBaseClass.GetGenericArguments()[0]; } else if ((compatibleGenericBaseClass = typeToConvert.GetCompatibleGenericInterface(typeof(IEnumerable<>))) != null) { typeFromHandle = typeof(IEnumerableOfTConverter<, >); type = compatibleGenericBaseClass.GetGenericArguments()[0]; } else if (typeof(IDictionary).IsAssignableFrom(typeToConvert)) { if (typeToConvert == typeof(IDictionary)) { return s_converterForIDictionary; } typeFromHandle = typeof(IDictionaryConverter<>); } else if (typeof(IList).IsAssignableFrom(typeToConvert)) { if (typeToConvert == typeof(IList)) { return s_converterForIList; } typeFromHandle = typeof(IListConverter<>); } else if (typeToConvert.IsNonGenericStackOrQueue()) { typeFromHandle = typeof(IEnumerableWithAddMethodConverter<>); } else { if (typeToConvert == typeof(IEnumerable)) { return s_converterForIEnumerable; } typeFromHandle = typeof(IEnumerableConverter<>); } return (JsonConverter)Activator.CreateInstance(typeFromHandle.GetGenericArguments().Length switch { 1 => typeFromHandle.MakeGenericType(typeToConvert), 2 => typeFromHandle.MakeGenericType(typeToConvert, type), _ => typeFromHandle.MakeGenericType(typeToConvert, type2, type), }, BindingFlags.Instance | BindingFlags.Public, null, null, null); } } internal abstract class IEnumerableDefaultConverter : JsonCollectionConverter { protected abstract void Add(in TElement value, ref ReadStack state); protected abstract void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options); protected virtual void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) { } protected static JsonConverter GetElementConverter(JsonClassInfo elementClassInfo) { return (JsonConverter)elementClassInfo.PropertyInfoForClassInfo.ConverterBase; } protected static JsonConverter GetElementConverter(ref WriteStack state) { return (JsonConverter)state.Current.DeclaredJsonPropertyInfo.ConverterBase; } internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, [MaybeNullWhen(false)] out TCollection value) { JsonClassInfo elementClassInfo = state.Current.JsonClassInfo.ElementClassInfo; if (state.UseFastPath) { if (reader.TokenType != JsonTokenType.StartArray) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } CreateCollection(ref reader, ref state, options); JsonConverter elementConverter = GetElementConverter(elementClassInfo); if (elementConverter.CanUseDirectReadOrWrite && !state.Current.NumberHandling.HasValue) { while (true) { reader.ReadWithVerify(); if (reader.TokenType == JsonTokenType.EndArray) { break; } TElement value2 = elementConverter.Read(ref reader, elementConverter.TypeToConvert, options); Add(in value2, ref state); } } else { while (true) { reader.ReadWithVerify(); if (reader.TokenType == JsonTokenType.EndArray) { break; } elementConverter.TryRead(ref reader, typeof(TElement), options, ref state, out var value3); Add(in value3, ref state); } } } else { bool flag = options.ReferenceHandler != null; if (state.Current.ObjectState == StackFrameObjectState.None) { if (reader.TokenType == JsonTokenType.StartArray) { state.Current.ObjectState = StackFrameObjectState.PropertyValue; } else if (flag) { if (reader.TokenType != JsonTokenType.StartObject) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } state.Current.ObjectState = StackFrameObjectState.StartToken; } else { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } } if (flag && (int)state.Current.ObjectState < 14) { if (!JsonSerializer.ResolveMetadataForJsonArray(ref reader, ref state, options)) { value = default(TCollection); return false; } if (state.Current.ObjectState == StackFrameObjectState.ReadRefEndObject) { value = (TCollection)state.Current.ReturnValue; return true; } } if ((int)state.Current.ObjectState < 15) { CreateCollection(ref reader, ref state, options); state.Current.JsonPropertyInfo = state.Current.JsonClassInfo.ElementClassInfo.PropertyInfoForClassInfo; state.Current.ObjectState = StackFrameObjectState.CreatedObject; } if ((int)state.Current.ObjectState < 16) { JsonConverter elementConverter2 = GetElementConverter(elementClassInfo); while (true) { if ((int)state.Current.PropertyState < 3) { state.Current.PropertyState = StackFramePropertyState.ReadValue; if (!JsonConverter.SingleValueReadWithReadAhead(elementConverter2.ClassType, ref reader, ref state)) { value = default(TCollection); return false; } } if ((int)state.Current.PropertyState < 4) { if (reader.TokenType == JsonTokenType.EndArray) { break; } state.Current.PropertyState = StackFramePropertyState.ReadValueIsEnd; } if ((int)state.Current.PropertyState < 5) { if (!elementConverter2.TryRead(ref reader, typeof(TElement), options, ref state, out var value4)) { value = default(TCollection); return false; } Add(in value4, ref state); state.Current.EndElement(); } } state.Current.ObjectState = StackFrameObjectState.ReadElements; } if ((int)state.Current.ObjectState < 17) { state.Current.ObjectState = StackFrameObjectState.EndToken; if (state.Current.ValidateEndTokenOnArray && !reader.Read()) { value = default(TCollection); return false; } } if ((int)state.Current.ObjectState < 18 && state.Current.ValidateEndTokenOnArray && reader.TokenType != JsonTokenType.EndObject) { ThrowHelper.ThrowJsonException_MetadataPreservedArrayInvalidProperty(ref state, typeToConvert, in reader); } } ConvertCollection(ref state, options); value = (TCollection)state.Current.ReturnValue; return true; } internal sealed override bool OnTryWrite(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { bool flag; if (value == null) { writer.WriteNullValue(); flag = true; } else { if (!state.Current.ProcessedStartToken) { state.Current.ProcessedStartToken = true; if (options.ReferenceHandler == null) { writer.WriteStartArray(); } else { MetadataPropertyName metadataPropertyName = JsonSerializer.WriteReferenceForCollection(this, value, ref state, writer); if (metadataPropertyName == MetadataPropertyName.Ref) { return true; } state.Current.MetadataPropertyName = metadataPropertyName; } state.Current.DeclaredJsonPropertyInfo = state.Current.JsonClassInfo.ElementClassInfo.PropertyInfoForClassInfo; } flag = OnWriteResume(writer, value, options, ref state); if (flag && !state.Current.ProcessedEndToken) { state.Current.ProcessedEndToken = true; writer.WriteEndArray(); if (state.Current.MetadataPropertyName == MetadataPropertyName.Id) { writer.WriteEndObject(); } } } return flag; } protected abstract bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state); internal sealed override void CreateInstanceForReferenceResolver(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { CreateCollection(ref reader, ref state, options); } } internal sealed class IEnumerableOfTConverter : IEnumerableDefaultConverter where TCollection : IEnumerable { internal override Type RuntimeType => typeof(List); protected override void Add(in TElement value, ref ReadStack state) { ((List)state.Current.ReturnValue).Add(value); } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { if (!TypeToConvert.IsAssignableFrom(RuntimeType)) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = new List(); } protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IEnumerator enumerator; if (state.Current.CollectionEnumerator == null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) { return true; } } else { enumerator = (IEnumerator)state.Current.CollectionEnumerator; } JsonConverter elementConverter = IEnumerableDefaultConverter.GetElementConverter(ref state); do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } TElement value2 = enumerator.Current; if (!elementConverter.TryWrite(writer, in value2, options, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } } while (enumerator.MoveNext()); return true; } } internal sealed class IEnumerableWithAddMethodConverter : IEnumerableDefaultConverter where TCollection : IEnumerable { protected override void Add(in object value, ref ReadStack state) { Action action = (Action)state.Current.JsonClassInfo.AddMethodDelegate; action((TCollection)state.Current.ReturnValue, value); } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { JsonClassInfo jsonClassInfo = state.Current.JsonClassInfo; JsonClassInfo.ConstructorDelegate createObject = jsonClassInfo.CreateObject; if (createObject == null) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = createObject(); if (jsonClassInfo.AddMethodDelegate == null) { jsonClassInfo.AddMethodDelegate = options.MemberAccessorStrategy.CreateAddMethodDelegate(); } } protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IEnumerator enumerator; if (state.Current.CollectionEnumerator == null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) { return true; } } else { enumerator = state.Current.CollectionEnumerator; } JsonConverter elementConverter = IEnumerableDefaultConverter.GetElementConverter(ref state); do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } object value2 = enumerator.Current; if (!elementConverter.TryWrite(writer, in value2, options, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } } while (enumerator.MoveNext()); return true; } } internal sealed class IListConverter : IEnumerableDefaultConverter where TCollection : IList { internal override Type RuntimeType { get { if (TypeToConvert.IsAbstract || TypeToConvert.IsInterface) { return typeof(List); } return TypeToConvert; } } protected override void Add(in object value, ref ReadStack state) { ((IList)state.Current.ReturnValue).Add(value); } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { JsonClassInfo jsonClassInfo = state.Current.JsonClassInfo; if (TypeToConvert.IsInterface || TypeToConvert.IsAbstract) { if (!TypeToConvert.IsAssignableFrom(RuntimeType)) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = new List(); return; } if (jsonClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(TypeToConvert, ref reader, ref state); } TCollection val = (TCollection)jsonClassInfo.CreateObject(); if (val.IsReadOnly) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = val; } protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IList list = value; int i = state.Current.EnumeratorIndex; JsonConverter elementConverter = IEnumerableDefaultConverter.GetElementConverter(ref state); if (elementConverter.CanUseDirectReadOrWrite && !state.Current.NumberHandling.HasValue) { for (; i < list.Count; i++) { elementConverter.Write(writer, list[i], options); } } else { for (; i < list.Count; i++) { object value2 = list[i]; if (!elementConverter.TryWrite(writer, in value2, options, ref state)) { state.Current.EnumeratorIndex = i; return false; } if (ShouldFlush(writer, ref state)) { i = (state.Current.EnumeratorIndex = i + 1); return false; } } } return true; } } internal sealed class IListOfTConverter : IEnumerableDefaultConverter where TCollection : IList { internal override Type RuntimeType { get { if (TypeToConvert.IsAbstract || TypeToConvert.IsInterface) { return typeof(List); } return TypeToConvert; } } protected override void Add(in TElement value, ref ReadStack state) { ((TCollection)state.Current.ReturnValue).Add(value); } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { JsonClassInfo jsonClassInfo = state.Current.JsonClassInfo; if (TypeToConvert.IsInterface || TypeToConvert.IsAbstract) { if (!TypeToConvert.IsAssignableFrom(RuntimeType)) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = new List(); return; } if (jsonClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(TypeToConvert, ref reader, ref state); } TCollection val = (TCollection)jsonClassInfo.CreateObject(); if (val.IsReadOnly) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = val; } protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IEnumerator enumerator; if (state.Current.CollectionEnumerator == null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) { return true; } } else { enumerator = (IEnumerator)state.Current.CollectionEnumerator; } JsonConverter elementConverter = IEnumerableDefaultConverter.GetElementConverter(ref state); do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } TElement value2 = enumerator.Current; if (!elementConverter.TryWrite(writer, in value2, options, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } } while (enumerator.MoveNext()); return true; } } internal sealed class ImmutableDictionaryOfTKeyTValueConverter : DictionaryDefaultConverter where TCollection : IReadOnlyDictionary { internal override bool CanHaveIdMetadata => false; protected override void Add(TKey key, in TValue value, JsonSerializerOptions options, ref ReadStack state) { ((Dictionary)state.Current.ReturnValue)[key] = value; } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state) { state.Current.ReturnValue = new Dictionary(); } protected override void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) { JsonClassInfo jsonClassInfo = state.Current.JsonClassInfo; Func>, TCollection> func = (Func>, TCollection>)jsonClassInfo.CreateObjectWithArgs; if (func == null) { func = (Func>, TCollection>)(jsonClassInfo.CreateObjectWithArgs = options.MemberAccessorStrategy.CreateImmutableDictionaryCreateRangeDelegate()); } state.Current.ReturnValue = func((Dictionary)state.Current.ReturnValue); } protected internal override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IEnumerator> enumerator; if (state.Current.CollectionEnumerator == null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) { return true; } } else { enumerator = (IEnumerator>)state.Current.CollectionEnumerator; } JsonConverter jsonConverter = _keyConverter ?? (_keyConverter = DictionaryDefaultConverter.GetKeyConverter(KeyType, options)); JsonConverter jsonConverter2 = _valueConverter ?? (_valueConverter = DictionaryDefaultConverter.GetValueConverter(state.Current.JsonClassInfo.ElementClassInfo)); do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } if ((int)state.Current.PropertyState < 2) { state.Current.PropertyState = StackFramePropertyState.Name; TKey key = enumerator.Current.Key; jsonConverter.WriteWithQuotes(writer, key, options, ref state); } TValue value2 = enumerator.Current.Value; if (!jsonConverter2.TryWrite(writer, in value2, options, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } state.Current.EndDictionaryElement(); } while (enumerator.MoveNext()); return true; } } internal sealed class ImmutableEnumerableOfTConverter : IEnumerableDefaultConverter where TCollection : IEnumerable { internal override bool CanHaveIdMetadata => false; protected override void Add(in TElement value, ref ReadStack state) { ((List)state.Current.ReturnValue).Add(value); } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { state.Current.ReturnValue = new List(); } protected override void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) { JsonClassInfo jsonClassInfo = state.Current.JsonClassInfo; Func, TCollection> func = (Func, TCollection>)jsonClassInfo.CreateObjectWithArgs; if (func == null) { func = (Func, TCollection>)(jsonClassInfo.CreateObjectWithArgs = options.MemberAccessorStrategy.CreateImmutableEnumerableCreateRangeDelegate()); } state.Current.ReturnValue = func((List)state.Current.ReturnValue); } protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IEnumerator enumerator; if (state.Current.CollectionEnumerator == null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) { return true; } } else { enumerator = (IEnumerator)state.Current.CollectionEnumerator; } JsonConverter elementConverter = IEnumerableDefaultConverter.GetElementConverter(ref state); do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } TElement value2 = enumerator.Current; if (!elementConverter.TryWrite(writer, in value2, options, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } } while (enumerator.MoveNext()); return true; } } internal sealed class IReadOnlyDictionaryOfTKeyTValueConverter : DictionaryDefaultConverter where TCollection : IReadOnlyDictionary { internal override Type RuntimeType => typeof(Dictionary); protected override void Add(TKey key, in TValue value, JsonSerializerOptions options, ref ReadStack state) { ((Dictionary)state.Current.ReturnValue)[key] = value; } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state) { if (!TypeToConvert.IsAssignableFrom(RuntimeType)) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = new Dictionary(); } protected internal override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IEnumerator> enumerator; if (state.Current.CollectionEnumerator == null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) { return true; } } else { enumerator = (Dictionary.Enumerator)(object)state.Current.CollectionEnumerator; } JsonConverter jsonConverter = _keyConverter ?? (_keyConverter = DictionaryDefaultConverter.GetKeyConverter(KeyType, options)); JsonConverter jsonConverter2 = _valueConverter ?? (_valueConverter = DictionaryDefaultConverter.GetValueConverter(state.Current.JsonClassInfo.ElementClassInfo)); do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } if ((int)state.Current.PropertyState < 2) { state.Current.PropertyState = StackFramePropertyState.Name; TKey key = enumerator.Current.Key; jsonConverter.WriteWithQuotes(writer, key, options, ref state); } TValue value2 = enumerator.Current.Value; if (!jsonConverter2.TryWrite(writer, in value2, options, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } state.Current.EndDictionaryElement(); } while (enumerator.MoveNext()); return true; } } internal sealed class ISetOfTConverter : IEnumerableDefaultConverter where TCollection : ISet { internal override Type RuntimeType { get { if (TypeToConvert.IsAbstract || TypeToConvert.IsInterface) { return typeof(HashSet); } return TypeToConvert; } } protected override void Add(in TElement value, ref ReadStack state) { ((TCollection)state.Current.ReturnValue).Add(value); } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { JsonClassInfo jsonClassInfo = state.Current.JsonClassInfo; if (TypeToConvert.IsInterface || TypeToConvert.IsAbstract) { if (!TypeToConvert.IsAssignableFrom(RuntimeType)) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = new HashSet(); return; } if (jsonClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(TypeToConvert, ref reader, ref state); } TCollection val = (TCollection)jsonClassInfo.CreateObject(); if (val.IsReadOnly) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = val; } protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IEnumerator enumerator; if (state.Current.CollectionEnumerator == null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) { return true; } } else { enumerator = (IEnumerator)state.Current.CollectionEnumerator; } JsonConverter elementConverter = IEnumerableDefaultConverter.GetElementConverter(ref state); do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } TElement value2 = enumerator.Current; if (!elementConverter.TryWrite(writer, in value2, options, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } } while (enumerator.MoveNext()); return true; } } internal sealed class ListOfTConverter : IEnumerableDefaultConverter where TCollection : List { protected override void Add(in TElement value, ref ReadStack state) { ((TCollection)state.Current.ReturnValue).Add(value); } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { if (state.Current.JsonClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(state.Current.JsonClassInfo.Type); } state.Current.ReturnValue = state.Current.JsonClassInfo.CreateObject(); } protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { int i = state.Current.EnumeratorIndex; JsonConverter elementConverter = IEnumerableDefaultConverter.GetElementConverter(ref state); if (elementConverter.CanUseDirectReadOrWrite && !state.Current.NumberHandling.HasValue) { for (; i < value.Count; i++) { elementConverter.Write(writer, value[i], options); } } else { for (; i < value.Count; i++) { TElement value2 = value[i]; if (!elementConverter.TryWrite(writer, in value2, options, ref state)) { state.Current.EnumeratorIndex = i; return false; } if (ShouldFlush(writer, ref state)) { i = (state.Current.EnumeratorIndex = i + 1); return false; } } } return true; } } internal sealed class QueueOfTConverter : IEnumerableDefaultConverter where TCollection : Queue { protected override void Add(in TElement value, ref ReadStack state) { ((TCollection)state.Current.ReturnValue).Enqueue(value); } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { if (state.Current.JsonClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(state.Current.JsonClassInfo.Type); } state.Current.ReturnValue = state.Current.JsonClassInfo.CreateObject(); } protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IEnumerator enumerator; if (state.Current.CollectionEnumerator == null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) { return true; } } else { enumerator = (IEnumerator)state.Current.CollectionEnumerator; } JsonConverter elementConverter = IEnumerableDefaultConverter.GetElementConverter(ref state); do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } TElement value2 = enumerator.Current; if (!elementConverter.TryWrite(writer, in value2, options, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } } while (enumerator.MoveNext()); return true; } } internal sealed class StackOfTConverter : IEnumerableDefaultConverter where TCollection : Stack { protected override void Add(in TElement value, ref ReadStack state) { ((TCollection)state.Current.ReturnValue).Push(value); } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { if (state.Current.JsonClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(state.Current.JsonClassInfo.Type); } state.Current.ReturnValue = state.Current.JsonClassInfo.CreateObject(); } protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IEnumerator enumerator; if (state.Current.CollectionEnumerator == null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) { return true; } } else { enumerator = (IEnumerator)state.Current.CollectionEnumerator; } JsonConverter elementConverter = IEnumerableDefaultConverter.GetElementConverter(ref state); do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } TElement value2 = enumerator.Current; if (!elementConverter.TryWrite(writer, in value2, options, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } } while (enumerator.MoveNext()); return true; } } internal sealed class KeyValuePairConverter : SmallObjectWithParameterizedConstructorConverter, TKey, TValue, object, object> { private const string KeyNameCLR = "Key"; private const string ValueNameCLR = "Value"; private const int NumProperties = 2; private string _keyName; private string _valueName; private static readonly ConstructorInfo s_constructorInfo = typeof(KeyValuePair).GetConstructor(new Type[2] { typeof(TKey), typeof(TValue) }); internal override void Initialize(JsonSerializerOptions options) { JsonNamingPolicy propertyNamingPolicy = options.PropertyNamingPolicy; if (propertyNamingPolicy == null) { _keyName = "Key"; _valueName = "Value"; } else { _keyName = propertyNamingPolicy.ConvertName("Key"); _valueName = propertyNamingPolicy.ConvertName("Value"); } base.ConstructorInfo = s_constructorInfo; } protected override bool TryLookupConstructorParameter(ref ReadStack state, ref Utf8JsonReader reader, JsonSerializerOptions options, out JsonParameterInfo jsonParameterInfo) { JsonClassInfo jsonClassInfo = state.Current.JsonClassInfo; ArgumentState ctorArgumentState = state.Current.CtorArgumentState; bool propertyNameCaseInsensitive = options.PropertyNameCaseInsensitive; string @string = reader.GetString(); state.Current.JsonPropertyNameAsString = @string; if (!ctorArgumentState.FoundKey && FoundKeyProperty(@string, propertyNameCaseInsensitive)) { jsonParameterInfo = jsonClassInfo.ParameterCache[_keyName]; ctorArgumentState.FoundKey = true; } else { if (ctorArgumentState.FoundValue || !FoundValueProperty(@string, propertyNameCaseInsensitive)) { ThrowHelper.ThrowJsonException(); jsonParameterInfo = null; return false; } jsonParameterInfo = jsonClassInfo.ParameterCache[_valueName]; ctorArgumentState.FoundValue = true; } ctorArgumentState.ParameterIndex++; ctorArgumentState.JsonParameterInfo = jsonParameterInfo; state.Current.NumberHandling = jsonParameterInfo.NumberHandling; return true; } protected override void EndRead(ref ReadStack state) { if (state.Current.CtorArgumentState.ParameterIndex != 2) { ThrowHelper.ThrowJsonException(); } } private bool FoundKeyProperty(string propertyName, bool caseInsensitiveMatch) { if (!(propertyName == _keyName) && (!caseInsensitiveMatch || !string.Equals(propertyName, _keyName, StringComparison.OrdinalIgnoreCase))) { return propertyName == "Key"; } return true; } private bool FoundValueProperty(string propertyName, bool caseInsensitiveMatch) { if (!(propertyName == _valueName) && (!caseInsensitiveMatch || !string.Equals(propertyName, _valueName, StringComparison.OrdinalIgnoreCase))) { return propertyName == "Value"; } return true; } } internal class ObjectConverterFactory : JsonConverterFactory { public override bool CanConvert(Type typeToConvert) { return true; } public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { if (IsKeyValuePair(typeToConvert)) { return CreateKeyValuePairConverter(typeToConvert, options); } ConstructorInfo deserializationConstructor = GetDeserializationConstructor(typeToConvert); ParameterInfo[] array = deserializationConstructor?.GetParameters(); Type type; if (deserializationConstructor == null || typeToConvert.IsAbstract || array.Length == 0) { type = typeof(ObjectDefaultConverter<>).MakeGenericType(typeToConvert); } else { int num = array.Length; if (num <= 4) { Type objectType = JsonClassInfo.ObjectType; Type[] array2 = new Type[5] { typeToConvert, null, null, null, null }; for (int i = 0; i < 4; i++) { if (i < num) { array2[i + 1] = array[i].ParameterType; } else { array2[i + 1] = objectType; } } type = typeof(SmallObjectWithParameterizedConstructorConverter<, , , , >).MakeGenericType(array2); } else { type = typeof(LargeObjectWithParameterizedConstructorConverter<>).MakeGenericType(typeToConvert); } } JsonConverter jsonConverter = (JsonConverter)Activator.CreateInstance(type, BindingFlags.Instance | BindingFlags.Public, null, null, null); jsonConverter.ConstructorInfo = deserializationConstructor; return jsonConverter; } private bool IsKeyValuePair(Type typeToConvert) { if (!typeToConvert.IsGenericType) { return false; } Type genericTypeDefinition = typeToConvert.GetGenericTypeDefinition(); return genericTypeDefinition == typeof(KeyValuePair<, >); } private JsonConverter CreateKeyValuePairConverter(Type type, JsonSerializerOptions options) { Type type2 = type.GetGenericArguments()[0]; Type type3 = type.GetGenericArguments()[1]; JsonConverter jsonConverter = (JsonConverter)Activator.CreateInstance(typeof(KeyValuePairConverter<, >).MakeGenericType(type2, type3), BindingFlags.Instance | BindingFlags.Public, null, null, null); jsonConverter.Initialize(options); return jsonConverter; } private ConstructorInfo GetDeserializationConstructor(Type type) { ConstructorInfo constructorInfo = null; ConstructorInfo constructorInfo2 = null; ConstructorInfo constructorInfo3 = null; ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public); if (constructors.Length == 1) { constructorInfo3 = constructors[0]; } ConstructorInfo[] array = constructors; foreach (ConstructorInfo constructorInfo4 in array) { if (constructorInfo4.GetCustomAttribute() != null) { if (constructorInfo != null) { ThrowHelper.ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(type); } constructorInfo = constructorInfo4; } else if (constructorInfo4.GetParameters().Length == 0) { constructorInfo2 = constructorInfo4; } } ConstructorInfo constructorInfo5 = constructorInfo; constructors = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic); ConstructorInfo[] array2 = constructors; foreach (ConstructorInfo constructorInfo6 in array2) { if (constructorInfo6.GetCustomAttribute() != null) { if (constructorInfo5 != null) { ThrowHelper.ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(type); } constructorInfo5 = constructorInfo6; } } if (type.IsValueType && constructorInfo == null) { return null; } return constructorInfo ?? constructorInfo2 ?? constructorInfo3; } } internal class ObjectDefaultConverter : JsonObjectConverter { internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, [MaybeNullWhen(false)] out T value) { object obj; if (state.UseFastPath) { if (reader.TokenType != JsonTokenType.StartObject) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } if (state.Current.JsonClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(state.Current.JsonClassInfo.Type, ref reader, ref state); } obj = state.Current.JsonClassInfo.CreateObject(); while (true) { reader.ReadWithVerify(); JsonTokenType tokenType = reader.TokenType; if (tokenType == JsonTokenType.EndObject) { break; } ReadOnlySpan propertyName = JsonSerializer.GetPropertyName(ref state, ref reader, options); bool useExtensionProperty; JsonPropertyInfo jsonPropertyInfo = JsonSerializer.LookupProperty(obj, propertyName, ref state, out useExtensionProperty); ReadPropertyValue(obj, ref state, ref reader, jsonPropertyInfo, useExtensionProperty); } } else { if (state.Current.ObjectState == StackFrameObjectState.None) { if (reader.TokenType != JsonTokenType.StartObject) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } state.Current.ObjectState = StackFrameObjectState.StartToken; } if ((int)state.Current.ObjectState < 14 && options.ReferenceHandler != null) { if (!JsonSerializer.ResolveMetadataForJsonObject(ref reader, ref state, options)) { value = default(T); return false; } if (state.Current.ObjectState == StackFrameObjectState.ReadRefEndObject) { value = (T)state.Current.ReturnValue; return true; } } if ((int)state.Current.ObjectState < 15) { if (state.Current.JsonClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(state.Current.JsonClassInfo.Type, ref reader, ref state); } obj = state.Current.JsonClassInfo.CreateObject(); state.Current.ReturnValue = obj; state.Current.ObjectState = StackFrameObjectState.CreatedObject; } else { obj = state.Current.ReturnValue; } while (true) { if (state.Current.PropertyState == StackFramePropertyState.None) { state.Current.PropertyState = StackFramePropertyState.ReadName; if (!reader.Read()) { state.Current.ReturnValue = obj; value = default(T); return false; } } JsonPropertyInfo jsonPropertyInfo2; if ((int)state.Current.PropertyState < 2) { state.Current.PropertyState = StackFramePropertyState.Name; JsonTokenType tokenType2 = reader.TokenType; if (tokenType2 == JsonTokenType.EndObject) { break; } ReadOnlySpan propertyName2 = JsonSerializer.GetPropertyName(ref state, ref reader, options); jsonPropertyInfo2 = JsonSerializer.LookupProperty(obj, propertyName2, ref state, out var useExtensionProperty2); state.Current.UseExtensionProperty = useExtensionProperty2; } else { jsonPropertyInfo2 = state.Current.JsonPropertyInfo; } if ((int)state.Current.PropertyState < 3) { if (!jsonPropertyInfo2.ShouldDeserialize) { if (!reader.TrySkip()) { state.Current.ReturnValue = obj; value = default(T); return false; } state.Current.EndProperty(); continue; } if (!ReadAheadPropertyValue(ref state, ref reader, jsonPropertyInfo2)) { state.Current.ReturnValue = obj; value = default(T); return false; } } if ((int)state.Current.PropertyState >= 5) { continue; } if (!state.Current.UseExtensionProperty) { if (!jsonPropertyInfo2.ReadJsonAndSetMember(obj, ref state, ref reader)) { state.Current.ReturnValue = obj; value = default(T); return false; } } else if (!jsonPropertyInfo2.ReadJsonAndAddExtensionProperty(obj, ref state, ref reader)) { state.Current.ReturnValue = obj; value = default(T); return false; } state.Current.EndProperty(); } } if (state.Current.PropertyRefCache != null) { state.Current.JsonClassInfo.UpdateSortedPropertyCache(ref state.Current); } value = (T)obj; return true; } internal sealed override bool OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state) { object obj = value; if (!state.SupportContinuation) { writer.WriteStartObject(); if (options.ReferenceHandler != null && JsonSerializer.WriteReferenceForObject(this, obj, ref state, writer) == MetadataPropertyName.Ref) { return true; } JsonPropertyInfo dataExtensionProperty = state.Current.JsonClassInfo.DataExtensionProperty; int num = 0; JsonPropertyInfo[] propertyCacheArray = state.Current.JsonClassInfo.PropertyCacheArray; if (propertyCacheArray != null) { num = propertyCacheArray.Length; } for (int i = 0; i < num; i++) { JsonPropertyInfo jsonPropertyInfo = propertyCacheArray[i]; state.Current.DeclaredJsonPropertyInfo = jsonPropertyInfo; state.Current.NumberHandling = jsonPropertyInfo.NumberHandling; if (jsonPropertyInfo.ShouldSerialize) { if (jsonPropertyInfo == dataExtensionProperty) { if (!jsonPropertyInfo.GetMemberAndWriteJsonExtensionData(obj, ref state, writer)) { return false; } } else if (!jsonPropertyInfo.GetMemberAndWriteJson(obj, ref state, writer)) { return false; } } state.Current.EndProperty(); } writer.WriteEndObject(); return true; } if (!state.Current.ProcessedStartToken) { writer.WriteStartObject(); if (options.ReferenceHandler != null && JsonSerializer.WriteReferenceForObject(this, obj, ref state, writer) == MetadataPropertyName.Ref) { return true; } state.Current.ProcessedStartToken = true; } JsonPropertyInfo dataExtensionProperty2 = state.Current.JsonClassInfo.DataExtensionProperty; int num2 = 0; JsonPropertyInfo[] propertyCacheArray2 = state.Current.JsonClassInfo.PropertyCacheArray; if (propertyCacheArray2 != null) { num2 = propertyCacheArray2.Length; } while (num2 > state.Current.EnumeratorIndex) { JsonPropertyInfo jsonPropertyInfo2 = propertyCacheArray2[state.Current.EnumeratorIndex]; state.Current.DeclaredJsonPropertyInfo = jsonPropertyInfo2; state.Current.NumberHandling = jsonPropertyInfo2.NumberHandling; if (jsonPropertyInfo2.ShouldSerialize) { if (jsonPropertyInfo2 == dataExtensionProperty2) { if (!jsonPropertyInfo2.GetMemberAndWriteJsonExtensionData(obj, ref state, writer)) { return false; } } else if (!jsonPropertyInfo2.GetMemberAndWriteJson(obj, ref state, writer)) { return false; } } state.Current.EndProperty(); state.Current.EnumeratorIndex++; if (ShouldFlush(writer, ref state)) { return false; } } if (!state.Current.ProcessedEndToken) { state.Current.ProcessedEndToken = true; writer.WriteEndObject(); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected void ReadPropertyValue(object obj, ref ReadStack state, ref Utf8JsonReader reader, JsonPropertyInfo jsonPropertyInfo, bool useExtensionProperty) { if (!jsonPropertyInfo.ShouldDeserialize) { reader.Skip(); } else { reader.ReadWithVerify(); if (!useExtensionProperty) { jsonPropertyInfo.ReadJsonAndSetMember(obj, ref state, ref reader); } else { jsonPropertyInfo.ReadJsonAndAddExtensionProperty(obj, ref state, ref reader); } } state.Current.EndProperty(); } protected bool ReadAheadPropertyValue(ref ReadStack state, ref Utf8JsonReader reader, JsonPropertyInfo jsonPropertyInfo) { state.Current.PropertyState = StackFramePropertyState.ReadValue; if (!state.Current.UseExtensionProperty) { if (!JsonConverter.SingleValueReadWithReadAhead(jsonPropertyInfo.ConverterBase.ClassType, ref reader, ref state)) { return false; } } else if (!JsonConverter.SingleValueReadWithReadAhead(ClassType.Value, ref reader, ref state)) { return false; } return true; } internal sealed override void CreateInstanceForReferenceResolver(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { if (state.Current.JsonClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(state.Current.JsonClassInfo.Type, ref reader, ref state); } object returnValue = state.Current.JsonClassInfo.CreateObject(); state.Current.ReturnValue = returnValue; } } internal abstract class ObjectWithParameterizedConstructorConverter : ObjectDefaultConverter { internal override bool ConstructorIsParameterized => true; internal sealed override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, [MaybeNullWhen(false)] out T value) { ArgumentState ctorArgumentState = state.Current.CtorArgumentState; object obj; if (state.UseFastPath) { ReadOnlySpan originalSpan = reader.OriginalSpan; ReadConstructorArguments(ref state, ref reader, options); obj = CreateObject(ref state.Current); if (ctorArgumentState.FoundPropertyCount > 0) { (JsonPropertyInfo, JsonReaderState, long, byte[], string)[] foundProperties = ctorArgumentState.FoundProperties; for (int i = 0; i < ctorArgumentState.FoundPropertyCount; i++) { JsonPropertyInfo item = foundProperties[i].Item1; long item2 = foundProperties[i].Item3; byte[] item3 = foundProperties[i].Item4; string item4 = foundProperties[i].Item5; Utf8JsonReader reader2 = new Utf8JsonReader(originalSpan.Slice(checked((int)item2)), isFinalBlock: true, foundProperties[i].Item2); state.Current.JsonPropertyName = item3; state.Current.JsonPropertyInfo = item; state.Current.NumberHandling = item.NumberHandling; bool flag = item4 != null; if (flag) { state.Current.JsonPropertyNameAsString = item4; JsonSerializer.CreateDataExtensionProperty(obj, item); } ReadPropertyValue(obj, ref state, ref reader2, item, flag); } ArrayPool<(JsonPropertyInfo, JsonReaderState, long, byte[], string)>.Shared.Return(ctorArgumentState.FoundProperties, clearArray: true); ctorArgumentState.FoundProperties = null; } } else { if (state.Current.ObjectState == StackFrameObjectState.None) { state.Current.ObjectState = StackFrameObjectState.StartToken; BeginRead(ref state, ref reader, options); } if (!ReadConstructorArgumentsWithContinuation(ref state, ref reader, options)) { value = default(T); return false; } obj = CreateObject(ref state.Current); if (ctorArgumentState.FoundPropertyCount > 0) { for (int j = 0; j < ctorArgumentState.FoundPropertyCount; j++) { JsonPropertyInfo item5 = ctorArgumentState.FoundPropertiesAsync[j].Item1; object item6 = ctorArgumentState.FoundPropertiesAsync[j].Item2; string item7 = ctorArgumentState.FoundPropertiesAsync[j].Item3; if (item7 == null) { item5.SetExtensionDictionaryAsObject(obj, item6); continue; } JsonSerializer.CreateDataExtensionProperty(obj, item5); object valueAsObject = item5.GetValueAsObject(obj); if (valueAsObject is IDictionary dictionary) { dictionary[item7] = (JsonElement)item6; } else { ((IDictionary)valueAsObject)[item7] = item6; } } ArrayPool<(JsonPropertyInfo, object, string)>.Shared.Return(ctorArgumentState.FoundPropertiesAsync, clearArray: true); ctorArgumentState.FoundPropertiesAsync = null; } } if (state.Current.PropertyRefCache != null) { state.Current.JsonClassInfo.UpdateSortedPropertyCache(ref state.Current); } if (ctorArgumentState.ParameterRefCache != null) { state.Current.JsonClassInfo.UpdateSortedParameterCache(ref state.Current); } EndRead(ref state); value = (T)obj; return true; } protected abstract void InitializeConstructorArgumentCaches(ref ReadStack state, JsonSerializerOptions options); protected abstract bool ReadAndCacheConstructorArgument(ref ReadStack state, ref Utf8JsonReader reader, JsonParameterInfo jsonParameterInfo); protected abstract object CreateObject(ref ReadStackFrame frame); [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ReadConstructorArguments(ref ReadStack state, ref Utf8JsonReader reader, JsonSerializerOptions options) { BeginRead(ref state, ref reader, options); while (true) { reader.ReadWithVerify(); JsonTokenType tokenType = reader.TokenType; if (tokenType == JsonTokenType.EndObject) { break; } if (TryLookupConstructorParameter(ref state, ref reader, options, out var jsonParameterInfo)) { reader.ReadWithVerify(); if (!jsonParameterInfo.ShouldDeserialize) { reader.Skip(); state.Current.EndConstructorParameter(); } else { ReadAndCacheConstructorArgument(ref state, ref reader, jsonParameterInfo); state.Current.EndConstructorParameter(); } continue; } ReadOnlySpan propertyName = JsonSerializer.GetPropertyName(ref state, ref reader, options); bool useExtensionProperty; JsonPropertyInfo jsonPropertyInfo = JsonSerializer.LookupProperty(null, propertyName, ref state, out useExtensionProperty, createExtensionProperty: false); if (jsonPropertyInfo.ShouldDeserialize) { ArgumentState ctorArgumentState = state.Current.CtorArgumentState; if (ctorArgumentState.FoundProperties == null) { ctorArgumentState.FoundProperties = ArrayPool<(JsonPropertyInfo, JsonReaderState, long, byte[], string)>.Shared.Rent(Math.Max(1, state.Current.JsonClassInfo.PropertyCache.Count)); } else if (ctorArgumentState.FoundPropertyCount == ctorArgumentState.FoundProperties.Length) { (JsonPropertyInfo, JsonReaderState, long, byte[], string)[] array = ArrayPool<(JsonPropertyInfo, JsonReaderState, long, byte[], string)>.Shared.Rent(ctorArgumentState.FoundProperties.Length * 2); ctorArgumentState.FoundProperties.CopyTo(array, 0); ArrayPool<(JsonPropertyInfo, JsonReaderState, long, byte[], string)>.Shared.Return(ctorArgumentState.FoundProperties, clearArray: true); ctorArgumentState.FoundProperties = array; } ctorArgumentState.FoundProperties[ctorArgumentState.FoundPropertyCount++] = (jsonPropertyInfo, reader.CurrentState, reader.BytesConsumed, state.Current.JsonPropertyName, state.Current.JsonPropertyNameAsString); } reader.Skip(); state.Current.EndProperty(); } } private bool ReadConstructorArgumentsWithContinuation(ref ReadStack state, ref Utf8JsonReader reader, JsonSerializerOptions options) { while (true) { if (state.Current.PropertyState == StackFramePropertyState.None) { state.Current.PropertyState = StackFramePropertyState.ReadName; if (!reader.Read()) { return false; } } JsonParameterInfo jsonParameterInfo; JsonPropertyInfo jsonPropertyInfo; if ((int)state.Current.PropertyState < 2) { state.Current.PropertyState = StackFramePropertyState.Name; JsonTokenType tokenType = reader.TokenType; if (tokenType == JsonTokenType.EndObject) { return true; } if (TryLookupConstructorParameter(ref state, ref reader, options, out jsonParameterInfo)) { jsonPropertyInfo = null; } else { ReadOnlySpan propertyName = JsonSerializer.GetPropertyName(ref state, ref reader, options); jsonPropertyInfo = JsonSerializer.LookupProperty(null, propertyName, ref state, out var useExtensionProperty, createExtensionProperty: false); state.Current.UseExtensionProperty = useExtensionProperty; } } else { jsonParameterInfo = state.Current.CtorArgumentState.JsonParameterInfo; jsonPropertyInfo = state.Current.JsonPropertyInfo; } if (jsonParameterInfo != null) { if (!HandleConstructorArgumentWithContinuation(ref state, ref reader, jsonParameterInfo)) { return false; } } else if (!HandlePropertyWithContinuation(ref state, ref reader, jsonPropertyInfo)) { break; } } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool HandleConstructorArgumentWithContinuation(ref ReadStack state, ref Utf8JsonReader reader, JsonParameterInfo jsonParameterInfo) { if ((int)state.Current.PropertyState < 3) { if (!jsonParameterInfo.ShouldDeserialize) { if (!reader.TrySkip()) { return false; } state.Current.EndConstructorParameter(); return true; } state.Current.PropertyState = StackFramePropertyState.ReadValue; if (!JsonConverter.SingleValueReadWithReadAhead(jsonParameterInfo.ConverterBase.ClassType, ref reader, ref state)) { return false; } } if (!ReadAndCacheConstructorArgument(ref state, ref reader, jsonParameterInfo)) { return false; } state.Current.EndConstructorParameter(); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool HandlePropertyWithContinuation(ref ReadStack state, ref Utf8JsonReader reader, JsonPropertyInfo jsonPropertyInfo) { if ((int)state.Current.PropertyState < 3) { if (!jsonPropertyInfo.ShouldDeserialize) { if (!reader.TrySkip()) { return false; } state.Current.EndProperty(); return true; } if (!ReadAheadPropertyValue(ref state, ref reader, jsonPropertyInfo)) { return false; } } object value; if (state.Current.UseExtensionProperty) { if (!jsonPropertyInfo.ReadJsonExtensionDataValue(ref state, ref reader, out value)) { return false; } } else if (!jsonPropertyInfo.ReadJsonAsObject(ref state, ref reader, out value)) { return false; } ArgumentState ctorArgumentState = state.Current.CtorArgumentState; if (ctorArgumentState.FoundPropertiesAsync == null) { ctorArgumentState.FoundPropertiesAsync = ArrayPool<(JsonPropertyInfo, object, string)>.Shared.Rent(Math.Max(1, state.Current.JsonClassInfo.PropertyCache.Count)); } else if (ctorArgumentState.FoundPropertyCount == ctorArgumentState.FoundPropertiesAsync.Length) { (JsonPropertyInfo, object, string)[] array = ArrayPool<(JsonPropertyInfo, object, string)>.Shared.Rent(ctorArgumentState.FoundPropertiesAsync.Length * 2); ctorArgumentState.FoundPropertiesAsync.CopyTo(array, 0); ArrayPool<(JsonPropertyInfo, object, string)>.Shared.Return(ctorArgumentState.FoundPropertiesAsync, clearArray: true); ctorArgumentState.FoundPropertiesAsync = array; } ctorArgumentState.FoundPropertiesAsync[ctorArgumentState.FoundPropertyCount++] = (jsonPropertyInfo, value, state.Current.JsonPropertyNameAsString); state.Current.EndProperty(); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void BeginRead(ref ReadStack state, ref Utf8JsonReader reader, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.StartObject) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } if (state.Current.JsonClassInfo.ParameterCount != state.Current.JsonClassInfo.ParameterCache.Count) { ThrowHelper.ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(base.ConstructorInfo, TypeToConvert); } state.Current.JsonPropertyInfo = null; InitializeConstructorArgumentCaches(ref state, options); } protected virtual void EndRead(ref ReadStack state) { } protected virtual bool TryLookupConstructorParameter(ref ReadStack state, ref Utf8JsonReader reader, JsonSerializerOptions options, out JsonParameterInfo jsonParameterInfo) { ReadOnlySpan propertyName = JsonSerializer.GetPropertyName(ref state, ref reader, options); jsonParameterInfo = state.Current.JsonClassInfo.GetParameter(propertyName, ref state.Current, out var utf8PropertyName); state.Current.CtorArgumentState.ParameterIndex++; state.Current.JsonPropertyName = utf8PropertyName; state.Current.CtorArgumentState.JsonParameterInfo = jsonParameterInfo; state.Current.NumberHandling = jsonParameterInfo?.NumberHandling; return jsonParameterInfo != null; } } internal sealed class LargeObjectWithParameterizedConstructorConverter : ObjectWithParameterizedConstructorConverter { protected override bool ReadAndCacheConstructorArgument(ref ReadStack state, ref Utf8JsonReader reader, JsonParameterInfo jsonParameterInfo) { object value; bool flag = jsonParameterInfo.ConverterBase.TryReadAsObject(ref reader, jsonParameterInfo.Options, ref state, out value); if (flag && (value != null || !jsonParameterInfo.IgnoreDefaultValuesOnRead)) { ((object[])state.Current.CtorArgumentState.Arguments)[jsonParameterInfo.Position] = value; } return flag; } protected override object CreateObject(ref ReadStackFrame frame) { object[] array = (object[])frame.CtorArgumentState.Arguments; JsonClassInfo.ParameterizedConstructorDelegate parameterizedConstructorDelegate = (JsonClassInfo.ParameterizedConstructorDelegate)frame.JsonClassInfo.CreateObjectWithArgs; if (parameterizedConstructorDelegate == null) { ThrowHelper.ThrowNotSupportedException_ConstructorMaxOf64Parameters(base.ConstructorInfo, TypeToConvert); } object result = parameterizedConstructorDelegate(array); ArrayPool.Shared.Return(array, clearArray: true); return result; } protected override void InitializeConstructorArgumentCaches(ref ReadStack state, JsonSerializerOptions options) { JsonClassInfo jsonClassInfo = state.Current.JsonClassInfo; if (jsonClassInfo.CreateObjectWithArgs == null) { jsonClassInfo.CreateObjectWithArgs = options.MemberAccessorStrategy.CreateParameterizedConstructor(base.ConstructorInfo); } object[] array = ArrayPool.Shared.Rent(jsonClassInfo.ParameterCount); foreach (JsonParameterInfo value in jsonClassInfo.ParameterCache.Values) { if (value.ShouldDeserialize) { array[value.Position] = value.DefaultValue; } } state.Current.CtorArgumentState.Arguments = array; } } internal class SmallObjectWithParameterizedConstructorConverter : ObjectWithParameterizedConstructorConverter { protected override object CreateObject(ref ReadStackFrame frame) { JsonClassInfo.ParameterizedConstructorDelegate parameterizedConstructorDelegate = (JsonClassInfo.ParameterizedConstructorDelegate)frame.JsonClassInfo.CreateObjectWithArgs; Arguments arguments = (Arguments)frame.CtorArgumentState.Arguments; return parameterizedConstructorDelegate(arguments.Arg0, arguments.Arg1, arguments.Arg2, arguments.Arg3); } protected override bool ReadAndCacheConstructorArgument(ref ReadStack state, ref Utf8JsonReader reader, JsonParameterInfo jsonParameterInfo) { Arguments arguments = (Arguments)state.Current.CtorArgumentState.Arguments; return jsonParameterInfo.Position switch { 0 => TryRead(ref state, ref reader, jsonParameterInfo, out arguments.Arg0), 1 => TryRead(ref state, ref reader, jsonParameterInfo, out arguments.Arg1), 2 => TryRead(ref state, ref reader, jsonParameterInfo, out arguments.Arg2), 3 => TryRead(ref state, ref reader, jsonParameterInfo, out arguments.Arg3), _ => throw new InvalidOperationException(), }; } private bool TryRead(ref ReadStack state, ref Utf8JsonReader reader, JsonParameterInfo jsonParameterInfo, out TArg arg) { JsonParameterInfo jsonParameterInfo2 = (JsonParameterInfo)jsonParameterInfo; JsonConverter jsonConverter = (JsonConverter)jsonParameterInfo.ConverterBase; TArg value; bool result = jsonConverter.TryRead(ref reader, jsonParameterInfo2.RuntimePropertyType, jsonParameterInfo2.Options, ref state, out value); arg = ((value == null && jsonParameterInfo.IgnoreDefaultValuesOnRead) ? ((TArg)jsonParameterInfo2.DefaultValue) : value); return result; } protected override void InitializeConstructorArgumentCaches(ref ReadStack state, JsonSerializerOptions options) { JsonClassInfo jsonClassInfo = state.Current.JsonClassInfo; if (jsonClassInfo.CreateObjectWithArgs == null) { jsonClassInfo.CreateObjectWithArgs = options.MemberAccessorStrategy.CreateParameterizedConstructor(base.ConstructorInfo); } Arguments arguments = new Arguments(); foreach (JsonParameterInfo value in jsonClassInfo.ParameterCache.Values) { if (value.ShouldDeserialize) { switch (value.Position) { case 0: arguments.Arg0 = ((JsonParameterInfo)value).TypedDefaultValue; break; case 1: arguments.Arg1 = ((JsonParameterInfo)value).TypedDefaultValue; break; case 2: arguments.Arg2 = ((JsonParameterInfo)value).TypedDefaultValue; break; case 3: arguments.Arg3 = ((JsonParameterInfo)value).TypedDefaultValue; break; default: throw new InvalidOperationException(); } } } state.Current.CtorArgumentState.Arguments = arguments; } } internal sealed class BooleanConverter : JsonConverter { public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetBoolean(); } public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options) { writer.WriteBooleanValue(value); } internal override bool ReadWithQuotes(ref Utf8JsonReader reader) { ReadOnlySpan span = reader.GetSpan(); if (Utf8Parser.TryParse(span, out bool value, out int bytesConsumed, '\0') && span.Length == bytesConsumed) { return value; } throw ThrowHelper.GetFormatException(DataType.Boolean); } internal override void WriteWithQuotes(Utf8JsonWriter writer, bool value, JsonSerializerOptions options, ref WriteStack state) { writer.WritePropertyName(value); } } internal sealed class ByteArrayConverter : JsonConverter { public override byte[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetBytesFromBase64(); } public override void Write(Utf8JsonWriter writer, byte[] value, JsonSerializerOptions options) { writer.WriteBase64StringValue(value); } } internal sealed class ByteConverter : JsonConverter { public ByteConverter() { IsInternalConverterForNumberType = true; } public override byte Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetByte(); } public override void Write(Utf8JsonWriter writer, byte value, JsonSerializerOptions options) { writer.WriteNumberValue(value); } internal override byte ReadWithQuotes(ref Utf8JsonReader reader) { return reader.GetByteWithQuotes(); } internal override void WriteWithQuotes(Utf8JsonWriter writer, byte value, JsonSerializerOptions options, ref WriteStack state) { writer.WritePropertyName(value); } internal override byte ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling) { if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != 0) { return reader.GetByteWithQuotes(); } return reader.GetByte(); } internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, byte value, JsonNumberHandling handling) { if ((JsonNumberHandling.WriteAsString & handling) != 0) { writer.WriteNumberValueAsString(value); } else { writer.WriteNumberValue(value); } } } internal sealed class CharConverter : JsonConverter { public override char Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { string @string = reader.GetString(); if (string.IsNullOrEmpty(@string) || @string.Length > 1) { throw ThrowHelper.GetInvalidOperationException_ExpectedChar(reader.TokenType); } return @string[0]; } public override void Write(Utf8JsonWriter writer, char value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString()); } internal override char ReadWithQuotes(ref Utf8JsonReader reader) { return Read(ref reader, null, null); } internal override void WriteWithQuotes(Utf8JsonWriter writer, char value, JsonSerializerOptions options, ref WriteStack state) { writer.WritePropertyName(value.ToString()); } } internal sealed class DateTimeConverter : JsonConverter { public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetDateTime(); } public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { writer.WriteStringValue(value); } internal override DateTime ReadWithQuotes(ref Utf8JsonReader reader) { return reader.GetDateTimeNoValidation(); } internal override void WriteWithQuotes(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options, ref WriteStack state) { writer.WritePropertyName(value); } } internal sealed class DateTimeOffsetConverter : JsonConverter { public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetDateTimeOffset(); } public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options) { writer.WriteStringValue(value); } internal override DateTimeOffset ReadWithQuotes(ref Utf8JsonReader reader) { return reader.GetDateTimeOffsetNoValidation(); } internal override void WriteWithQuotes(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options, ref WriteStack state) { writer.WritePropertyName(value); } } internal sealed class DecimalConverter : JsonConverter { public DecimalConverter() { IsInternalConverterForNumberType = true; } public override decimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetDecimal(); } public override void Write(Utf8JsonWriter writer, decimal value, JsonSerializerOptions options) { writer.WriteNumberValue(value); } internal override decimal ReadWithQuotes(ref Utf8JsonReader reader) { return reader.GetDecimalWithQuotes(); } internal override void WriteWithQuotes(Utf8JsonWriter writer, decimal value, JsonSerializerOptions options, ref WriteStack state) { writer.WritePropertyName(value); } internal override decimal ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling) { if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != 0) { return reader.GetDecimalWithQuotes(); } return reader.GetDecimal(); } internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, decimal value, JsonNumberHandling handling) { if ((JsonNumberHandling.WriteAsString & handling) != 0) { writer.WriteNumberValueAsString(value); } else { writer.WriteNumberValue(value); } } } internal sealed class DoubleConverter : JsonConverter { public DoubleConverter() { IsInternalConverterForNumberType = true; } public override double Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetDouble(); } public override void Write(Utf8JsonWriter writer, double value, JsonSerializerOptions options) { writer.WriteNumberValue(value); } internal override double ReadWithQuotes(ref Utf8JsonReader reader) { return reader.GetDoubleWithQuotes(); } internal override void WriteWithQuotes(Utf8JsonWriter writer, double value, JsonSerializerOptions options, ref WriteStack state) { writer.WritePropertyName(value); } internal override double ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling) { if (reader.TokenType == JsonTokenType.String) { if ((JsonNumberHandling.AllowReadingFromString & handling) != 0) { return reader.GetDoubleWithQuotes(); } if ((JsonNumberHandling.AllowNamedFloatingPointLiterals & handling) != 0) { return reader.GetDoubleFloatingPointConstant(); } } return reader.GetDouble(); } internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, double value, JsonNumberHandling handling) { if ((JsonNumberHandling.WriteAsString & handling) != 0) { writer.WriteNumberValueAsString(value); } else if ((JsonNumberHandling.AllowNamedFloatingPointLiterals & handling) != 0) { writer.WriteFloatingPointConstant(value); } else { writer.WriteNumberValue(value); } } } internal class EnumConverter : JsonConverter where T : struct, Enum { private static readonly TypeCode s_enumTypeCode = Type.GetTypeCode(typeof(T)); private static readonly string s_negativeSign = (((int)s_enumTypeCode % 2 == 0) ? null : NumberFormatInfo.CurrentInfo.NegativeSign); private const string ValueSeparator = ", "; private readonly EnumConverterOptions _converterOptions; private readonly JsonNamingPolicy _namingPolicy; private readonly ConcurrentDictionary _nameCache; private const int NameCacheSizeSoftLimit = 64; public override bool CanConvert(Type type) { return type.IsEnum; } public EnumConverter(EnumConverterOptions converterOptions, JsonSerializerOptions serializerOptions) : this(converterOptions, (JsonNamingPolicy)null, serializerOptions) { } public EnumConverter(EnumConverterOptions converterOptions, JsonNamingPolicy namingPolicy, JsonSerializerOptions serializerOptions) { _converterOptions = converterOptions; _namingPolicy = namingPolicy; _nameCache = new ConcurrentDictionary(); string[] names = Enum.GetNames(TypeToConvert); Array values = Enum.GetValues(TypeToConvert); JavaScriptEncoder encoder = serializerOptions.Encoder; for (int i = 0; i < names.Length; i++) { if (_nameCache.Count >= 64) { break; } T val = (T)values.GetValue(i); ulong key = ConvertToUInt64(val); string value = names[i]; _nameCache.TryAdd(key, (namingPolicy == null) ? JsonEncodedText.Encode(value, encoder) : FormatEnumValue(value, encoder)); } } public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { switch (reader.TokenType) { case JsonTokenType.String: if (!_converterOptions.HasFlag(EnumConverterOptions.AllowStrings)) { ThrowHelper.ThrowJsonException(); return default(T); } return ReadWithQuotes(ref reader); case JsonTokenType.Number: if (_converterOptions.HasFlag(EnumConverterOptions.AllowNumbers)) { switch (s_enumTypeCode) { case TypeCode.Int32: { if (reader.TryGetInt32(out var value6)) { return Unsafe.As(ref value6); } break; } case TypeCode.UInt32: { if (reader.TryGetUInt32(out var value2)) { return Unsafe.As(ref value2); } break; } case TypeCode.UInt64: { if (reader.TryGetUInt64(out var value5)) { return Unsafe.As(ref value5); } break; } case TypeCode.Int64: { if (reader.TryGetInt64(out var value8)) { return Unsafe.As(ref value8); } break; } case TypeCode.SByte: { if (reader.TryGetInt32(out var value3) && JsonHelpers.IsInRangeInclusive(value3, -128, 127)) { sbyte source2 = (sbyte)value3; return Unsafe.As(ref source2); } break; } case TypeCode.Byte: { if (reader.TryGetUInt32(out var value7) && JsonHelpers.IsInRangeInclusive(value7, 0u, 255u)) { byte source4 = (byte)value7; return Unsafe.As(ref source4); } break; } case TypeCode.Int16: { if (reader.TryGetInt32(out var value4) && JsonHelpers.IsInRangeInclusive(value4, -32768, 32767)) { short source3 = (short)value4; return Unsafe.As(ref source3); } break; } case TypeCode.UInt16: { if (reader.TryGetUInt32(out var value) && JsonHelpers.IsInRangeInclusive(value, 0u, 65535u)) { ushort source = (ushort)value; return Unsafe.As(ref source); } break; } } ThrowHelper.ThrowJsonException(); return default(T); } goto default; default: ThrowHelper.ThrowJsonException(); return default(T); } } public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { if (_converterOptions.HasFlag(EnumConverterOptions.AllowStrings)) { ulong key = ConvertToUInt64(value); if (_nameCache.TryGetValue(key, out var value2)) { writer.WriteStringValue(value2); return; } string text = value.ToString(); if (IsValidIdentifier(text)) { JavaScriptEncoder encoder = options.Encoder; if (_nameCache.Count < 64) { value2 = ((_namingPolicy == null) ? JsonEncodedText.Encode(text, encoder) : FormatEnumValue(text, encoder)); writer.WriteStringValue(value2); _nameCache.TryAdd(key, value2); } else { writer.WriteStringValue((_namingPolicy == null) ? text : FormatEnumValueToString(text, encoder)); } return; } } if (!_converterOptions.HasFlag(EnumConverterOptions.AllowNumbers)) { ThrowHelper.ThrowJsonException(); } switch (s_enumTypeCode) { case TypeCode.Int32: writer.WriteNumberValue(Unsafe.As(ref value)); break; case TypeCode.UInt32: writer.WriteNumberValue(Unsafe.As(ref value)); break; case TypeCode.UInt64: writer.WriteNumberValue(Unsafe.As(ref value)); break; case TypeCode.Int64: writer.WriteNumberValue(Unsafe.As(ref value)); break; case TypeCode.Int16: writer.WriteNumberValue(Unsafe.As(ref value)); break; case TypeCode.UInt16: writer.WriteNumberValue(Unsafe.As(ref value)); break; case TypeCode.Byte: writer.WriteNumberValue(Unsafe.As(ref value)); break; case TypeCode.SByte: writer.WriteNumberValue(Unsafe.As(ref value)); break; default: ThrowHelper.ThrowJsonException(); break; } } private static ulong ConvertToUInt64(object value) { return s_enumTypeCode switch { TypeCode.Int32 => (ulong)(int)value, TypeCode.UInt32 => (uint)value, TypeCode.UInt64 => (ulong)value, TypeCode.Int64 => (ulong)(long)value, TypeCode.SByte => (ulong)(sbyte)value, TypeCode.Byte => (byte)value, TypeCode.Int16 => (ulong)(short)value, TypeCode.UInt16 => (ushort)value, _ => throw new InvalidOperationException(), }; } private static bool IsValidIdentifier(string value) { if (value[0] >= 'A') { if (s_negativeSign != null) { return !value.StartsWith(s_negativeSign); } return true; } return false; } private JsonEncodedText FormatEnumValue(string value, JavaScriptEncoder encoder) { string value2 = FormatEnumValueToString(value, encoder); return JsonEncodedText.Encode(value2, encoder); } private string FormatEnumValueToString(string value, JavaScriptEncoder encoder) { if (!value.Contains(", ")) { return _namingPolicy.ConvertName(value); } string[] array = value.Split(new string[1] { ", " }, StringSplitOptions.None); for (int i = 0; i < array.Length; i++) { array[i] = _namingPolicy.ConvertName(array[i]); } return string.Join(", ", array); } internal override T ReadWithQuotes(ref Utf8JsonReader reader) { string @string = reader.GetString(); if (!Enum.TryParse(@string, out var result) && !Enum.TryParse(@string, ignoreCase: true, out result)) { ThrowHelper.ThrowJsonException(); } return result; } internal override void WriteWithQuotes(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state) { ulong key = ConvertToUInt64(value); if (_nameCache.TryGetValue(key, out var value2)) { writer.WritePropertyName(value2); return; } string text = value.ToString(); if (IsValidIdentifier(text)) { JavaScriptEncoder encoder = options.Encoder; if (_nameCache.Count < 64) { value2 = JsonEncodedText.Encode(text, encoder); writer.WritePropertyName(value2); _nameCache.TryAdd(key, value2); } else { writer.WritePropertyName(text); } return; } switch (s_enumTypeCode) { case TypeCode.Int32: writer.WritePropertyName(Unsafe.As(ref value)); break; case TypeCode.UInt32: writer.WritePropertyName(Unsafe.As(ref value)); break; case TypeCode.UInt64: writer.WritePropertyName(Unsafe.As(ref value)); break; case TypeCode.Int64: writer.WritePropertyName(Unsafe.As(ref value)); break; case TypeCode.Int16: writer.WritePropertyName(Unsafe.As(ref value)); break; case TypeCode.UInt16: writer.WritePropertyName(Unsafe.As(ref value)); break; case TypeCode.Byte: writer.WritePropertyName(Unsafe.As(ref value)); break; case TypeCode.SByte: writer.WritePropertyName(Unsafe.As(ref value)); break; default: ThrowHelper.ThrowJsonException(); break; } } } internal sealed class EnumConverterFactory : JsonConverterFactory { public override bool CanConvert(Type type) { return type.IsEnum; } public override JsonConverter CreateConverter(Type type, JsonSerializerOptions options) { return (JsonConverter)Activator.CreateInstance(typeof(EnumConverter<>).MakeGenericType(type), BindingFlags.Instance | BindingFlags.Public, null, new object[2] { EnumConverterOptions.AllowNumbers, options }, null); } } [Flags] internal enum EnumConverterOptions { AllowStrings = 1, AllowNumbers = 2 } internal sealed class GuidConverter : JsonConverter { public override Guid Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetGuid(); } public override void Write(Utf8JsonWriter writer, Guid value, JsonSerializerOptions options) { writer.WriteStringValue(value); } internal override Guid ReadWithQuotes(ref Utf8JsonReader reader) { return reader.GetGuidNoValidation(); } internal override void WriteWithQuotes(Utf8JsonWriter writer, Guid value, JsonSerializerOptions options, ref WriteStack state) { writer.WritePropertyName(value); } } internal sealed class Int16Converter : JsonConverter { public Int16Converter() { IsInternalConverterForNumberType = true; } public override short Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetInt16(); } public override void Write(Utf8JsonWriter writer, short value, JsonSerializerOptions options) { writer.WriteNumberValue((long)value); } internal override short ReadWithQuotes(ref Utf8JsonReader reader) { return reader.GetInt16WithQuotes(); } internal override void WriteWithQuotes(Utf8JsonWriter writer, short value, JsonSerializerOptions options, ref WriteStack state) { writer.WritePropertyName(value); } internal override short ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling) { if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != 0) { return reader.GetInt16WithQuotes(); } return reader.GetInt16(); } internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, short value, JsonNumberHandling handling) { if ((JsonNumberHandling.WriteAsString & handling) != 0) { writer.WriteNumberValueAsString(value); } else { writer.WriteNumberValue((long)value); } } } internal sealed class Int32Converter : JsonConverter { public Int32Converter() { IsInternalConverterForNumberType = true; } public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetInt32(); } public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options) { writer.WriteNumberValue((long)value); } internal override int ReadWithQuotes(ref Utf8JsonReader reader) { return reader.GetInt32WithQuotes(); } internal override void WriteWithQuotes(Utf8JsonWriter writer, int value, JsonSerializerOptions options, ref WriteStack state) { writer.WritePropertyName(value); } internal override int ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling) { if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != 0) { return reader.GetInt32WithQuotes(); } return reader.GetInt32(); } internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, int value, JsonNumberHandling handling) { if ((JsonNumberHandling.WriteAsString & handling) != 0) { writer.WriteNumberValueAsString(value); } else { writer.WriteNumberValue((long)value); } } } internal sealed class Int64Converter : JsonConverter { public Int64Converter() { IsInternalConverterForNumberType = true; } public override long Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetInt64(); } public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options) { writer.WriteNumberValue(value); } internal override long ReadWithQuotes(ref Utf8JsonReader reader) { return reader.GetInt64WithQuotes(); } internal override void WriteWithQuotes(Utf8JsonWriter writer, long value, JsonSerializerOptions options, ref WriteStack state) { writer.WritePropertyName(value); } internal override long ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling) { if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != 0) { return reader.GetInt64WithQuotes(); } return reader.GetInt64(); } internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, long value, JsonNumberHandling handling) { if ((JsonNumberHandling.WriteAsString & handling) != 0) { writer.WriteNumberValueAsString(value); } else { writer.WriteNumberValue(value); } } } internal sealed class JsonDocumentConverter : JsonConverter { public override JsonDocument Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return JsonDocument.ParseValue(ref reader); } public override void Write(Utf8JsonWriter writer, JsonDocument value, JsonSerializerOptions options) { value.WriteTo(writer); } } internal sealed class JsonElementConverter : JsonConverter { public override JsonElement Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader); return jsonDocument.RootElement.Clone(); } public override void Write(Utf8JsonWriter writer, JsonElement value, JsonSerializerOptions options) { value.WriteTo(writer); } } internal class NullableConverter : JsonConverter where T : struct { private readonly JsonConverter _converter; public NullableConverter(JsonConverter converter) { _converter = converter; IsInternalConverterForNumberType = converter.IsInternalConverterForNumberType; } public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) { return null; } return _converter.Read(ref reader, typeof(T), options); } public override void Write(Utf8JsonWriter writer, T? value, JsonSerializerOptions options) { if (!value.HasValue) { writer.WriteNullValue(); } else { _converter.Write(writer, value.Value, options); } } internal override T? ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling numberHandling) { if (reader.TokenType == JsonTokenType.Null) { return null; } return _converter.ReadNumberWithCustomHandling(ref reader, numberHandling); } internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, T? value, JsonNumberHandling handling) { if (!value.HasValue) { writer.WriteNullValue(); } else { _converter.WriteNumberWithCustomHandling(writer, value.Value, handling); } } } internal class NullableConverterFactory : JsonConverterFactory { public override bool CanConvert(Type typeToConvert) { return Nullable.GetUnderlyingType(typeToConvert) != null; } public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { Type type = typeToConvert.GetGenericArguments()[0]; JsonConverter converter = options.GetConverter(type); if (!converter.TypeToConvert.IsValueType && type.IsValueType) { return converter; } return CreateValueConverter(type, converter); } public static JsonConverter CreateValueConverter(Type valueTypeToConvert, JsonConverter valueConverter) { return (JsonConverter)Activator.CreateInstance(typeof(NullableConverter<>).MakeGenericType(valueTypeToConvert), BindingFlags.Instance | BindingFlags.Public, null, new object[1] { valueConverter }, null); } } internal sealed class ObjectConverter : JsonConverter { public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader); return jsonDocument.RootElement.Clone(); } public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options) { throw new InvalidOperationException(); } internal override object ReadWithQuotes(ref Utf8JsonReader reader) { ThrowHelper.ThrowNotSupportedException_DictionaryKeyTypeNotSupported(TypeToConvert); return null; } internal override void WriteWithQuotes(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state) { JsonConverter runtimeConverter = GetRuntimeConverter(value.GetType(), options); runtimeConverter.WriteWithQuotesAsObject(writer, value, options, ref state); } private JsonConverter GetRuntimeConverter(Type runtimeType, JsonSerializerOptions options) { JsonConverter dictionaryKeyConverter = options.GetDictionaryKeyConverter(runtimeType); if (dictionaryKeyConverter == this) { ThrowHelper.ThrowNotSupportedException_DictionaryKeyTypeNotSupported(runtimeType); } return dictionaryKeyConverter; } } internal sealed class SByteConverter : JsonConverter { public SByteConverter() { IsInternalConverterForNumberType = true; } public override sbyte Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetSByte(); } public override void Write(Utf8JsonWriter writer, sbyte value, JsonSerializerOptions options) { writer.WriteNumberValue(value); } internal override sbyte ReadWithQuotes(ref Utf8JsonReader reader) { return reader.GetSByteWithQuotes(); } internal override void WriteWithQuotes(Utf8JsonWriter writer, sbyte value, JsonSerializerOptions options, ref WriteStack state) { writer.WritePropertyName(value); } internal override sbyte ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling) { if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != 0) { return reader.GetSByteWithQuotes(); } return reader.GetSByte(); } internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, sbyte value, JsonNumberHandling handling) { if ((JsonNumberHandling.WriteAsString & handling) != 0) { writer.WriteNumberValueAsString(value); } else { writer.WriteNumberValue(value); } } } internal sealed class SingleConverter : JsonConverter { public SingleConverter() { IsInternalConverterForNumberType = true; } public override float Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetSingle(); } public override void Write(Utf8JsonWriter writer, float value, JsonSerializerOptions options) { writer.WriteNumberValue(value); } internal override float ReadWithQuotes(ref Utf8JsonReader reader) { return reader.GetSingleWithQuotes(); } internal override void WriteWithQuotes(Utf8JsonWriter writer, float value, JsonSerializerOptions options, ref WriteStack state) { writer.WritePropertyName(value); } internal override float ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling) { if (reader.TokenType == JsonTokenType.String) { if ((JsonNumberHandling.AllowReadingFromString & handling) != 0) { return reader.GetSingleWithQuotes(); } if ((JsonNumberHandling.AllowNamedFloatingPointLiterals & handling) != 0) { return reader.GetSingleFloatingPointConstant(); } } return reader.GetSingle(); } internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, float value, JsonNumberHandling handling) { if ((JsonNumberHandling.WriteAsString & handling) != 0) { writer.WriteNumberValueAsString(value); } else if ((JsonNumberHandling.AllowNamedFloatingPointLiterals & handling) != 0) { writer.WriteFloatingPointConstant(value); } else { writer.WriteNumberValue(value); } } } internal sealed class StringConverter : JsonConverter { public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetString(); } public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) { if (value == null) { writer.WriteNullValue(); } else { writer.WriteStringValue(MemoryExtensions.AsSpan(value)); } } internal override string ReadWithQuotes(ref Utf8JsonReader reader) { return reader.GetString(); } internal override void WriteWithQuotes(Utf8JsonWriter writer, string value, JsonSerializerOptions options, ref WriteStack state) { if (options.DictionaryKeyPolicy != null && !state.Current.IgnoreDictionaryKeyPolicy) { value = options.DictionaryKeyPolicy.ConvertName(value); if (value == null) { ThrowHelper.ThrowInvalidOperationException_NamingPolicyReturnNull(options.DictionaryKeyPolicy); } } writer.WritePropertyName(value); } } internal sealed class TypeConverter : JsonConverter { public override Type Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { throw new NotSupportedException(System.SR.SerializeTypeInstanceNotSupported); } public override void Write(Utf8JsonWriter writer, Type value, JsonSerializerOptions options) { throw new NotSupportedException(System.SR.SerializeTypeInstanceNotSupported); } } internal sealed class UInt16Converter : JsonConverter { public UInt16Converter() { IsInternalConverterForNumberType = true; } public override ushort Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetUInt16(); } public override void Write(Utf8JsonWriter writer, ushort value, JsonSerializerOptions options) { writer.WriteNumberValue((long)value); } internal override ushort ReadWithQuotes(ref Utf8JsonReader reader) { return reader.GetUInt16WithQuotes(); } internal override void WriteWithQuotes(Utf8JsonWriter writer, ushort value, JsonSerializerOptions options, ref WriteStack state) { writer.WritePropertyName(value); } internal override ushort ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling) { if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != 0) { return reader.GetUInt16WithQuotes(); } return reader.GetUInt16(); } internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, ushort value, JsonNumberHandling handling) { if ((JsonNumberHandling.WriteAsString & handling) != 0) { writer.WriteNumberValueAsString(value); } else { writer.WriteNumberValue((long)value); } } } internal sealed class UInt32Converter : JsonConverter { public UInt32Converter() { IsInternalConverterForNumberType = true; } public override uint Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetUInt32(); } public override void Write(Utf8JsonWriter writer, uint value, JsonSerializerOptions options) { writer.WriteNumberValue((ulong)value); } internal override uint ReadWithQuotes(ref Utf8JsonReader reader) { return reader.GetUInt32WithQuotes(); } internal override void WriteWithQuotes(Utf8JsonWriter writer, uint value, JsonSerializerOptions options, ref WriteStack state) { writer.WritePropertyName(value); } internal override uint ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling) { if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != 0) { return reader.GetUInt32WithQuotes(); } return reader.GetUInt32(); } internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, uint value, JsonNumberHandling handling) { if ((JsonNumberHandling.WriteAsString & handling) != 0) { writer.WriteNumberValueAsString(value); } else { writer.WriteNumberValue((ulong)value); } } } internal sealed class UInt64Converter : JsonConverter { public UInt64Converter() { IsInternalConverterForNumberType = true; } public override ulong Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetUInt64(); } public override void Write(Utf8JsonWriter writer, ulong value, JsonSerializerOptions options) { writer.WriteNumberValue(value); } internal override ulong ReadWithQuotes(ref Utf8JsonReader reader) { return reader.GetUInt64WithQuotes(); } internal override void WriteWithQuotes(Utf8JsonWriter writer, ulong value, JsonSerializerOptions options, ref WriteStack state) { writer.WritePropertyName(value); } internal override ulong ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling) { if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != 0) { return reader.GetUInt64WithQuotes(); } return reader.GetUInt64(); } internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, ulong value, JsonNumberHandling handling) { if ((JsonNumberHandling.WriteAsString & handling) != 0) { writer.WriteNumberValueAsString(value); } else { writer.WriteNumberValue(value); } } } internal sealed class UriConverter : JsonConverter { public override Uri Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { string @string = reader.GetString(); if (Uri.TryCreate(@string, UriKind.RelativeOrAbsolute, out Uri result)) { return result; } ThrowHelper.ThrowJsonException(); return null; } public override void Write(Utf8JsonWriter writer, Uri value, JsonSerializerOptions options) { writer.WriteStringValue(value.OriginalString); } } } namespace System { internal static class ThrowHelper { internal static void ThrowArgumentNullException(System.ExceptionArgument argument) { throw GetArgumentNullException(argument); } internal static void ThrowArgumentOutOfRangeException(System.ExceptionArgument argument) { throw GetArgumentOutOfRangeException(argument); } private static ArgumentNullException GetArgumentNullException(System.ExceptionArgument argument) { return new ArgumentNullException(GetArgumentName(argument)); } private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(System.ExceptionArgument argument) { return new ArgumentOutOfRangeException(GetArgumentName(argument)); } [MethodImpl(MethodImplOptions.NoInlining)] private static string GetArgumentName(System.ExceptionArgument argument) { return argument.ToString(); } } internal enum ExceptionArgument { task, source, state } } namespace System.Threading.Tasks { [StructLayout(LayoutKind.Auto)] [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder))] internal readonly struct ValueTask : IEquatable { private sealed class ValueTaskSourceAsTask : TaskCompletionSource { private static readonly Action s_completionAction = delegate(object state) { IValueTaskSource source; if (!(state is ValueTaskSourceAsTask valueTaskSourceAsTask) || (source = valueTaskSourceAsTask._source) == null) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.state); return; } valueTaskSourceAsTask._source = null; ValueTaskSourceStatus status = source.GetStatus(valueTaskSourceAsTask._token); try { source.GetResult(valueTaskSourceAsTask._token); valueTaskSourceAsTask.TrySetResult(result: false); } catch (Exception exception) { if (status == ValueTaskSourceStatus.Canceled) { valueTaskSourceAsTask.TrySetCanceled(); } else { valueTaskSourceAsTask.TrySetException(exception); } } }; private IValueTaskSource _source; private readonly short _token; public ValueTaskSourceAsTask(IValueTaskSource source, short token) { _token = token; _source = source; source.OnCompleted(s_completionAction, this, token, ValueTaskSourceOnCompletedFlags.None); } } private static readonly Task s_canceledTask = Task.Delay(-1, new CancellationToken(canceled: true)); internal readonly object _obj; internal readonly short _token; internal readonly bool _continueOnCapturedContext; internal static Task CompletedTask { get; } = Task.Delay(0); public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { object obj = _obj; if (obj == null) { return true; } if (obj is Task task) { return task.IsCompleted; } return Unsafe.As(obj).GetStatus(_token) != ValueTaskSourceStatus.Pending; } } public bool IsCompletedSuccessfully { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { object obj = _obj; if (obj == null) { return true; } if (obj is Task task) { return task.Status == TaskStatus.RanToCompletion; } return Unsafe.As(obj).GetStatus(_token) == ValueTaskSourceStatus.Succeeded; } } public bool IsFaulted { get { object obj = _obj; if (obj == null) { return false; } if (obj is Task task) { return task.IsFaulted; } return Unsafe.As(obj).GetStatus(_token) == ValueTaskSourceStatus.Faulted; } } public bool IsCanceled { get { object obj = _obj; if (obj == null) { return false; } if (obj is Task task) { return task.IsCanceled; } return Unsafe.As(obj).GetStatus(_token) == ValueTaskSourceStatus.Canceled; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(Task task) { if (task == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.task); } _obj = task; _continueOnCapturedContext = true; _token = 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(IValueTaskSource source, short token) { if (source == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.source); } _obj = source; _token = token; _continueOnCapturedContext = true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ValueTask(object obj, short token, bool continueOnCapturedContext) { _obj = obj; _token = token; _continueOnCapturedContext = continueOnCapturedContext; } public override int GetHashCode() { return _obj?.GetHashCode() ?? 0; } public override bool Equals(object obj) { if (obj is ValueTask) { return Equals((ValueTask)obj); } return false; } public bool Equals(ValueTask other) { if (_obj == other._obj) { return _token == other._token; } return false; } public static bool operator ==(ValueTask left, ValueTask right) { return left.Equals(right); } public static bool operator !=(ValueTask left, ValueTask right) { return !left.Equals(right); } public Task AsTask() { object obj = _obj; object obj2; if (obj != null) { obj2 = obj as Task; if (obj2 == null) { return GetTaskForValueTaskSource(Unsafe.As(obj)); } } else { obj2 = CompletedTask; } return (Task)obj2; } public ValueTask Preserve() { if (_obj != null) { return new ValueTask(AsTask()); } return this; } private Task GetTaskForValueTaskSource(IValueTaskSource t) { ValueTaskSourceStatus status = t.GetStatus(_token); if (status != 0) { try { t.GetResult(_token); return CompletedTask; } catch (Exception exception) { if (status == ValueTaskSourceStatus.Canceled) { return s_canceledTask; } TaskCompletionSource taskCompletionSource = new TaskCompletionSource(); taskCompletionSource.TrySetException(exception); return taskCompletionSource.Task; } } ValueTaskSourceAsTask valueTaskSourceAsTask = new ValueTaskSourceAsTask(t, _token); return valueTaskSourceAsTask.Task; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [StackTraceHidden] internal void ThrowIfCompletedUnsuccessfully() { object obj = _obj; if (obj != null) { if (obj is Task task) { task.GetAwaiter().GetResult(); } else { Unsafe.As(obj).GetResult(_token); } } } public ValueTaskAwaiter GetAwaiter() { return new ValueTaskAwaiter(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) { return new ConfiguredValueTaskAwaitable(new ValueTask(_obj, _token, continueOnCapturedContext)); } } [StructLayout(LayoutKind.Auto)] [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder<>))] internal readonly struct ValueTask : IEquatable> { private sealed class ValueTaskSourceAsTask : TaskCompletionSource { private static readonly Action s_completionAction = delegate(object state) { IValueTaskSource source; if (!(state is ValueTaskSourceAsTask valueTaskSourceAsTask) || (source = valueTaskSourceAsTask._source) == null) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.state); return; } valueTaskSourceAsTask._source = null; ValueTaskSourceStatus status = source.GetStatus(valueTaskSourceAsTask._token); try { valueTaskSourceAsTask.TrySetResult(source.GetResult(valueTaskSourceAsTask._token)); } catch (Exception exception) { if (status == ValueTaskSourceStatus.Canceled) { valueTaskSourceAsTask.TrySetCanceled(); } else { valueTaskSourceAsTask.TrySetException(exception); } } }; private IValueTaskSource _source; private readonly short _token; public ValueTaskSourceAsTask(IValueTaskSource source, short token) { _source = source; _token = token; source.OnCompleted(s_completionAction, this, token, ValueTaskSourceOnCompletedFlags.None); } } private static Task s_canceledTask; internal readonly object _obj; internal readonly TResult _result; internal readonly short _token; internal readonly bool _continueOnCapturedContext; public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { object obj = _obj; if (obj == null) { return true; } if (obj is Task task) { return task.IsCompleted; } return Unsafe.As>(obj).GetStatus(_token) != ValueTaskSourceStatus.Pending; } } public bool IsCompletedSuccessfully { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { object obj = _obj; if (obj == null) { return true; } if (obj is Task task) { return task.Status == TaskStatus.RanToCompletion; } return Unsafe.As>(obj).GetStatus(_token) == ValueTaskSourceStatus.Succeeded; } } public bool IsFaulted { get { object obj = _obj; if (obj == null) { return false; } if (obj is Task task) { return task.IsFaulted; } return Unsafe.As>(obj).GetStatus(_token) == ValueTaskSourceStatus.Faulted; } } public bool IsCanceled { get { object obj = _obj; if (obj == null) { return false; } if (obj is Task task) { return task.IsCanceled; } return Unsafe.As>(obj).GetStatus(_token) == ValueTaskSourceStatus.Canceled; } } public TResult Result { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { object obj = _obj; if (obj == null) { return _result; } if (obj is Task task) { return task.GetAwaiter().GetResult(); } return Unsafe.As>(obj).GetResult(_token); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(TResult result) { _result = result; _obj = null; _continueOnCapturedContext = true; _token = 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(Task task) { if (task == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.task); } _obj = task; _result = default(TResult); _continueOnCapturedContext = true; _token = 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(IValueTaskSource source, short token) { if (source == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.source); } _obj = source; _token = token; _result = default(TResult); _continueOnCapturedContext = true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ValueTask(object obj, TResult result, short token, bool continueOnCapturedContext) { _obj = obj; _result = result; _token = token; _continueOnCapturedContext = continueOnCapturedContext; } public override int GetHashCode() { if (_obj == null) { if (_result == null) { return 0; } return _result.GetHashCode(); } return _obj.GetHashCode(); } public override bool Equals(object obj) { if (obj is ValueTask) { return Equals((ValueTask)obj); } return false; } public bool Equals(ValueTask other) { if (_obj == null && other._obj == null) { return EqualityComparer.Default.Equals(_result, other._result); } if (_obj == other._obj) { return _token == other._token; } return false; } public static bool operator ==(ValueTask left, ValueTask right) { return left.Equals(right); } public static bool operator !=(ValueTask left, ValueTask right) { return !left.Equals(right); } public Task AsTask() { object obj = _obj; if (obj == null) { return Task.FromResult(_result); } if (obj is Task result) { return result; } return GetTaskForValueTaskSource(Unsafe.As>(obj)); } public ValueTask Preserve() { if (_obj != null) { return new ValueTask(AsTask()); } return this; } private Task GetTaskForValueTaskSource(IValueTaskSource t) { ValueTaskSourceStatus status = t.GetStatus(_token); if (status != 0) { try { return Task.FromResult(t.GetResult(_token)); } catch (Exception exception) { if (status == ValueTaskSourceStatus.Canceled) { Task task = s_canceledTask; if (task == null) { TaskCompletionSource taskCompletionSource = new TaskCompletionSource(); taskCompletionSource.TrySetCanceled(); task = (s_canceledTask = taskCompletionSource.Task); } return task; } TaskCompletionSource taskCompletionSource2 = new TaskCompletionSource(); taskCompletionSource2.TrySetException(exception); return taskCompletionSource2.Task; } } ValueTaskSourceAsTask valueTaskSourceAsTask = new ValueTaskSourceAsTask(t, _token); return valueTaskSourceAsTask.Task; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTaskAwaiter GetAwaiter() { return new ValueTaskAwaiter(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) { return new ConfiguredValueTaskAwaitable(new ValueTask(_obj, _result, _token, continueOnCapturedContext)); } public override string ToString() { if (IsCompletedSuccessfully) { TResult result = Result; if (result != null) { return result.ToString(); } } return string.Empty; } } } namespace System.Threading.Tasks.Sources { [Flags] internal enum ValueTaskSourceOnCompletedFlags { None = 0, UseSchedulingContext = 1, FlowExecutionContext = 2 } internal enum ValueTaskSourceStatus { Pending, Succeeded, Faulted, Canceled } internal interface IValueTaskSource { ValueTaskSourceStatus GetStatus(short token); void OnCompleted(Action continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags); void GetResult(short token); } internal interface IValueTaskSource { ValueTaskSourceStatus GetStatus(short token); void OnCompleted(Action continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags); TResult GetResult(short token); } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false, AllowMultiple = false)] internal sealed class AsyncMethodBuilderAttribute : Attribute { public Type BuilderType { get; } public AsyncMethodBuilderAttribute(Type builderType) { BuilderType = builderType; } } [StructLayout(LayoutKind.Auto)] internal struct AsyncValueTaskMethodBuilder { private AsyncTaskMethodBuilder _methodBuilder; private bool _haveResult; private bool _useBuilder; public ValueTask Task { get { if (_haveResult) { return default(ValueTask); } _useBuilder = true; return new ValueTask(_methodBuilder.Task); } } public static AsyncValueTaskMethodBuilder Create() { return default(AsyncValueTaskMethodBuilder); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { _methodBuilder.Start(ref stateMachine); } public void SetStateMachine(IAsyncStateMachine stateMachine) { _methodBuilder.SetStateMachine(stateMachine); } public void SetResult() { if (_useBuilder) { _methodBuilder.SetResult(); } else { _haveResult = true; } } public void SetException(Exception exception) { _methodBuilder.SetException(exception); } public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { _useBuilder = true; _methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine); } [SecuritySafeCritical] public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { _useBuilder = true; _methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); } } [StructLayout(LayoutKind.Auto)] internal struct AsyncValueTaskMethodBuilder { private AsyncTaskMethodBuilder _methodBuilder; private TResult _result; private bool _haveResult; private bool _useBuilder; public ValueTask Task { get { if (_haveResult) { return new ValueTask(_result); } _useBuilder = true; return new ValueTask(_methodBuilder.Task); } } public static AsyncValueTaskMethodBuilder Create() { return default(AsyncValueTaskMethodBuilder); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { _methodBuilder.Start(ref stateMachine); } public void SetStateMachine(IAsyncStateMachine stateMachine) { _methodBuilder.SetStateMachine(stateMachine); } public void SetResult(TResult result) { if (_useBuilder) { _methodBuilder.SetResult(result); return; } _result = result; _haveResult = true; } public void SetException(Exception exception) { _methodBuilder.SetException(exception); } public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { _useBuilder = true; _methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine); } [SecuritySafeCritical] public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { _useBuilder = true; _methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); } } [StructLayout(LayoutKind.Auto)] internal readonly struct ConfiguredValueTaskAwaitable { [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion { private readonly ValueTask _value; public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _value.IsCompleted; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaiter(ValueTask value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [StackTraceHidden] public void GetResult() { _value.ThrowIfCompletedUnsuccessfully(); } public void OnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } else if (obj != null) { Unsafe.As(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.FlowExecutionContext | (_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None)); } else { ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } } public void UnsafeOnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } else if (obj != null) { Unsafe.As(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } } } private readonly ValueTask _value; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaitable(ValueTask value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ConfiguredValueTaskAwaiter GetAwaiter() { return new ConfiguredValueTaskAwaiter(_value); } } [StructLayout(LayoutKind.Auto)] internal readonly struct ConfiguredValueTaskAwaitable { [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion { private readonly ValueTask _value; public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _value.IsCompleted; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaiter(ValueTask value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [StackTraceHidden] public TResult GetResult() { return _value.Result; } public void OnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } else if (obj != null) { Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.FlowExecutionContext | (_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None)); } else { ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } } public void UnsafeOnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } else if (obj != null) { Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } } } private readonly ValueTask _value; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaitable(ValueTask value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ConfiguredValueTaskAwaiter GetAwaiter() { return new ConfiguredValueTaskAwaiter(_value); } } internal readonly struct ValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion { internal static readonly Action s_invokeActionDelegate = delegate(object state) { if (!(state is Action action)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.state); } else { action(); } }; private readonly ValueTask _value; public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _value.IsCompleted; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ValueTaskAwaiter(ValueTask value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [StackTraceHidden] public void GetResult() { _value.ThrowIfCompletedUnsuccessfully(); } public void OnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.GetAwaiter().OnCompleted(continuation); } else if (obj != null) { Unsafe.As(obj).OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext); } else { ValueTask.CompletedTask.GetAwaiter().OnCompleted(continuation); } } public void UnsafeOnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.GetAwaiter().UnsafeOnCompleted(continuation); } else if (obj != null) { Unsafe.As(obj).OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); } else { ValueTask.CompletedTask.GetAwaiter().UnsafeOnCompleted(continuation); } } } internal readonly struct ValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion { private readonly ValueTask _value; public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _value.IsCompleted; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ValueTaskAwaiter(ValueTask value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [StackTraceHidden] public TResult GetResult() { return _value.Result; } public void OnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.GetAwaiter().OnCompleted(continuation); } else if (obj != null) { Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext); } else { ValueTask.CompletedTask.GetAwaiter().OnCompleted(continuation); } } public void UnsafeOnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.GetAwaiter().UnsafeOnCompleted(continuation); } else if (obj != null) { Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); } else { ValueTask.CompletedTask.GetAwaiter().UnsafeOnCompleted(continuation); } } } [AttributeUsage(AttributeTargets.All)] internal class __BlockReflectionAttribute : Attribute { } } namespace System.Diagnostics { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class StackTraceHiddenAttribute : Attribute { } }