Decompiled source of GDWeave v2.0.14

GDWeave/core/GDWeave.dll

Decompiled 3 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using GDWeave.Godot;
using GDWeave.Godot.Variants;
using GDWeave.Modding;
using Iced.Intel;
using Reloaded.Hooks;
using Reloaded.Hooks.Definitions;
using Reloaded.Memory.Sigscan;
using Reloaded.Memory.Sigscan.Definitions.Structs;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Sinks.File;
using Serilog.Sinks.SystemConsole.Themes;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(/*Could not decode attribute arguments.*/)]
[assembly: TargetFramework(".NETCoreApp,Version=v8.0", FrameworkDisplayName = ".NET 8.0")]
[assembly: AssemblyCompany("GDWeave")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("2.0.14.0")]
[assembly: AssemblyInformationalVersion("2.0.14.0+30f7a5233b08874f5ea55a9a43486cb8678bc312")]
[assembly: AssemblyProduct("GDWeave")]
[assembly: AssemblyTitle("GDWeave")]
[assembly: SecurityPermission(8, SkipVerification = true)]
[assembly: AssemblyVersion("2.0.14.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace GDWeave
{
	internal class ConsoleFixer
	{
		[DllImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(2)]
		private static extern bool AllocConsole();

		[DllImport("kernel32.dll")]
		[return: MarshalAs(2)]
		private static extern bool AttachConsole(int pid);

		public static void Init()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			if (Environment.GetEnvironmentVariable("GDWEAVE_CONSOLE") != null)
			{
				AllocConsole();
				AttachConsole(-1);
			}
			Console.SetOut((TextWriter)new StreamWriter(Console.OpenStandardOutput())
			{
				AutoFlush = true
			});
			Console.SetError((TextWriter)new StreamWriter(Console.OpenStandardError())
			{
				AutoFlush = true
			});
		}
	}
	internal class GDWeave
	{
		public delegate void MainDelegate();

		public static readonly Assembly Assembly = Assembly.GetExecutingAssembly();

		public static readonly string Version = ((object)Assembly.GetName().Version).ToString();

		public static string GameDir = null;

		public static string GDWeaveDir = null;

		public static ILogger Logger = null;

		public static ModLoader ModLoader = null;

		public static Interop Interop = null;

		public static Hooks Hooks = null;

		public static JsonSerializerOptions JsonSerializerOptions;

		public static void Main()
		{
			try
			{
				Init();
			}
			catch (global::System.Exception ex)
			{
				if (Logger != null)
				{
					Logger.Error(ex, "GDWeave failed to initialize");
				}
				else
				{
					Console.WriteLine("GDWeave failed to initialize: " + ex.Message);
				}
			}
		}

		private static void Init()
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			ConsoleFixer.Init();
			GameDir = Path.GetDirectoryName(Environment.ProcessPath);
			GDWeaveDir = Environment.GetEnvironmentVariable("GDWEAVE_FOLDER_OVERRIDE") ?? Path.Combine(GameDir, "GDWeave");
			string text = Path.Combine(GDWeaveDir, "GDWeave.log");
			if (File.Exists(text))
			{
				File.Delete(text);
			}
			LoggerConfiguration val = ConsoleLoggerConfigurationExtensions.Console(FileLoggerConfigurationExtensions.File(new LoggerConfiguration().WriteTo, text, (LogEventLevel)0, "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}", (IFormatProvider)null, (long?)1073741824L, (LoggingLevelSwitch)null, false, false, (TimeSpan?)null, (RollingInterval)0, false, (int?)31, (Encoding)null, (FileLifecycleHooks)null, (TimeSpan?)null).WriteTo, (LogEventLevel)0, "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", (IFormatProvider)null, (LoggingLevelSwitch)null, (LogEventLevel?)null, (ConsoleTheme)null, false, (object)null);
			if (Environment.GetEnvironmentVariable("GDWEAVE_DEBUG") != null)
			{
				val.MinimumLevel.Verbose();
			}
			else
			{
				val.MinimumLevel.Information();
			}
			Logger = (ILogger)(object)val.CreateLogger();
			Log.Logger = Logger;
			Logger.Information<string, string>("This is GDWeave {Version} - {GitHub}", Version, "https://github.com/NotNite/GDWeave");
			ModLoader = new ModLoader();
			Interop = new Interop();
			List<IScriptMod> scriptMods = ModLoader.ScriptMods;
			int count = scriptMods.Count;
			List<IScriptMod> val2 = new List<IScriptMod>(count);
			CollectionsMarshal.SetCount<IScriptMod>(val2, count);
			global::System.Span<IScriptMod> span = CollectionsMarshal.AsSpan<IScriptMod>(val2);
			int num = 0;
			global::System.Span<IScriptMod> span2 = CollectionsMarshal.AsSpan<IScriptMod>(scriptMods);
			span2.CopyTo(span.Slice(num, span2.Length));
			num += span2.Length;
			List<IScriptMod> val3 = val2;
			List<LoadedMod> val4 = Enumerable.ToList<LoadedMod>(Enumerable.Where<LoadedMod>((global::System.Collections.Generic.IEnumerable<LoadedMod>)ModLoader.LoadedMods, (Func<LoadedMod, bool>)((LoadedMod m) => m.PackPath != null)));
			if (val4.Count > 0)
			{
				val3.Add((IScriptMod)new PackFileLoader(val4));
			}
			Hooks = new Hooks(new ScriptModder(val3), Interop);
		}

		static GDWeave()
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_0068: Expected O, but got Unknown
			JsonSerializerOptions val = new JsonSerializerOptions
			{
				WriteIndented = true
			};
			((global::System.Collections.Generic.ICollection<JsonConverter>)val.Converters).Add((JsonConverter)new JsonStringEnumConverter());
			JsonSerializerOptions = val;
		}
	}
	internal class Hooks
	{
		private unsafe delegate nint LoadByteCodeDelegate(nint gdscript, GodotString* path);

		private unsafe delegate nint SetCodeBufferDelegate(nint tokenizerBuffer, GodotVector* codeBuffer);

		private delegate nint SetUnhandledExceptionFilterDelegate(nint filter);

		private unsafe delegate nint UnhandledExceptionFilterDelegate(ExceptionPointersStruct* exceptionInfo);

		private enum PatternType
		{
			LoadByteCode,
			SetCode
		}

		[StructLayout(2, Pack = 1, Size = 8)]
		public struct CowData : global::System.IDisposable
		{
			[FieldOffset(0)]
			public nint Value;

			public unsafe int RefCount => *(int*)(Value - 8);

			public unsafe int Size => *(int*)(Value - 4);

			public unsafe static CowData Ctor(global::System.ReadOnlySpan<byte> buffer)
			{
				nint num = Marshal.AllocHGlobal(8 + buffer.Length);
				*(int*)num = 1;
				*(int*)(num + 4) = buffer.Length;
				buffer.CopyTo(new global::System.Span<byte>((void*)(num + 8), buffer.Length));
				CowData result = default(CowData);
				result.Value = num + 8;
				return result;
			}

			public void Dispose()
			{
				Marshal.FreeHGlobal((global::System.IntPtr)(Value - 8));
			}
		}

		[StructLayout(2, Pack = 1)]
		public struct GodotString
		{
			[FieldOffset(0)]
			public CowData CowData;

			public string Value
			{
				get
				{
					string str = Marshal.PtrToStringUni((global::System.IntPtr)CowData.Value, CowData.Size);
					MemoryUtils.TrimNullTerminator(ref str);
					return str;
				}
			}

			public unsafe static GodotString* Ctor(string value)
			{
				GodotString* ptr = (GodotString*)Marshal.AllocHGlobal(sizeof(GodotString));
				ptr->CowData = CowData.Ctor(global::System.ReadOnlySpan<byte>.op_Implicit(Encoding.Unicode.GetBytes(value + "\0")));
				return ptr;
			}

			public unsafe static void Dtor(GodotString* str)
			{
				str->CowData.Dispose();
				Marshal.FreeHGlobal((global::System.IntPtr)(nint)str);
			}
		}

		public class GodotStringWrapper : global::System.IDisposable
		{
			public unsafe readonly GodotString* String = GodotString.Ctor(value);

			public unsafe GodotStringWrapper(string value)
			{
			}

			public unsafe void Dispose()
			{
				GodotString.Dtor(String);
			}
		}

		[StructLayout(2, Pack = 1)]
		public struct GodotVector
		{
			[FieldOffset(8)]
			public CowData CowData;

			public unsafe global::System.ReadOnlySpan<byte> Data => new global::System.ReadOnlySpan<byte>((void*)CowData.Value, CowData.Size);

			public unsafe static GodotVector* Ctor(global::System.ReadOnlySpan<byte> buffer)
			{
				GodotVector* ptr = (GodotVector*)Marshal.AllocHGlobal(sizeof(GodotVector));
				ptr->CowData = CowData.Ctor(buffer);
				return ptr;
			}

			public unsafe static void Dtor(GodotVector* vector)
			{
				vector->CowData.Dispose();
				Marshal.FreeHGlobal((global::System.IntPtr)(nint)vector);
			}
		}

		public class GodotVectorWrapper : global::System.IDisposable
		{
			public unsafe readonly GodotVector* Vector = GodotVector.Ctor(buffer);

			public unsafe GodotVectorWrapper(global::System.ReadOnlySpan<byte> buffer)
			{
			}

			public unsafe void Dispose()
			{
				GodotVector.Dtor(Vector);
			}
		}

		private struct ExceptionPointersStruct
		{
			public unsafe ExceptionRecordStruct* ExceptionRecord;
		}

		private struct ExceptionRecordStruct
		{
			public uint ExceptionCode;

			public uint ExceptionFlags;

			public nint ExceptionRecord;

			public nint ExceptionAddress;

			public uint NumberParameters;

			[FixedBuffer(typeof(uint), 15)]
			public unsafe fixed uint ExceptionInformation[15];
		}

		private ITrackedHook<SetUnhandledExceptionFilterDelegate> setUnhandledExceptionFilterHook;

		private UnhandledExceptionFilterDelegate unhandledExceptionFilter;

		private ITrackedHook<LoadByteCodeDelegate> loadByteCodeHook;

		private ITrackedHook<SetCodeBufferDelegate> setCodeBufferHook;

		private readonly ILogger logger = GDWeave.Logger.ForContext<Hooks>();

		private readonly ThreadLocal<string> currentPath = new ThreadLocal<string>((Func<string>)(() => string.Empty));

		private readonly ScriptModder modder;

		private bool dumpGdsc = Environment.GetEnvironmentVariable("GDWEAVE_DUMP_GDSC") != null;

		public unsafe Hooks(ScriptModder modder, Interop interop)
		{
			this.modder = modder;
			nint procAddress = GetProcAddress(LoadLibrary("kernel32.dll"), "SetUnhandledExceptionFilter");
			unhandledExceptionFilter = UnhandledExceptionFilter;
			setUnhandledExceptionFilterHook = interop.CreateHook<SetUnhandledExceptionFilterDelegate>(procAddress, SetUnhandledExceptionFilterDetour);
			setUnhandledExceptionFilterHook.Enable();
			Dictionary<PatternType, string[]> val = new Dictionary<PatternType, string[]>
			{
				[PatternType.LoadByteCode] = new string[2] { "E8 ?? ?? ?? ?? 85 C0 0F 84 ?? ?? ?? ?? 48 89 7D ?? 48 8D 35", "48 89 54 24 ?? 48 89 4C 24 ?? 55 53 56 57 41 54 41 55 41 56 41 57 48 8D AC 24 ?? ?? ?? ?? 48 81 EC 78 02 00 00" },
				[PatternType.SetCode] = new string[2] { "E8 ?? ?? ?? ?? 48 89 5D ?? 48 8D 54 24 ?? 48 8D 4D ?? E8 ?? ?? ?? ?? 44 8B E0", "48 89 5C 24 ?? 55 56 57 41 54 41 55 41 56 41 57 48 8D 6C 24 ?? 48 81 EC D0 00 00 00 48 8B 05 ?? ?? ?? ?? 48 33 C4 48 89 45 ?? 4C 8B F9" }
			};
			if (File.Exists("patterns.json"))
			{
				val = JsonSerializer.Deserialize<Dictionary<PatternType, string[]>>(File.ReadAllText("patterns.json"), GDWeave.JsonSerializerOptions);
			}
			nint addr = interop.ScanText(val[PatternType.LoadByteCode]);
			loadByteCodeHook = interop.CreateHook<LoadByteCodeDelegate>(addr, LoadByteCodeDetour);
			loadByteCodeHook.Enable();
			nint addr2 = interop.ScanText(val[PatternType.SetCode]);
			setCodeBufferHook = interop.CreateHook<SetCodeBufferDelegate>(addr2, SetCodeBufferDetour);
			setCodeBufferHook.Enable();
		}

		private nint SetUnhandledExceptionFilterDetour(nint filter)
		{
			return setUnhandledExceptionFilterHook.Original(Marshal.GetFunctionPointerForDelegate<UnhandledExceptionFilterDelegate>(unhandledExceptionFilter));
		}

		private unsafe nint UnhandledExceptionFilter(ExceptionPointersStruct* exceptionInfo)
		{
			logger.Error("========== UNHANDLED EXCEPTION!!!");
			logger.Error<uint>("Exception code: {Code:X8}", exceptionInfo->ExceptionRecord->ExceptionCode);
			logger.Error<nint>("Exception address: {Address:X8}", exceptionInfo->ExceptionRecord->ExceptionAddress);
			MessageBox(global::System.IntPtr.Zero, "The game has crashed. Sorry! :(\r\n\r\nTry disabling some mods and see if the problem persists. It is very likely this issue was not caused by GDWeave itself but rather a mod.\r\n\r\nWhen asking for support, provide the log file in the GDWeave folder in your game install.", "GDWeave", 48u);
			return 0;
		}

		private unsafe nint LoadByteCodeDetour(nint gdscript, GodotString* path)
		{
			currentPath.Value = path->Value;
			return loadByteCodeHook.Original(gdscript, path);
		}

		private unsafe nint SetCodeBufferDetour(nint tokenizerBuffer, GodotVector* codeBuffer)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Expected O, but got Unknown
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Expected O, but got Unknown
			global::System.ReadOnlySpan<byte> buffer = codeBuffer->Data;
			string text = currentPath.Value ?? string.Empty;
			bool flag = false;
			try
			{
				MemoryStream val = new MemoryStream(buffer.ToArray());
				try
				{
					BinaryReader val2 = new BinaryReader((Stream)(object)val);
					try
					{
						GodotScriptFile godotScriptFile = new GodotScriptFile(val2);
						if (dumpGdsc)
						{
							DumpGdsc(godotScriptFile, text, "gdc");
						}
						try
						{
							flag = modder.Run(godotScriptFile, text);
						}
						catch (global::System.Exception ex)
						{
							logger.Error<string>(ex, "Failed to run mod on {Path}", text);
						}
						if (dumpGdsc && flag)
						{
							DumpGdsc(godotScriptFile, text, "gdc_modded");
						}
						MemoryStream val3 = new MemoryStream();
						try
						{
							BinaryWriter val4 = new BinaryWriter((Stream)(object)val3);
							try
							{
								godotScriptFile.Write(val4);
								buffer = global::System.ReadOnlySpan<byte>.op_Implicit(val3.ToArray());
							}
							finally
							{
								((global::System.IDisposable)val4)?.Dispose();
							}
						}
						finally
						{
							((global::System.IDisposable)val3)?.Dispose();
						}
					}
					finally
					{
						((global::System.IDisposable)val2)?.Dispose();
					}
				}
				finally
				{
					((global::System.IDisposable)val)?.Dispose();
				}
			}
			catch (global::System.Exception ex2)
			{
				if (!(ex2 is InvalidDataException))
				{
					logger.Error<string>(ex2, "Failed to parse GDSC file {Path}", text);
				}
			}
			if (!flag)
			{
				return setCodeBufferHook.Original(tokenizerBuffer, codeBuffer);
			}
			using GodotVectorWrapper godotVectorWrapper = new GodotVectorWrapper(buffer);
			return setCodeBufferHook.Original(tokenizerBuffer, godotVectorWrapper.Vector);
		}

		private void DumpGdsc(GodotScriptFile script, string path, string dir)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			try
			{
				string text = Path.Combine(Path.GetDirectoryName(Environment.ProcessPath), dir, path.Replace("res://", ""));
				string directoryName = Path.GetDirectoryName(text);
				if (!Directory.Exists(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				if (File.Exists(text))
				{
					File.Delete(text);
				}
				FileStream val = File.OpenWrite(text);
				try
				{
					BinaryWriter val2 = new BinaryWriter((Stream)(object)val);
					try
					{
						script.Write(val2);
					}
					finally
					{
						((global::System.IDisposable)val2)?.Dispose();
					}
				}
				finally
				{
					((global::System.IDisposable)val)?.Dispose();
				}
			}
			catch (global::System.Exception ex)
			{
				logger.Warning(ex, "Failed to write GDSC file");
			}
		}

		public unsafe static nint CowDataCtor(global::System.ReadOnlySpan<byte> buffer)
		{
			nint num = Marshal.AllocHGlobal(8 + buffer.Length);
			*(int*)num = 1;
			*(int*)(num + 4) = buffer.Length;
			buffer.CopyTo(new global::System.Span<byte>((void*)(num + 8), buffer.Length));
			return num + 8;
		}

		public static void CowDataDtor(nint cowData)
		{
			Marshal.FreeHGlobal((global::System.IntPtr)(cowData - 8));
		}

		[DllImport("kernel32.dll", CharSet = 3, SetLastError = true)]
		private static extern nint LoadLibrary(string lpFileName);

		[DllImport("kernel32.dll", CharSet = 2, SetLastError = true)]
		private static extern nint GetProcAddress(nint hModule, string lpProcName);

		[DllImport("user32.dll", CharSet = 3, SetLastError = true)]
		private static extern int MessageBox(nint hwnd, string text, string caption, uint type);
	}
	public interface IMod : global::System.IDisposable
	{
	}
	public interface IModInterface
	{
		ILogger Logger { get; }

		string[] LoadedMods { get; }

		T ReadConfig<T>() where T : class, new();

		void WriteConfig<T>(T config) where T : class;

		void RegisterScriptMod(IScriptMod mod);
	}
	public class Interop : global::System.IDisposable
	{
		private class UnsafeCodeReader : CodeReader
		{
			private readonly int length;

			private unsafe readonly byte* address;

			private int pos;

			public bool CanReadByte => pos < length;

			public unsafe UnsafeCodeReader(byte* address, int length)
			{
				this.length = length;
				this.address = address;
			}

			public unsafe override int ReadByte()
			{
				if (pos < length)
				{
					return address[pos++];
				}
				return -1;
			}
		}

		private readonly Process process;

		private readonly Scanner scanner;

		private List<TrackedHook> tracked = new List<TrackedHook>();

		[field: CompilerGenerated]
		public nint BaseAddress
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private init;
		}

		public Interop()
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			process = Process.GetCurrentProcess();
			scanner = new Scanner(process, process.MainModule);
			BaseAddress = process.MainModule.BaseAddress;
		}

		public void Dispose()
		{
			tracked.ForEach((Action<TrackedHook>)delegate(TrackedHook x)
			{
				x.Dispose();
			});
			tracked.Clear();
		}

		public nint ScanText(string[] text)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			foreach (string text2 in text)
			{
				PatternScanResult val = scanner.FindPattern(text2);
				if (!((PatternScanResult)(ref val)).Found)
				{
					Console.WriteLine("Failed to match signature {0}", (object)text2);
					continue;
				}
				nint num = (nint)process.MainModule.BaseAddress + ((PatternScanResult)(ref val)).Offset;
				byte b = Marshal.ReadByte((global::System.IntPtr)num);
				if ((uint)(b - 232) > 1u)
				{
					return num;
				}
				return ResolveJmpCall(num);
			}
			throw new global::System.Exception("Failed to match any signatures");
		}

		public unsafe nint GetStaticAddress(string[] sigs, int offset = 0)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Invalid comparison between Unknown and I4
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Invalid comparison between Unknown and I4
			nint num = ScanText(sigs) + offset;
			UnsafeCodeReader unsafeCodeReader = new UnsafeCodeReader((byte*)num, 64);
			Decoder val = Decoder.Create(64, (CodeReader)(object)unsafeCodeReader, (ulong)num, (DecoderOptions)2);
			while (unsafeCodeReader.CanReadByte)
			{
				Instruction val2 = val.Decode();
				if (!((Instruction)(ref val2)).IsInvalid && ((int)((Instruction)(ref val2)).Op0Kind == 24 || (int)((Instruction)(ref val2)).Op1Kind == 24))
				{
					return (nint)((Instruction)(ref val2)).MemoryDisplacement64;
				}
			}
			throw new global::System.Exception("Failed to resolve static address from signature");
		}

		private nint ResolveJmpCall(nint address)
		{
			int num = Marshal.ReadInt32((global::System.IntPtr)(address + 1));
			return address + 5 + num;
		}

		public ITrackedHook<T> CreateHook<T>(nint addr, T detour) where T : global::System.Delegate
		{
			byte[] originalBytes = MemoryUtils.ReadRaw(addr, 50);
			IHook<T> val = ReloadedHooks.Instance.CreateHook<T>(detour, (long)addr);
			val.Activate();
			val.Disable();
			TrackedHook<T> trackedHook = new TrackedHook<T>(addr, originalBytes, val);
			tracked.Add((TrackedHook)trackedHook);
			return trackedHook;
		}
	}
	public interface ITrackedHook : global::System.IDisposable
	{
		nint Address { get; }

		bool Enabled { get; }

		void Enable();

		void Disable();

		bool Toggle();
	}
	public interface ITrackedHook<out T> : ITrackedHook, global::System.IDisposable where T : global::System.Delegate
	{
		T Original { get; }
	}
	public abstract class TrackedHook : ITrackedHook, global::System.IDisposable
	{
		[CompilerGenerated]
		private nint <addr>P;

		[CompilerGenerated]
		private byte[] <originalBytes>P;

		public byte[] OriginalBytes => <originalBytes>P;

		public nint Address => <addr>P;

		public abstract bool Enabled { get; }

		protected TrackedHook(nint addr, byte[] originalBytes)
		{
			<addr>P = addr;
			<originalBytes>P = originalBytes;
			base..ctor();
		}

		public virtual void Dispose()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			MemoryUtils.Unprotect(Address, OriginalBytes.Length, (Action)([CompilerGenerated] () =>
			{
				MemoryUtils.WriteRaw(Address, OriginalBytes);
			}));
		}

		public abstract void Enable();

		public abstract void Disable();

		public abstract bool Toggle();
	}
	public class TrackedHook<T> : TrackedHook, ITrackedHook<T>, ITrackedHook, global::System.IDisposable where T : global::System.Delegate
	{
		[CompilerGenerated]
		private IHook<T> <hook>P;

		public T Original => <hook>P.OriginalFunction;

		public override bool Enabled => <hook>P.IsHookEnabled;

		public TrackedHook(nint addr, byte[] originalBytes, IHook<T> hook)
		{
			<hook>P = hook;
			base..ctor(addr, originalBytes);
		}

		public override void Enable()
		{
			if (!<hook>P.IsHookEnabled)
			{
				<hook>P.Enable();
			}
		}

		public override void Disable()
		{
			if (<hook>P.IsHookEnabled)
			{
				<hook>P.Disable();
			}
		}

		public override bool Toggle()
		{
			if (<hook>P.IsHookEnabled)
			{
				<hook>P.Disable();
				return false;
			}
			<hook>P.Enable();
			return true;
		}

		public override void Dispose()
		{
			Disable();
			base.Dispose();
		}
	}
	[RequiredMember]
	internal class LoadedMod
	{
		[RequiredMember]
		public ModManifest Manifest;

		[RequiredMember]
		public string Directory;

		public IMod? AssemblyMod;

		public string? AssemblyPath;

		public string? PackPath;

		[Obsolete("Constructors of types with required members are not supported in this version of your compiler.", true)]
		[CompilerFeatureRequired("RequiredMembers")]
		public LoadedMod()
		{
		}
	}
	internal class ModInterface : IModInterface
	{
		[CompilerGenerated]
		private string <modId>P;

		[CompilerGenerated]
		private ModLoader <modLoader>P;

		[field: CompilerGenerated]
		public ILogger Logger
		{
			[CompilerGenerated]
			get;
		}

		public string[] LoadedMods => Enumerable.ToArray<string>(Enumerable.Select<LoadedMod, string>((global::System.Collections.Generic.IEnumerable<LoadedMod>)<modLoader>P.LoadedMods, (Func<LoadedMod, string>)((LoadedMod x) => x.Manifest.Id)));

		public ModInterface(string modId, ModLoader modLoader)
		{
			<modId>P = modId;
			<modLoader>P = modLoader;
			Logger = GDWeave.Logger.ForContext("SourceContext", (object)<modId>P, false);
			base..ctor();
		}

		private string GetConfigPath()
		{
			return Path.Combine(GDWeave.GDWeaveDir, "configs", <modId>P + ".json");
		}

		public T ReadConfig<T>() where T : class, new()
		{
			string configPath = GetConfigPath();
			if (!File.Exists(configPath))
			{
				T val = new T();
				WriteConfig(val);
				return val;
			}
			T val2 = JsonSerializer.Deserialize<T>(File.ReadAllText(configPath), GDWeave.JsonSerializerOptions);
			WriteConfig(val2);
			return val2;
		}

		public void WriteConfig<T>(T config) where T : class
		{
			string configPath = GetConfigPath();
			string directoryName = Path.GetDirectoryName(configPath);
			if (!Directory.Exists(directoryName))
			{
				Directory.CreateDirectory(directoryName);
			}
			string text = JsonSerializer.Serialize<T>(config, GDWeave.JsonSerializerOptions);
			File.WriteAllText(configPath, text);
		}

		public void RegisterScriptMod(IScriptMod mod)
		{
			<modLoader>P.RegisterScriptMod(<modId>P, mod);
		}
	}
	public class ModLoadContext : AssemblyLoadContext
	{
		private AssemblyDependencyResolver resolver = new AssemblyDependencyResolver(path);

		public ModLoadContext(string path)
			: base(true)
		{
		}//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Expected O, but got Unknown


		protected override Assembly Load(AssemblyName assemblyName)
		{
			AssemblyName assemblyName2 = assemblyName;
			if (assemblyName2.Name == "GDWeave")
			{
				return GDWeave.Assembly;
			}
			AssemblyName val = Enumerable.FirstOrDefault<AssemblyName>((global::System.Collections.Generic.IEnumerable<AssemblyName>)GDWeave.Assembly.GetReferencedAssemblies(), (Func<AssemblyName, bool>)((AssemblyName a) => a.Name == assemblyName2.Name));
			if (val != null)
			{
				return Assembly.Load(val);
			}
			string text = resolver.ResolveAssemblyToPath(assemblyName2);
			if (text == null)
			{
				return null;
			}
			return ((AssemblyLoadContext)this).LoadFromAssemblyPath(text);
		}

		protected override nint LoadUnmanagedDll(string unmanagedDllName)
		{
			string text = resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
			if (text == null)
			{
				return global::System.IntPtr.Zero;
			}
			return ((AssemblyLoadContext)this).LoadUnmanagedDllFromPath(text);
		}
	}
	internal class ModLoader
	{
		public List<LoadedMod> LoadedMods = new List<LoadedMod>();

		private readonly ILogger logger = GDWeave.Logger.ForContext<ModLoader>();

		private readonly Dictionary<string, List<IScriptMod>> scriptMods = new Dictionary<string, List<IScriptMod>>();

		public List<IScriptMod> ScriptMods => Enumerable.ToList<IScriptMod>(Enumerable.SelectMany<List<IScriptMod>, IScriptMod>((global::System.Collections.Generic.IEnumerable<List<IScriptMod>>)scriptMods.Values, (Func<List<IScriptMod>, global::System.Collections.Generic.IEnumerable<IScriptMod>>)((List<IScriptMod> x) => (global::System.Collections.Generic.IEnumerable<IScriptMod>)x)));

		public ModLoader()
		{
			Register();
			Sort();
			LoadAssemblies();
			logger.Information<int, global::System.Collections.Generic.IEnumerable<string>>("Loaded {Count} mods: {ModIds}", LoadedMods.Count, Enumerable.Select<LoadedMod, string>((global::System.Collections.Generic.IEnumerable<LoadedMod>)LoadedMods, (Func<LoadedMod, string>)((LoadedMod x) => x.Manifest.Id)));
		}

		private void Register()
		{
			string text = Path.Combine(GDWeave.GDWeaveDir, "mods");
			if (!Directory.Exists(text))
			{
				return;
			}
			string[] directories = Directory.GetDirectories(text);
			foreach (string text2 in directories)
			{
				try
				{
					string text3 = Path.Combine(text2, "manifest.json");
					if (!File.Exists(text3))
					{
						logger.Warning<string>("Mod at {ModDir} does not have a manifest.json", text2);
						continue;
					}
					ModManifest manifest = JsonSerializer.Deserialize<ModManifest>(File.ReadAllText(text3), (JsonSerializerOptions)null);
					if (Enumerable.Any<LoadedMod>((global::System.Collections.Generic.IEnumerable<LoadedMod>)LoadedMods, (Func<LoadedMod, bool>)((LoadedMod x) => x.Manifest.Id == manifest.Id)))
					{
						logger.Warning<string>("Duplicate mod ID: {ModId}", manifest.Id);
						continue;
					}
					logger.Debug<string, string>("Loading mod {ModId} from {ModDir}", manifest.Id, text2);
					LoadedMod obj = new LoadedMod
					{
						Manifest = manifest,
						Directory = text2,
						AssemblyMod = null
					};
					string assemblyPath = manifest.AssemblyPath;
					obj.AssemblyPath = ((assemblyPath != null) ? Path.Combine(text2, assemblyPath) : null);
					string packPath = manifest.PackPath;
					obj.PackPath = ((packPath != null) ? Path.Combine(text2, packPath) : null);
					LoadedMod loadedMod = obj;
					if (loadedMod.AssemblyPath != null && !File.Exists(loadedMod.AssemblyPath))
					{
						logger.Warning<string>("Assembly at {AssemblyPath} does not exist", loadedMod.AssemblyPath);
					}
					else if (loadedMod.PackPath != null && !File.Exists(loadedMod.PackPath))
					{
						logger.Warning<string>("Pack file at {PackPath} does not exist", loadedMod.PackPath);
					}
					else
					{
						LoadedMods.Add(loadedMod);
					}
				}
				catch (global::System.Exception ex)
				{
					logger.Warning<string>(ex, "Failed to load mod at {ModDir}", text2);
				}
			}
		}

		private void Sort()
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			while (true)
			{
				List<LoadedMod> val = Enumerable.ToList<LoadedMod>(Enumerable.Where<LoadedMod>((global::System.Collections.Generic.IEnumerable<LoadedMod>)LoadedMods, (Func<LoadedMod, bool>)((LoadedMod x) => Enumerable.Any<string>((global::System.Collections.Generic.IEnumerable<string>)x.Manifest.Dependencies, (Func<string, bool>)((string d) => !Enumerable.Any<LoadedMod>((global::System.Collections.Generic.IEnumerable<LoadedMod>)LoadedMods, (Func<LoadedMod, bool>)((LoadedMod m) => m.Manifest.Id == d)))))));
				if (val.Count == 0)
				{
					break;
				}
				Enumerator<LoadedMod> enumerator = val.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						LoadedMod current = enumerator.Current;
						logger.Warning<string, List<string>>("Mod {ModId} has missing/invalid dependencies: {InvalidDependencies}", current.Manifest.Id, current.Manifest.Dependencies);
						LoadedMods.Remove(current);
					}
				}
				finally
				{
					((global::System.IDisposable)enumerator).Dispose();
				}
			}
			Dictionary<string, List<string>> val2 = Enumerable.ToDictionary<LoadedMod, string, List<string>>((global::System.Collections.Generic.IEnumerable<LoadedMod>)LoadedMods, (Func<LoadedMod, string>)((LoadedMod x) => x.Manifest.Id), (Func<LoadedMod, List<string>>)((LoadedMod x) => x.Manifest.Dependencies));
			List<string> resolvedOrder = new List<string>();
			string text = default(string);
			List<string> val4 = default(List<string>);
			while (val2.Count > 0)
			{
				List<KeyValuePair<string, List<string>>> val3 = Enumerable.ToList<KeyValuePair<string, List<string>>>(Enumerable.Where<KeyValuePair<string, List<string>>>((global::System.Collections.Generic.IEnumerable<KeyValuePair<string, List<string>>>)val2, (Func<KeyValuePair<string, List<string>>, bool>)((KeyValuePair<string, List<string>> x) => x.Value.Count == 0)));
				Enumerator<KeyValuePair<string, List<string>>> enumerator2 = val3.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						enumerator2.Current.Deconstruct(ref text, ref val4);
						string text2 = text;
						resolvedOrder.Add(text2);
						val2.Remove(text2);
					}
				}
				finally
				{
					((global::System.IDisposable)enumerator2).Dispose();
				}
				Enumerator<string, List<string>> enumerator3 = val2.GetEnumerator();
				try
				{
					while (enumerator3.MoveNext())
					{
						enumerator3.Current.Deconstruct(ref text, ref val4);
						List<string> val5 = val4;
						enumerator2 = val3.GetEnumerator();
						try
						{
							while (enumerator2.MoveNext())
							{
								val5.Remove(enumerator2.Current.Key);
							}
						}
						finally
						{
							((global::System.IDisposable)enumerator2).Dispose();
						}
					}
				}
				finally
				{
					((global::System.IDisposable)enumerator3).Dispose();
				}
				if (val3.Count == 0)
				{
					logger.Warning<KeyCollection<string, List<string>>>("Circular dependency detected: {CircularDependency}", val2.Keys);
					break;
				}
			}
			logger.Debug<List<string>>("Resolved mod load order: {ResolvedOrder}", resolvedOrder);
			LoadedMods = Enumerable.ToList<LoadedMod>((global::System.Collections.Generic.IEnumerable<LoadedMod>)Enumerable.OrderBy<LoadedMod, int>((global::System.Collections.Generic.IEnumerable<LoadedMod>)LoadedMods, (Func<LoadedMod, int>)((LoadedMod x) => resolvedOrder.IndexOf(x.Manifest.Id))));
		}

		private void LoadAssemblies()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			List<LoadedMod> val = new List<LoadedMod>();
			Enumerator<LoadedMod> enumerator = LoadedMods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					LoadedMod current = enumerator.Current;
					string assemblyPath = current.AssemblyPath;
					if (assemblyPath != null)
					{
						try
						{
							logger.Debug<string, string>("Loading assembly for mod {ModId} from {AssemblyPath}", current.Manifest.Id, assemblyPath);
							IMod assemblyMod = LoadAssembly(current.Manifest.Id, assemblyPath);
							current.AssemblyMod = assemblyMod;
						}
						catch (global::System.Exception ex)
						{
							logger.Warning<string>(ex, "Failed to load assembly for mod {ModId}", current.Manifest.Id);
							val.Add(current);
						}
					}
				}
			}
			finally
			{
				((global::System.IDisposable)enumerator).Dispose();
			}
			enumerator = val.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					LoadedMod current2 = enumerator.Current;
					LoadedMods.Remove(current2);
				}
			}
			finally
			{
				((global::System.IDisposable)enumerator).Dispose();
			}
		}

		private IMod? LoadAssembly(string id, string assemblyPath)
		{
			string fullPath = Path.GetFullPath(assemblyPath);
			global::System.Type type = Enumerable.FirstOrDefault<global::System.Type>((global::System.Collections.Generic.IEnumerable<global::System.Type>)((AssemblyLoadContext)new ModLoadContext(fullPath)).LoadFromAssemblyPath(fullPath).GetTypes(), (Func<global::System.Type, bool>)((global::System.Type t) => Enumerable.FirstOrDefault<global::System.Type>((global::System.Collections.Generic.IEnumerable<global::System.Type>)t.GetInterfaces(), (Func<global::System.Type, bool>)((global::System.Type t) => t.FullName == typeof(IMod).FullName)) != (global::System.Type)null));
			if (type == (global::System.Type)null)
			{
				logger.Warning<string>("Assembly at {AssemblyPath} does not contain a mod", assemblyPath);
				return null;
			}
			ConstructorInfo constructor = type.GetConstructor(new global::System.Type[1] { typeof(IModInterface) });
			if (constructor == null)
			{
				return Activator.CreateInstance(type) as IMod;
			}
			return constructor.Invoke(new object[1]
			{
				new ModInterface(id, this)
			}) as IMod;
		}

		public void RegisterScriptMod(string modId, IScriptMod mod)
		{
			if (!scriptMods.ContainsKey(modId))
			{
				scriptMods[modId] = new List<IScriptMod>();
			}
			scriptMods[modId].Add(mod);
		}
	}
	[RequiredMember]
	internal class ModManifest
	{
		internal class ModMetadata
		{
			[field: CompilerGenerated]
			public string? Name
			{
				[CompilerGenerated]
				get;
				[CompilerGenerated]
				set;
			}

			[field: CompilerGenerated]
			public string? Author
			{
				[CompilerGenerated]
				get;
				[CompilerGenerated]
				set;
			}

			[field: CompilerGenerated]
			public string? Version
			{
				[CompilerGenerated]
				get;
				[CompilerGenerated]
				set;
			}

			[field: CompilerGenerated]
			public string? Description
			{
				[CompilerGenerated]
				get;
				[CompilerGenerated]
				set;
			}

			[field: CompilerGenerated]
			public string? Homepage
			{
				[CompilerGenerated]
				get;
				[CompilerGenerated]
				set;
			}
		}

		[RequiredMember]
		[field: CompilerGenerated]
		public string Id
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string? AssemblyPath
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string? PackPath
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public List<string> Dependencies
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		} = new List<string>();


		[field: CompilerGenerated]
		public ModMetadata? Metadata
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[Obsolete("Constructors of types with required members are not supported in this version of your compiler.", true)]
		[CompilerFeatureRequired("RequiredMembers")]
		public ModManifest()
		{
		}
	}
	internal class PackFileLoader : IScriptMod
	{
		[CompilerGenerated]
		private sealed class <Modify>d__4 : global::System.Collections.Generic.IEnumerable<Token>, global::System.Collections.IEnumerable, global::System.Collections.Generic.IEnumerator<Token>, global::System.Collections.IEnumerator, global::System.IDisposable
		{
			private int <>1__state;

			private Token <>2__current;

			private int <>l__initialThreadId;

			private global::System.Collections.Generic.IEnumerable<Token> tokens;

			public global::System.Collections.Generic.IEnumerable<Token> <>3__tokens;

			public PackFileLoader <>4__this;

			private MultiTokenWaiter <readyWaiter>5__2;

			private global::System.Collections.Generic.IEnumerator<Token> <>7__wrap2;

			private Token <token>5__4;

			private Enumerator<LoadedMod> <>7__wrap4;

			private LoadedMod <mod>5__6;

			Token global::System.Collections.Generic.IEnumerator<Token>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object global::System.Collections.IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <Modify>d__4(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void global::System.IDisposable.Dispose()
			{
				int num = <>1__state;
				if ((uint)(num - -4) > 1u && (uint)(num - 1) > 49u)
				{
					return;
				}
				try
				{
					if (num != -4 && (uint)(num - 2) > 47u)
					{
						return;
					}
					try
					{
					}
					finally
					{
						<>m__Finally2();
					}
				}
				finally
				{
					<>m__Finally1();
				}
			}

			private bool MoveNext()
			{
				//IL_023b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0240: Unknown result type (might be due to invalid IL or missing references)
				//IL_0b01: Unknown result type (might be due to invalid IL or missing references)
				try
				{
					int num = <>1__state;
					PackFileLoader packFileLoader = <>4__this;
					switch (num)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						<readyWaiter>5__2 = new MultiTokenWaiter(new Func<Token, bool>[6]
						{
							(Token t) => t.Type == TokenType.PrFunction,
							(Token t) => t is IdentifierToken identifierToken && identifierToken.Name == "_ready",
							(Token t) => t.Type == TokenType.ParenthesisOpen,
							(Token t) => t.Type == TokenType.ParenthesisClose,
							(Token t) => t.Type == TokenType.Colon,
							(Token t) => t.Type == TokenType.Newline
						});
						<>7__wrap2 = tokens.GetEnumerator();
						<>1__state = -3;
						break;
					case 1:
						<>1__state = -3;
						<>7__wrap4 = packFileLoader.<mods>P.GetEnumerator();
						<>1__state = -4;
						goto IL_0ae5;
					case 2:
						<>1__state = -4;
						<>2__current = new Token(TokenType.Period);
						<>1__state = 3;
						return true;
					case 3:
						<>1__state = -4;
						<>2__current = new IdentifierToken("load_resource_pack");
						<>1__state = 4;
						return true;
					case 4:
						<>1__state = -4;
						<>2__current = new Token(TokenType.ParenthesisOpen);
						<>1__state = 5;
						return true;
					case 5:
						<>1__state = -4;
						<>2__current = new ConstantToken(new StringVariant(<mod>5__6.PackPath));
						<>1__state = 6;
						return true;
					case 6:
						<>1__state = -4;
						<>2__current = new Token(TokenType.ParenthesisClose);
						<>1__state = 7;
						return true;
					case 7:
						<>1__state = -4;
						<>2__current = <token>5__4;
						<>1__state = 8;
						return true;
					case 8:
						<>1__state = -4;
						<>2__current = new Token(TokenType.PrVar);
						<>1__state = 9;
						return true;
					case 9:
						<>1__state = -4;
						<>2__current = new IdentifierToken(<mod>5__6.Manifest.Id ?? "");
						<>1__state = 10;
						return true;
					case 10:
						<>1__state = -4;
						<>2__current = new Token(TokenType.OpAssign);
						<>1__state = 11;
						return true;
					case 11:
						<>1__state = -4;
						<>2__current = new Token(TokenType.BuiltInFunc, 76u);
						<>1__state = 12;
						return true;
					case 12:
						<>1__state = -4;
						<>2__current = new Token(TokenType.ParenthesisOpen);
						<>1__state = 13;
						return true;
					case 13:
						<>1__state = -4;
						<>2__current = new ConstantToken(new StringVariant("res://mods/" + <mod>5__6.Manifest.Id + "/main.gd"));
						<>1__state = 14;
						return true;
					case 14:
						<>1__state = -4;
						<>2__current = new Token(TokenType.ParenthesisClose);
						<>1__state = 15;
						return true;
					case 15:
						<>1__state = -4;
						<>2__current = new Token(TokenType.Period);
						<>1__state = 16;
						return true;
					case 16:
						<>1__state = -4;
						<>2__current = new IdentifierToken("new");
						<>1__state = 17;
						return true;
					case 17:
						<>1__state = -4;
						<>2__current = new Token(TokenType.ParenthesisOpen);
						<>1__state = 18;
						return true;
					case 18:
						<>1__state = -4;
						<>2__current = new Token(TokenType.ParenthesisClose);
						<>1__state = 19;
						return true;
					case 19:
						<>1__state = -4;
						<>2__current = <token>5__4;
						<>1__state = 20;
						return true;
					case 20:
						<>1__state = -4;
						<>2__current = new IdentifierToken(<mod>5__6.Manifest.Id ?? "");
						<>1__state = 21;
						return true;
					case 21:
						<>1__state = -4;
						<>2__current = new Token(TokenType.Period);
						<>1__state = 22;
						return true;
					case 22:
						<>1__state = -4;
						<>2__current = new IdentifierToken("add_to_group");
						<>1__state = 23;
						return true;
					case 23:
						<>1__state = -4;
						<>2__current = new Token(TokenType.ParenthesisOpen);
						<>1__state = 24;
						return true;
					case 24:
						<>1__state = -4;
						<>2__current = new ConstantToken(new StringVariant("gdweave_mod"));
						<>1__state = 25;
						return true;
					case 25:
						<>1__state = -4;
						<>2__current = new Token(TokenType.ParenthesisClose);
						<>1__state = 26;
						return true;
					case 26:
						<>1__state = -4;
						<>2__current = <token>5__4;
						<>1__state = 27;
						return true;
					case 27:
						<>1__state = -4;
						<>2__current = new IdentifierToken(<mod>5__6.Manifest.Id ?? "");
						<>1__state = 28;
						return true;
					case 28:
						<>1__state = -4;
						<>2__current = new Token(TokenType.Period);
						<>1__state = 29;
						return true;
					case 29:
						<>1__state = -4;
						<>2__current = new IdentifierToken("set_name");
						<>1__state = 30;
						return true;
					case 30:
						<>1__state = -4;
						<>2__current = new Token(TokenType.ParenthesisOpen);
						<>1__state = 31;
						return true;
					case 31:
						<>1__state = -4;
						<>2__current = new ConstantToken(new StringVariant(<mod>5__6.Manifest.Id ?? ""));
						<>1__state = 32;
						return true;
					case 32:
						<>1__state = -4;
						<>2__current = new Token(TokenType.ParenthesisClose);
						<>1__state = 33;
						return true;
					case 33:
						<>1__state = -4;
						<>2__current = <token>5__4;
						<>1__state = 34;
						return true;
					case 34:
						<>1__state = -4;
						<>2__current = new IdentifierToken("get_tree");
						<>1__state = 35;
						return true;
					case 35:
						<>1__state = -4;
						<>2__current = new Token(TokenType.ParenthesisOpen);
						<>1__state = 36;
						return true;
					case 36:
						<>1__state = -4;
						<>2__current = new Token(TokenType.ParenthesisClose);
						<>1__state = 37;
						return true;
					case 37:
						<>1__state = -4;
						<>2__current = new Token(TokenType.Period);
						<>1__state = 38;
						return true;
					case 38:
						<>1__state = -4;
						<>2__current = new IdentifierToken("get_root");
						<>1__state = 39;
						return true;
					case 39:
						<>1__state = -4;
						<>2__current = new Token(TokenType.ParenthesisOpen);
						<>1__state = 40;
						return true;
					case 40:
						<>1__state = -4;
						<>2__current = new Token(TokenType.ParenthesisClose);
						<>1__state = 41;
						return true;
					case 41:
						<>1__state = -4;
						<>2__current = new Token(TokenType.Period);
						<>1__state = 42;
						return true;
					case 42:
						<>1__state = -4;
						<>2__current = new IdentifierToken("call_deferred");
						<>1__state = 43;
						return true;
					case 43:
						<>1__state = -4;
						<>2__current = new Token(TokenType.ParenthesisOpen);
						<>1__state = 44;
						return true;
					case 44:
						<>1__state = -4;
						<>2__current = new ConstantToken(new StringVariant("add_child"));
						<>1__state = 45;
						return true;
					case 45:
						<>1__state = -4;
						<>2__current = new Token(TokenType.Comma);
						<>1__state = 46;
						return true;
					case 46:
						<>1__state = -4;
						<>2__current = new IdentifierToken(<mod>5__6.Manifest.Id ?? "");
						<>1__state = 47;
						return true;
					case 47:
						<>1__state = -4;
						<>2__current = new Token(TokenType.ParenthesisClose);
						<>1__state = 48;
						return true;
					case 48:
						<>1__state = -4;
						<>2__current = <token>5__4;
						<>1__state = 49;
						return true;
					case 49:
						<>1__state = -4;
						<mod>5__6 = null;
						goto IL_0ae5;
					case 50:
						{
							<>1__state = -3;
							goto IL_0b30;
						}
						IL_0ae5:
						while (<>7__wrap4.MoveNext())
						{
							<mod>5__6 = <>7__wrap4.Current;
							if (<mod>5__6.PackPath != null)
							{
								<>2__current = new IdentifierToken("ProjectSettings");
								<>1__state = 2;
								return true;
							}
						}
						<>m__Finally2();
						<>7__wrap4 = default(Enumerator<LoadedMod>);
						packFileLoader.Ran = true;
						goto IL_0b30;
						IL_0b30:
						<token>5__4 = null;
						break;
					}
					if (((global::System.Collections.IEnumerator)<>7__wrap2).MoveNext())
					{
						<token>5__4 = <>7__wrap2.Current;
						if (<readyWaiter>5__2.Check(<token>5__4))
						{
							<>2__current = <token>5__4;
							<>1__state = 1;
							return true;
						}
						<>2__current = <token>5__4;
						<>1__state = 50;
						return true;
					}
					<>m__Finally1();
					<>7__wrap2 = null;
					return false;
				}
				catch
				{
					//try-fault
					((global::System.IDisposable)this).Dispose();
					throw;
				}
			}

			bool global::System.Collections.IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			private void <>m__Finally1()
			{
				<>1__state = -1;
				if (<>7__wrap2 != null)
				{
					((global::System.IDisposable)<>7__wrap2).Dispose();
				}
			}

			private void <>m__Finally2()
			{
				<>1__state = -3;
				((global::System.IDisposable)<>7__wrap4).Dispose();
			}

			[DebuggerHidden]
			void global::System.Collections.IEnumerator.Reset()
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			global::System.Collections.Generic.IEnumerator<Token> global::System.Collections.Generic.IEnumerable<Token>.GetEnumerator()
			{
				<Modify>d__4 <Modify>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					<Modify>d__ = this;
				}
				else
				{
					<Modify>d__ = new <Modify>d__4(0)
					{
						<>4__this = <>4__this
					};
				}
				<Modify>d__.tokens = <>3__tokens;
				return <Modify>d__;
			}

			[DebuggerHidden]
			global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator()
			{
				return (global::System.Collections.IEnumerator)((global::System.Collections.Generic.IEnumerable<Token>)this).GetEnumerator();
			}
		}

		[CompilerGenerated]
		private List<LoadedMod> <mods>P;

		public bool Ran;

		public PackFileLoader(List<LoadedMod> mods)
		{
			<mods>P = mods;
			base..ctor();
		}

		public bool ShouldRun(string path)
		{
			return !Ran;
		}

		[IteratorStateMachine(typeof(<Modify>d__4))]
		public global::System.Collections.Generic.IEnumerable<Token> Modify(string path, global::System.Collections.Generic.IEnumerable<Token> tokens)
		{
			MultiTokenWaiter readyWaiter = new MultiTokenWaiter(new Func<Token, bool>[6]
			{
				(Token t) => t.Type == TokenType.PrFunction,
				(Token t) => t is IdentifierToken identifierToken && identifierToken.Name == "_ready",
				(Token t) => t.Type == TokenType.ParenthesisOpen,
				(Token t) => t.Type == TokenType.ParenthesisClose,
				(Token t) => t.Type == TokenType.Colon,
				(Token t) => t.Type == TokenType.Newline
			});
			global::System.Collections.Generic.IEnumerator<Token> enumerator = tokens.GetEnumerator();
			try
			{
				while (((global::System.Collections.IEnumerator)enumerator).MoveNext())
				{
					Token token = enumerator.Current;
					if (readyWaiter.Check(token))
					{
						yield return token;
						Enumerator<LoadedMod> enumerator2 = <mods>P.GetEnumerator();
						try
						{
							while (enumerator2.MoveNext())
							{
								LoadedMod mod = enumerator2.Current;
								if (mod.PackPath != null)
								{
									yield return new IdentifierToken("ProjectSettings");
									yield return new Token(TokenType.Period);
									yield return new IdentifierToken("load_resource_pack");
									yield return new Token(TokenType.ParenthesisOpen);
									yield return new ConstantToken(new StringVariant(mod.PackPath));
									yield return new Token(TokenType.ParenthesisClose);
									yield return token;
									yield return new Token(TokenType.PrVar);
									yield return new IdentifierToken(mod.Manifest.Id ?? "");
									yield return new Token(TokenType.OpAssign);
									yield return new Token(TokenType.BuiltInFunc, 76u);
									yield return new Token(TokenType.ParenthesisOpen);
									yield return new ConstantToken(new StringVariant("res://mods/" + mod.Manifest.Id + "/main.gd"));
									yield return new Token(TokenType.ParenthesisClose);
									yield return new Token(TokenType.Period);
									yield return new IdentifierToken("new");
									yield return new Token(TokenType.ParenthesisOpen);
									yield return new Token(TokenType.ParenthesisClose);
									yield return token;
									yield return new IdentifierToken(mod.Manifest.Id ?? "");
									yield return new Token(TokenType.Period);
									yield return new IdentifierToken("add_to_group");
									yield return new Token(TokenType.ParenthesisOpen);
									yield return new ConstantToken(new StringVariant("gdweave_mod"));
									yield return new Token(TokenType.ParenthesisClose);
									yield return token;
									yield return new IdentifierToken(mod.Manifest.Id ?? "");
									yield return new Token(TokenType.Period);
									yield return new IdentifierToken("set_name");
									yield return new Token(TokenType.ParenthesisOpen);
									yield return new ConstantToken(new StringVariant(mod.Manifest.Id ?? ""));
									yield return new Token(TokenType.ParenthesisClose);
									yield return token;
									yield return new IdentifierToken("get_tree");
									yield return new Token(TokenType.ParenthesisOpen);
									yield return new Token(TokenType.ParenthesisClose);
									yield return new Token(TokenType.Period);
									yield return new IdentifierToken("get_root");
									yield return new Token(TokenType.ParenthesisOpen);
									yield return new Token(TokenType.ParenthesisClose);
									yield return new Token(TokenType.Period);
									yield return new IdentifierToken("call_deferred");
									yield return new Token(TokenType.ParenthesisOpen);
									yield return new ConstantToken(new StringVariant("add_child"));
									yield return new Token(TokenType.Comma);
									yield return new IdentifierToken(mod.Manifest.Id ?? "");
									yield return new Token(TokenType.ParenthesisClose);
									yield return token;
								}
							}
						}
						finally
						{
							((global::System.IDisposable)enumerator2).Dispose();
						}
						Ran = true;
					}
					else
					{
						yield return token;
					}
				}
			}
			finally
			{
				((global::System.IDisposable)enumerator)?.Dispose();
			}
		}
	}
	public static class MemoryUtils
	{
		[DllImport("kernel32.dll", SetLastError = true)]
		public static extern bool VirtualProtect(nint address, nint size, uint newProtect, out uint oldProtect);

		public static void Unprotect(nint memoryAddress, int size, Action action)
		{
			VirtualProtect(memoryAddress, size, 64u, out var oldProtect);
			action.Invoke();
			VirtualProtect(memoryAddress, size, oldProtect, out var _);
		}

		public static byte[] ReadRaw(nint memoryAddress, int length)
		{
			byte[] array = new byte[length];
			Marshal.Copy((global::System.IntPtr)memoryAddress, array, 0, array.Length);
			return array;
		}

		public static void WriteRaw(nint memoryAddress, byte[] value)
		{
			Marshal.Copy(value, 0, (global::System.IntPtr)memoryAddress, value.Length);
		}

		public static void TrimNullTerminator(ref string str)
		{
			int num = str.IndexOf('\0');
			if (num != -1)
			{
				str = str.Substring(0, num);
			}
		}
	}
}
namespace GDWeave.Modding
{
	public class FunctionWaiter : IWaiter
	{
		[CompilerGenerated]
		private bool <waitForReady>P;

		private readonly MultiTokenWaiter functionWaiter;

		private bool foundFunction;

		private bool foundColon;

		[field: CompilerGenerated]
		public bool Matched
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		[field: CompilerGenerated]
		public bool Ready
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		public FunctionWaiter(string name, bool waitForReady = false)
		{
			<waitForReady>P = waitForReady;
			string name2 = name;
			functionWaiter = new MultiTokenWaiter(new Func<Token, bool>[2]
			{
				(Token t) => t.Type == TokenType.PrFunction,
				(Token t) => t is IdentifierToken identifierToken && identifierToken.Name == name2
			});
			Ready = !<waitForReady>P;
			base..ctor();
		}

		public void Reset()
		{
			foundFunction = false;
			foundColon = false;
			Matched = false;
			Ready = !<waitForReady>P;
			functionWaiter.Reset();
		}

		public void SetReady()
		{
			Ready = true;
		}

		public bool Check(Token token)
		{
			if (!Ready || Matched)
			{
				return false;
			}
			if (foundColon && token.Type == TokenType.Newline)
			{
				Matched = true;
				return true;
			}
			if (foundFunction && token.Type == TokenType.Colon)
			{
				foundColon = true;
				return false;
			}
			if (functionWaiter.Check(token))
			{
				foundFunction = true;
				return false;
			}
			return false;
		}
	}
	public interface IWaiter
	{
		bool Matched { get; }

		bool Ready { get; }

		void Reset();

		void SetReady();

		bool Check(Token token);
	}
	public class MultiTokenWaiter : IWaiter
	{
		[CompilerGenerated]
		private Func<Token, bool>[] <checks>P;

		[CompilerGenerated]
		private bool <waitForReady>P;

		[CompilerGenerated]
		private bool <allowPartialMatch>P;

		[field: CompilerGenerated]
		public bool Matched
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		[field: CompilerGenerated]
		public bool Ready
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		[field: CompilerGenerated]
		public uint Step
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		public MultiTokenWaiter(Func<Token, bool>[] checks, bool waitForReady = false, bool allowPartialMatch = false)
		{
			<checks>P = checks;
			<waitForReady>P = waitForReady;
			<allowPartialMatch>P = allowPartialMatch;
			Ready = !<waitForReady>P;
			base..ctor();
		}

		public void Reset()
		{
			Matched = false;
			Ready = !<waitForReady>P;
			Step = 0u;
		}

		public void SetReady()
		{
			Ready = true;
		}

		public bool Check(Token token)
		{
			if (!Matched && Ready)
			{
				if (<checks>P[Step].Invoke(token))
				{
					Step++;
					if (Step >= <checks>P.Length)
					{
						Matched = true;
						return true;
					}
				}
				else if (!<allowPartialMatch>P)
				{
					Reset();
				}
			}
			return false;
		}
	}
	public interface IScriptMod
	{
		bool ShouldRun(string path);

		global::System.Collections.Generic.IEnumerable<Token> Modify(string path, global::System.Collections.Generic.IEnumerable<Token> tokens);
	}
	public class ScriptModder
	{
		[CompilerGenerated]
		private List<IScriptMod>? <mods>P;

		public ScriptModder(List<IScriptMod>? mods = null)
		{
			<mods>P = mods;
			base..ctor();
		}

		public bool Run(GodotScriptFile file, string path)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			List<Token> val = CreateSpecialTokens(file);
			bool flag = false;
			if (<mods>P != null)
			{
				Enumerator<IScriptMod> enumerator = <mods>P.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						IScriptMod current = enumerator.Current;
						if (current.ShouldRun(path))
						{
							flag = true;
							val = Enumerable.ToList<Token>(current.Modify(path, (global::System.Collections.Generic.IEnumerable<Token>)val));
						}
					}
				}
				finally
				{
					((global::System.IDisposable)enumerator).Dispose();
				}
			}
			if (!flag)
			{
				return false;
			}
			file.Tokens.Clear();
			file.Lines.Clear();
			Enumerator<Token> enumerator2 = val.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					Token current2 = enumerator2.Current;
					ConstantToken constantToken = current2 as ConstantToken;
					if (constantToken == null)
					{
						IdentifierToken identifierToken = current2 as IdentifierToken;
						if (identifierToken != null)
						{
							int num = file.Identifiers.FindIndex((Predicate<string>)((string x) => x == identifierToken.Name));
							if (num == -1)
							{
								num = file.Identifiers.Count;
								file.Identifiers.Add(identifierToken.Name);
							}
							identifierToken.AssociatedData = (uint)num;
						}
					}
					else
					{
						int num2 = file.Constants.FindIndex((Predicate<Variant>)((Variant x) => x.Equals(constantToken.Value)));
						if (num2 == -1)
						{
							num2 = file.Constants.Count;
							file.Constants.Add(constantToken.Value);
						}
						constantToken.AssociatedData = (uint)num2;
					}
					file.Tokens.Add(current2);
					uint num3 = (uint)(file.Tokens.Count - 1);
					file.Lines.Add(new ValueTuple<uint, uint>(num3, num3 & 0xFFFFFFu));
				}
			}
			finally
			{
				((global::System.IDisposable)enumerator2).Dispose();
			}
			return true;
		}

		public static List<Token> CreateSpecialTokens(GodotScriptFile file)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			List<Token> val = new List<Token>();
			Enumerator<Token> enumerator = file.Tokens.GetEnumerator();
			try
			{
				Token token;
				Token token2;
				for (; enumerator.MoveNext(); token2 = token, val.Add(token2))
				{
					Token current = enumerator.Current;
					switch (current.Type)
					{
					case TokenType.Identifier:
					{
						uint? associatedData = current.AssociatedData;
						if (associatedData.HasValue)
						{
							token = new IdentifierToken(current.Type, current.AssociatedData, file.Identifiers[(int)current.AssociatedData.GetValueOrDefault()]);
							continue;
						}
						break;
					}
					case TokenType.Constant:
						token = new ConstantToken(current.Type, current.AssociatedData, (Variant)file.Constants[(int)current.AssociatedData.GetValueOrDefault()].Clone());
						continue;
					}
					token = current;
				}
				return val;
			}
			finally
			{
				((global::System.IDisposable)enumerator).Dispose();
			}
		}
	}
	public static class ScriptTokenizer
	{
		[StructLayout(3)]
		[CompilerGenerated]
		private struct <>c__DisplayClass6_0
		{
			public string previous;

			public global::System.Collections.Generic.IEnumerator<string> enumerator;

			public List<Token> finalTokens;

			public List<Token> toFlush;

			public string idName;
		}

		[StructLayout(3)]
		[CompilerGenerated]
		private struct <>c__DisplayClass8_0
		{
			public StringBuilder builder;
		}

		[CompilerGenerated]
		private sealed class <SanitizeInput>d__7 : global::System.Collections.Generic.IEnumerable<string>, global::System.Collections.IEnumerable, global::System.Collections.Generic.IEnumerator<string>, global::System.Collections.IEnumerator, global::System.IDisposable
		{
			private int <>1__state;

			private string <>2__current;

			private int <>l__initialThreadId;

			private global::System.Collections.Generic.IEnumerable<string> tokens;

			public global::System.Collections.Generic.IEnumerable<string> <>3__tokens;

			private global::System.Collections.Generic.IEnumerator<string> <>7__wrap1;

			string global::System.Collections.Generic.IEnumerator<string>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object global::System.Collections.IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <SanitizeInput>d__7(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void global::System.IDisposable.Dispose()
			{
				int num = <>1__state;
				if (num == -3 || num == 1)
				{
					try
					{
					}
					finally
					{
						<>m__Finally1();
					}
				}
			}

			private bool MoveNext()
			{
				try
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						<>7__wrap1 = tokens.GetEnumerator();
						<>1__state = -3;
						break;
					case 1:
						<>1__state = -3;
						break;
					}
					while (((global::System.Collections.IEnumerator)<>7__wrap1).MoveNext())
					{
						string current = <>7__wrap1.Current;
						if (!(current != "\n") || !string.IsNullOrWhiteSpace(current))
						{
							<>2__current = current;
							<>1__state = 1;
							return true;
						}
					}
					<>m__Finally1();
					<>7__wrap1 = null;
					return false;
				}
				catch
				{
					//try-fault
					((global::System.IDisposable)this).Dispose();
					throw;
				}
			}

			bool global::System.Collections.IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			private void <>m__Finally1()
			{
				<>1__state = -1;
				if (<>7__wrap1 != null)
				{
					((global::System.IDisposable)<>7__wrap1).Dispose();
				}
			}

			[DebuggerHidden]
			void global::System.Collections.IEnumerator.Reset()
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			global::System.Collections.Generic.IEnumerator<string> global::System.Collections.Generic.IEnumerable<string>.GetEnumerator()
			{
				<SanitizeInput>d__7 <SanitizeInput>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					<SanitizeInput>d__ = this;
				}
				else
				{
					<SanitizeInput>d__ = new <SanitizeInput>d__7(0);
				}
				<SanitizeInput>d__.tokens = <>3__tokens;
				return <SanitizeInput>d__;
			}

			[DebuggerHidden]
			global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator()
			{
				return (global::System.Collections.IEnumerator)((global::System.Collections.Generic.IEnumerable<string>)this).GetEnumerator();
			}
		}

		[CompilerGenerated]
		private sealed class <Tokenize>d__6 : global::System.Collections.Generic.IEnumerable<Token>, global::System.Collections.IEnumerable, global::System.Collections.Generic.IEnumerator<Token>, global::System.Collections.IEnumerator, global::System.IDisposable
		{
			private int <>1__state;

			private Token <>2__current;

			private int <>l__initialThreadId;

			private string gdScript;

			public string <>3__gdScript;

			private uint baseIndent;

			public uint <>3__baseIndent;

			private Enumerator<Token> <>7__wrap1;

			Token global::System.Collections.Generic.IEnumerator<Token>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object global::System.Collections.IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <Tokenize>d__6(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void global::System.IDisposable.Dispose()
			{
				int num = <>1__state;
				if (num == -3 || num == 1)
				{
					try
					{
					}
					finally
					{
						<>m__Finally1();
					}
				}
			}

			private bool MoveNext()
			{
				//IL_035a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0305: Unknown result type (might be due to invalid IL or missing references)
				//IL_030a: Unknown result type (might be due to invalid IL or missing references)
				try
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
					{
						<>1__state = -1;
						<>c__DisplayClass6_0 <>c__DisplayClass6_ = default(<>c__DisplayClass6_0);
						<>c__DisplayClass6_.finalTokens = new List<Token>();
						global::System.Collections.Generic.IEnumerable<string> enumerable = SanitizeInput(TokenizeString(gdScript + " "));
						<>c__DisplayClass6_.previous = string.Empty;
						<>c__DisplayClass6_.idName = string.Empty;
						<>c__DisplayClass6_.toFlush = new List<Token>(2);
						<>c__DisplayClass6_.finalTokens.Add(new Token(TokenType.Newline, baseIndent));
						<>c__DisplayClass6_.enumerator = enumerable.GetEnumerator();
						bool flag = false;
						TokenType type = default(TokenType);
						bool value = default(bool);
						while (flag || ((global::System.Collections.IEnumerator)<>c__DisplayClass6_.enumerator).MoveNext())
						{
							flag = false;
							if (<>c__DisplayClass6_.enumerator.Current == "\n")
							{
								InsertNewLine(<>c__DisplayClass6_.enumerator, baseIndent, <>c__DisplayClass6_.toFlush);
								<Tokenize>g__endAndFlushId|6_1(ref <>c__DisplayClass6_);
							}
							else if (<>c__DisplayClass6_.enumerator.Current == "_")
							{
								BuildIdentifierName(<>c__DisplayClass6_.enumerator, <>c__DisplayClass6_.toFlush, out string found);
								if (found == string.Empty)
								{
									<Tokenize>g__endAndFlushId|6_1(ref <>c__DisplayClass6_);
									continue;
								}
								<>c__DisplayClass6_.idName += found;
								<Tokenize>g__end|6_0(ref <>c__DisplayClass6_);
							}
							else if (<>c__DisplayClass6_.enumerator.Current == "-" || char.IsDigit(<>c__DisplayClass6_.enumerator.Current[0]))
							{
								BuildNumber(<>c__DisplayClass6_.enumerator, <>c__DisplayClass6_.toFlush, out var foundFull);
								flag = !foundFull;
								<Tokenize>g__endAndFlushId|6_1(ref <>c__DisplayClass6_);
							}
							else if (BuiltinFunctions.Contains(<>c__DisplayClass6_.enumerator.Current))
							{
								<>c__DisplayClass6_.toFlush.Add(new Token(TokenType.BuiltInFunc, (uint)BuiltinFunctions.IndexOf(<>c__DisplayClass6_.enumerator.Current)));
								<Tokenize>g__endAndFlushId|6_1(ref <>c__DisplayClass6_);
							}
							else if (Tokens.TryGetValue(<>c__DisplayClass6_.enumerator.Current, ref type))
							{
								<>c__DisplayClass6_.toFlush.Add(new Token(type));
								<Tokenize>g__endAndFlushId|6_1(ref <>c__DisplayClass6_);
							}
							else if (<>c__DisplayClass6_.enumerator.Current.StartsWith('"'))
							{
								string current = <>c__DisplayClass6_.enumerator.Current;
								<>c__DisplayClass6_.toFlush.Add((Token)new ConstantToken(new StringVariant(current.Substring(1, current.Length - 2))));
								<Tokenize>g__endAndFlushId|6_1(ref <>c__DisplayClass6_);
							}
							else if (bool.TryParse(<>c__DisplayClass6_.enumerator.Current, ref value))
							{
								<>c__DisplayClass6_.toFlush.Add((Token)new ConstantToken(new BoolVariant(value)));
								<Tokenize>g__endAndFlushId|6_1(ref <>c__DisplayClass6_);
							}
							else
							{
								<>c__DisplayClass6_.idName += <>c__DisplayClass6_.enumerator.Current;
								<Tokenize>g__end|6_0(ref <>c__DisplayClass6_);
							}
						}
						<>c__DisplayClass6_.finalTokens.Add(new Token(TokenType.Newline, baseIndent));
						<>7__wrap1 = <>c__DisplayClass6_.finalTokens.GetEnumerator();
						<>1__state = -3;
						break;
					}
					case 1:
						<>1__state = -3;
						break;
					}
					if (<>7__wrap1.MoveNext())
					{
						Token current2 = <>7__wrap1.Current;
						<>2__current = current2;
						<>1__state = 1;
						return true;
					}
					<>m__Finally1();
					<>7__wrap1 = default(Enumerator<Token>);
					return false;
				}
				catch
				{
					//try-fault
					((global::System.IDisposable)this).Dispose();
					throw;
				}
			}

			bool global::System.Collections.IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			private void <>m__Finally1()
			{
				<>1__state = -1;
				((global::System.IDisposable)<>7__wrap1).Dispose();
			}

			[DebuggerHidden]
			void global::System.Collections.IEnumerator.Reset()
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			global::System.Collections.Generic.IEnumerator<Token> global::System.Collections.Generic.IEnumerable<Token>.GetEnumerator()
			{
				<Tokenize>d__6 <Tokenize>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					<Tokenize>d__ = this;
				}
				else
				{
					<Tokenize>d__ = new <Tokenize>d__6(0);
				}
				<Tokenize>d__.gdScript = <>3__gdScript;
				<Tokenize>d__.baseIndent = <>3__baseIndent;
				return <Tokenize>d__;
			}

			[DebuggerHidden]
			global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator()
			{
				return (global::System.Collections.IEnumerator)((global::System.Collections.Generic.IEnumerable<Token>)this).GetEnumerator();
			}
		}

		[CompilerGenerated]
		private sealed class <TokenizeString>d__8 : global::System.Collections.Generic.IEnumerable<string>, global::System.Collections.IEnumerable, global::System.Collections.Generic.IEnumerator<string>, global::System.Collections.IEnumerator, global::System.IDisposable
		{
			private int <>1__state;

			private string <>2__current;

			private int <>l__initialThreadId;

			private string text;

			public string <>3__text;

			private <>c__DisplayClass8_0 <>8__1;

			private int <i>5__2;

			private int <start>5__3;

			private Enumerator<string> <>7__wrap3;

			private string <delimiter>5__5;

			string global::System.Collections.Generic.IEnumerator<string>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object global::System.Collections.IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <TokenizeString>d__8(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void global::System.IDisposable.Dispose()
			{
				int num = <>1__state;
				if (num == -3 || (uint)(num - 6) <= 1u)
				{
					try
					{
					}
					finally
					{
						<>m__Finally1();
					}
				}
			}

			private bool MoveNext()
			{
				//IL_004b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0055: Expected O, but got Unknown
				//IL_0322: Unknown result type (might be due to invalid IL or missing references)
				//IL_0257: Unknown result type (might be due to invalid IL or missing references)
				//IL_025c: Unknown result type (might be due to invalid IL or missing references)
				try
				{
					bool flag;
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						<>8__1.builder = new StringBuilder(20);
						<i>5__2 = 0;
						goto IL_0399;
					case 1:
						<>1__state = -1;
						<>8__1.builder.Append('"');
						<i>5__2++;
						while (<i>5__2 < text.Length)
						{
							<>8__1.builder.Append(text[<i>5__2]);
							if (text[<i>5__2] == '"')
							{
								break;
							}
							<i>5__2++;
						}
						<>2__current = <TokenizeString>g__ClearBuilder|8_0(ref <>8__1);
						<>1__state = 2;
						return true;
					case 2:
						<>1__state = -1;
						goto IL_0387;
					case 3:
						<>1__state = -1;
						<start>5__3 = <i>5__2;
						<i>5__2++;
						while (<i>5__2 < text.Length && text[<i>5__2] == ' ')
						{
							<i>5__2++;
						}
						<i>5__2--;
						<>2__current = "\n";
						<>1__state = 4;
						return true;
					case 4:
						<>1__state = -1;
						<>2__current = $"{(<i>5__2 - <start>5__3) / 4}";
						<>1__state = 5;
						return true;
					case 5:
						<>1__state = -1;
						goto IL_0387;
					case 6:
						<>1__state = -3;
						<>2__current = <delimiter>5__5;
						<>1__state = 7;
						return true;
					case 7:
						<>1__state = -3;
						<i>5__2 += <delimiter>5__5.Length - 1;
						flag = true;
						goto IL_0316;
					case 8:
						<>1__state = -1;
						goto IL_0387;
					case 9:
						{
							<>1__state = -1;
							return false;
						}
						IL_0399:
						if (<i>5__2 < text.Length)
						{
							switch (text[<i>5__2])
							{
							case '"':
								<>2__current = <TokenizeString>g__ClearBuilder|8_0(ref <>8__1);
								<>1__state = 1;
								return true;
							case '\n':
								<>2__current = <TokenizeString>g__ClearBuilder|8_0(ref <>8__1);
								<>1__state = 3;
								return true;
							}
							flag = false;
							<>7__wrap3 = Symbols.GetEnumerator();
							<>1__state = -3;
							while (<>7__wrap3.MoveNext())
							{
								<delimiter>5__5 = <>7__wrap3.Current;
								if (Match(text, <i>5__2, <delimiter>5__5))
								{
									<>2__current = <TokenizeString>g__ClearBuilder|8_0(ref <>8__1);
									<>1__state = 6;
									return true;
								}
								<delimiter>5__5 = null;
							}
							goto IL_0316;
						}
						<>2__current = "\n";
						<>1__state = 9;
						return true;
						IL_0387:
						<i>5__2++;
						goto IL_0399;
						IL_0316:
						<>m__Finally1();
						<>7__wrap3 = default(Enumerator<string>);
						if (!flag)
						{
							if (text[<i>5__2] == ' ')
							{
								<>2__current = <TokenizeString>g__ClearBuilder|8_0(ref <>8__1);
								<>1__state = 8;
								return true;
							}
							<>8__1.builder.Append(text[<i>5__2]);
						}
						goto IL_0387;
					}
				}
				catch
				{
					//try-fault
					((global::System.IDisposable)this).Dispose();
					throw;
				}
			}

			bool global::System.Collections.IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			private void <>m__Finally1()
			{
				<>1__state = -1;
				((global::System.IDisposable)<>7__wrap3).Dispose();
			}

			[DebuggerHidden]
			void global::System.Collections.IEnumerator.Reset()
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			global::System.Collections.Generic.IEnumerator<string> global::System.Collections.Generic.IEnumerable<string>.GetEnumerator()
			{
				<TokenizeString>d__8 <TokenizeString>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					<TokenizeString>d__ = this;
				}
				else
				{
					<TokenizeString>d__ = new <TokenizeString>d__8(0);
				}
				<TokenizeString>d__.text = <>3__text;
				return <TokenizeString>d__;
			}

			[DebuggerHidden]
			global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator()
			{
				return (global::System.Collections.IEnumerator)((global::System.Collections.Generic.IEnumerable<string>)this).GetEnumerator();
			}
		}

		private static readonly Dictionary<string, TokenType> Tokens;

		private static readonly HashSet<string> Symbols;

		private static readonly List<string> BuiltinFunctions;

		private static void InsertNewLine(global::System.Collections.Generic.IEnumerator<string> enumerator, uint baseIndent, List<Token> toFlush)
		{
			if (((global::System.Collections.IEnumerator)enumerator).MoveNext())
			{
				uint num = uint.Parse(enumerator.Current);
				toFlush.Add(new Token(TokenType.Newline, num + baseIndent));
			}
		}

		private static void BuildIdentifierName(global::System.Collections.Generic.IEnumerator<string> enumerator, List<Token> toFlush, out string? found)
		{
			found = string.Empty;
			if (((global::System.Collections.IEnumerator)enumerator).MoveNext())
			{
				if (enumerator.Current == ":")
				{
					toFlush.Add(new Token(TokenType.Wildcard));
					toFlush.Add(new Token(TokenType.Semicolon));
				}
				else
				{
					found = "_" + enumerator.Current;
				}
			}
		}

		private static void BuildNumber(global::System.Collections.Generic.IEnumerator<string> enumerator, List<Token> toFlush, out bool foundFull)
		{
			foundFull = true;
			int num = 1;
			if (enumerator.Current == "-")
			{
				num = -1;
				if (!((global::System.Collections.IEnumerator)enumerator).MoveNext())
				{
					return;
				}
			}
			long num2 = default(long);
			if (!long.TryParse(enumerator.Current, ref num2))
			{
				toFlush.Add(new Token(TokenType.OpSub));
				foundFull = false;
			}
			else if (((global::System.Collections.IEnumerator)enumerator).MoveNext())
			{
				long num3 = default(long);
				if (enumerator.Current != ".")
				{
					toFlush.Add((Token)new ConstantToken(new IntVariant(num2 * num)));
					foundFull = false;
				}
				else if (((global::System.Collections.IEnumerator)enumerator).MoveNext() && long.TryParse(enumerator.Current, ref num3))
				{
					double num4 = (double)num2 + (double)num3 / Math.Pow(10.0, (double)num3.ToString().Length);
					toFlush.Add((Token)new ConstantToken(new RealVariant(num4 * (double)num)));
				}
			}
		}

		[IteratorStateMachine(typeof(<Tokenize>d__6))]
		public static global::System.Collections.Generic.IEnumerable<Token> Tokenize(string gdScript, uint baseIndent = 0u)
		{
			List<Token> finalTokens = new List<Token>();
			global::System.Collections.Generic.IEnumerable<string> enumerable = SanitizeInput(TokenizeString(gdScript + " "));
			string previous = string.Empty;
			string idName = string.Empty;
			List<Token> toFlush = new List<Token>(2);
			finalTokens.Add(new Token(TokenType.Newline, baseIndent));
			global::System.Collections.Generic.IEnumerator<string> enumerator = enumerable.GetEnumerator();
			bool flag = false;
			TokenType type = default(TokenType);
			bool value = default(bool);
			while (flag || ((global::System.Collections.IEnumerator)enumerator).MoveNext())
			{
				flag = false;
				if (enumerator.Current == "\n")
				{
					InsertNewLine(enumerator, baseIndent, toFlush);
					endAndFlushId();
				}
				else if (enumerator.Current == "_")
				{
					BuildIdentifierName(enumerator, toFlush, out string found);
					if (found == string.Empty)
					{
						endAndFlushId();
						continue;
					}
					idName += found;
					end();
				}
				else if (enumerator.Current == "-" || char.IsDigit(enumerator.Current[0]))
				{
					BuildNumber(enumerator, toFlush, out var foundFull);
					flag = !foundFull;
					endAndFlushId();
				}
				else if (BuiltinFunctions.Contains(enumerator.Current))
				{
					toFlush.Add(new Token(TokenType.BuiltInFunc, (uint)BuiltinFunctions.IndexOf(enumerator.Current)));
					endAndFlushId();
				}
				else if (Tokens.TryGetValue(enumerator.Current, ref type))
				{
					toFlush.Add(new Token(type));
					endAndFlushId();
				}
				else if (enumerator.Current.StartsWith('"'))
				{
					string current = enumerator.Current;
					toFlush.Add((Token)new ConstantToken(new StringVariant(current.Substring(1, current.Length - 2))));
					endAndFlushId();
				}
				else if (bool.TryParse(enumerator.Current, ref value))
				{
					toFlush.Add((Token)new ConstantToken(new BoolVariant(value)));
					endAndFlushId();
				}
				else
				{
					idName += enumerator.Current;
					end();
				}
			}
			finalTokens.Add(new Token(TokenType.Newline, baseIndent));
			Enumerator<Token> enumerator2 = finalTokens.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					yield return enumerator2.Current;
				}
			}
			finally
			{
				((global::System.IDisposable)enumerator2).Dispose();
			}
			[CompilerGenerated]
			void end()
			{
				previous = enumerator.Current;
				finalTokens.AddRange((global::System.Collections.Generic.IEnumerable<Token>)toFlush);
				toFlush.Clear();
			}
			[CompilerGenerated]
			void endAndFlushId()
			{
				if (idName != string.Empty)
				{
					finalTokens.Add((Token)new IdentifierToken(idName));
					idName = string.Empty;
				}
				end();
			}
		}

		[IteratorStateMachine(typeof(<SanitizeInput>d__7))]
		private static global::System.Collections.Generic.IEnumerable<string> SanitizeInput(global::System.Collections.Generic.IEnumerable<string> tokens)
		{
			global::System.Collections.Generic.IEnumerator<string> enumerator = tokens.GetEnumerator();
			try
			{
				while (((global::System.Collections.IEnumerator)enumerator).MoveNext())
				{
					string current = enumerator.Current;
					if (!(current != "\n") || !string.IsNullOrWhiteSpace(current))
					{
						yield return current;
					}
				}
			}
			finally
			{
				((global::System.IDisposable)enumerator)?.Dispose();
			}
		}

		[IteratorStateMachine(typeof(<TokenizeString>d__8))]
		private static global::System.Collections.Generic.IEnumerable<string> TokenizeString(string text)
		{
			StringBuilder builder = new StringBuilder(20);
			for (int j = 0; j < text.Length; j++)
			{
				switch (text[j])
				{
				case '"':
					yield return ClearBuilder();
					builder.Append('"');
					for (j++; j < text.Length; j++)
					{
						builder.Append(text[j]);
						if (text[j] == '"')
						{
							break;
						}
					}
					yield return ClearBuilder();
					continue;
				case '\n':
				{
					yield return ClearBuilder();
					int start = j;
					for (j++; j < text.Length && text[j] == ' '; j++)
					{
					}
					j--;
					yield return "\n";
					yield return $"{(j - start) / 4}";
					continue;
				}
				}
				bool flag = false;
				Enumerator<string> enumerator = Symbols.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						string delimiter = enumerator.Current;
						if (Match(text, j, delimiter))
						{
							yield return ClearBuilder();
							yield return delimiter;
							j += delimiter.Length - 1;
							flag = true;
							break;
						}
					}
				}
				finally
				{
					((global::System.IDisposable)enumerator).Dispose();
				}
				if (!flag)
				{
					if (text[j] == ' ')
					{
						yield return ClearBuilder();
					}
					else
					{
						builder.Append(text[j]);
					}
				}
			}
			yield return "\n";
			[CompilerGenerated]
			string ClearBuilder()
			{
				string result = ((object)builder).ToString();
				builder.Clear();
				return result;
			}
		}

		private static bool Match(string text, int index, string match)
		{
			return string.Compare(text, index, match, 0, match.Length) == 0;
		}

		static ScriptTokenizer()
		{
			Dictionary<string, TokenType> obj = new Dictionary<string, TokenType>();
			obj.Add("continue", TokenType.CfContinue);
			obj.Add("return", TokenType.CfReturn);
			obj.Add("break", TokenType.CfBreak);
			obj.Add("match", TokenType.CfMatch);
			obj.Add("while", TokenType.CfWhile);
			obj.Add("elif", TokenType.CfElif);
			obj.Add("else", TokenType.CfElse);
			obj.Add("pass", TokenType.CfPass);
			obj.Add("for", TokenType.CfFor);
			obj.Add("if", TokenType.CfIf);
			obj.Add("const", TokenType.PrConst);
			obj.Add("var", TokenType.PrVar);
			obj.Add("func", TokenType.PrFunction);
			obj.Add("class", TokenType.PrClass);
			obj.Add("extends", TokenType.PrExtends);
			obj.Add("is", TokenType.PrIs);
			obj.Add("as", TokenType.PrAs);
			obj.Add("@onready", TokenType.PrOnready);
			obj.Add("@tool", TokenType.PrTool);
			obj.Add("@export", TokenType.PrExport);
			obj.Add("setget", TokenType.PrSetget);
			obj.Add("static", TokenType.PrStatic);
			obj.Add("void", TokenType.PrVoid);
			obj.Add("enum", TokenType.PrEnum);
			obj.Add("preload", TokenType.PrPreload);
			obj.Add("assert", TokenType.PrAssert);
			obj.Add("signal", TokenType.PrSignal);
			obj.Add("breakpoint", TokenType.PrBreakpoint);
			obj.Add("sync", TokenType.PrSync);
			obj.Add("remote", TokenType.PrRemote);
			obj.Add("master", TokenType.PrMaster);
			obj.Add("slave", TokenType.PrSlave);
			obj.Add("puppet", TokenType.PrPuppet);
			obj.Add("remotesync", TokenType.PrRemotesync);
			obj.Add("mastersync", TokenType.PrMastersync);
			obj.Add("puppetsync", TokenType.PrPuppetsync);
			obj.Add("\n", TokenType.Newline);
			obj.Add("PI", TokenType.ConstPi);
			obj.Add("TAU", TokenType.ConstTau);
			obj.Add("INF", TokenType.ConstInf);
			obj.Add("NAN", TokenType.ConstNan);
			obj.Add("error", TokenType.Error);
			obj.Add("cursor", TokenType.Cursor);
			obj.Add("in", TokenType.OpIn);
			obj.Add("_", TokenType.Wildcard);
			obj.Add("[", TokenType.BracketOpen);
			obj.Add("]", TokenType.BracketClose);
			obj.Add("{", TokenType.CurlyBracketOpen);
			obj.Add("}", TokenType.CurlyBracketOpen);
			obj.Add("(", TokenType.ParenthesisOpen);
			obj.Add(")", TokenType.ParenthesisClose);
			obj.Add(",", TokenType.Comma);
			obj.Add(";", TokenType.Semicolon);
			obj.Add(".", TokenType.Period);
			obj.Add("?", TokenType.QuestionMark);
			obj.Add(":", TokenType.Colon);
			obj.Add("$", TokenType.Dollar);
			obj.Add("->", TokenType.ForwardArrow);
			obj.Add(">>=", TokenType.OpAssignShiftRight);
			obj.Add("<<=", TokenType.OpAssignShiftLeft);
			obj.Add(">>", TokenType.OpShiftRight);
			obj.Add("<<", TokenType.OpShiftLeft);
			obj.Add("==", TokenType.OpEqual);
			obj.Add("!=", TokenType.OpNotEqual);
			obj.Add("&&", TokenType.OpAnd);
			obj.Add("||", TokenType.OpOr);
			obj.Add("!", TokenType.OpNot);
			obj.Add("+=", TokenType.OpAssignAdd);
			obj.Add("-=", TokenType.OpAssignSub);
			obj.Add("*=", TokenType.OpAssignMul);
			obj.Add("/=", TokenType.OpAssignDiv);
			obj.Add("%=", TokenType.OpAssignMod);
			obj.Add("&=", TokenType.OpAssignBitAnd);
			obj.Add("|=", TokenType.OpAssignBitOr);
			obj.Add("^=", TokenType.OpAssignBitXor);
			obj.Add("+", TokenType.OpAdd);
			obj.Add("-", TokenType.OpSub);
			obj.Add("*", TokenType.OpMul);
			obj.Add("/", TokenType.OpDiv);
			obj.Add("%", TokenType.OpMod);
			obj.Add("~", TokenType.OpBitInvert);
			obj.Add("&", TokenType.OpBitAnd);
			obj.Add("|", TokenType.OpBitOr);
			obj.Add("^", TokenType.OpBitXor);
			obj.Add("<=", TokenType.OpLessEqual);
			obj.Add(">=", TokenType.OpGreaterEqual);
			obj.Add("<", TokenType.OpLess);
			obj.Add(">", TokenType.OpGreater);
			obj.Add("=", TokenType.OpAssign);
			Tokens = obj;
			HashSet<string> obj2 = new HashSet<string>();
			obj2.Add("->");
			obj2.Add(">>=");
			obj2.Add("<<=");
			obj2.Add(">>");
			obj2.Add("<<");
			obj2.Add("==");
			obj2.Add("!=");
			obj2.Add("&&");
			obj2.Add("||");
			obj2.Add("!");
			obj2.Add("+=");
			obj2.Add("-=");
			obj2.Add("*=");
			obj2.Add("/=");
			obj2.Add("%=");
			obj2.Add("&=");
			obj2.Add("|=");
			obj2.Add("^=");
			obj2.Add("_");
			obj2.Add("[");
			obj2.Add("]");
			obj2.Add("{");
			obj2.Add("}");
			obj2.Add("(");
			obj2.Add(")");
			obj2.Add(",");
			obj2.Add(";");
			obj2.Add(".");
			obj2.Add("?");
			obj2.Add(":");
			obj2.Add("$");
			obj2.Add("+");
			obj2.Add("-");
			obj2.Add("*");
			obj2.Add("/");
			obj2.Add("%");
			obj2.Add("~");
			obj2.Add("&");
			obj2.Add("|");
			obj2.Add("^");
			obj2.Add("<=");
			obj2.Add(">=");
			obj2.Add("<");
			obj2.Add(">");
			obj2.Add("=");
			Symbols = obj2;
			BuiltinFunctions = Enumerable.ToList<string>((global::System.Collections.Generic.IEnumerable<string>)global::System.Enum.GetNames<BuiltinFunction>());
		}

		[CompilerGenerated]
		internal static void <Tokenize>g__end|6_0(ref <>c__DisplayClass6_0 P_0)
		{
			P_0.previous = P_0.enumerator.Current;
			P_0.finalTokens.AddRange((global::System.Collections.Generic.IEnumerable<Token>)P_0.toFlush);
			P_0.toFlush.Clear();
		}

		[CompilerGenerated]
		internal static void <Tokenize>g__endAndFlushId|6_1(ref <>c__DisplayClass6_0 P_0)
		{
			if (P_0.idName != string.Empty)
			{
				P_0.finalTokens.Add((Token)new IdentifierToken(P_0.idName));
				P_0.idName = string.Empty;
			}
			<Tokenize>g__end|6_0(ref P_0);
		}

		[CompilerGenerated]
		internal static string <TokenizeString>g__ClearBuilder|8_0(ref <>c__DisplayClass8_0 P_0)
		{
			string result = ((object)P_0.builder).ToString();
			P_0.builder.Clear();
			return result;
		}
	}
	public class TokenConsumer : IWaiter
	{
		[CompilerGenerated]
		private Func<Token, bool> <check>P;

		[field: CompilerGenerated]
		public bool Matched
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		[field: CompilerGenerated]
		public bool Ready
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		public TokenConsumer(Func<Token, bool> check)
		{
			<check>P = check;
			base..ctor();
		}

		public void Reset()
		{
			Matched = false;
			Ready = false;
		}

		public void SetReady()
		{
			Ready = true;
		}

		public bool Check(Token token)
		{
			if (!Matched && Ready)
			{
				if (<check>P.Invoke(token))
				{
					Matched = true;
					return false;
				}
				return true;
			}
			return false;
		}
	}
	public class TokenWaiter : IWaiter
	{
		[CompilerGenerated]
		private Func<Token, bool> <check>P;

		[CompilerGenerated]
		private bool <waitForReady>P;

		[field: CompilerGenerated]
		public bool Matched
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		[field: CompilerGenerated]
		public bool Ready
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		public TokenWaiter(Func<Token, bool> check, bool waitForReady = false)
		{
			<check>P = check;
			<waitForReady>P = waitForReady;
			Ready = !<waitForReady>P;
			base..ctor();
		}

		public void Reset()
		{
			Matched = false;
			Ready = !<waitForReady>P;
		}

		public void SetReady()
		{
			Ready = true;
		}

		public bool Check(Token token)
		{
			if (!Matched && Ready && <check>P.Invoke(token))
			{
				Matched = true;
				return true;
			}
			return false;
		}
	}
}
namespace GDWeave.Godot
{
	public enum BuiltinFunction : uint
	{
		MathSin,
		MathCos,
		MathTan,
		MathSinh,
		MathCosh,
		MathTanh,
		MathAsin,
		MathAcos,
		MathAtan,
		MathAtan2,
		MathSqrt,
		MathFmod,
		MathFposmod,
		MathPosmod,
		MathFloor,
		MathCeil,
		MathRound,
		MathAbs,
		MathSign,
		MathPow,
		MathLog,
		MathExp,
		MathIsnan,
		MathIsinf,
		MathIsequalapprox,
		MathIszeroapprox,
		MathEase,
		MathDecimals,
		MathStepDecimals,
		MathStepify,
		MathLerp,
		MathLerpAngle,
		MathInverseLerp,
		MathRangeLerp,
		MathSmoothstep,
		MathMoveToward,
		MathDectime,
		MathRandomize,
		MathRand,
		MathRandf,
		MathRandom,
		MathSeed,
		MathRandseed,
		MathDeg2Rad,
		MathRad2Deg,
		MathLinear2Db,
		MathDb2Linear,
		MathPolar2Cartesian,
		MathCartesian2Polar,
		MathWrap,
		MathWrapf,
		LogicMax,
		LogicMin,
		LogicClamp,
		LogicNearestPo2,
		ObjWeakref,
		FuncFuncref,
		TypeConvert,
		TypeOf,
		TypeExists,
		TextChar,
		TextOrd,
		TextStr,
		TextPrint,
		TextPrintTabbed,
		TextPrintSpaced,
		TextPrinterr,
		TextPrintraw,
		TextPrintDebug,
		PushError,
		PushWarning,
		VarToStr,
		StrToVar,
		VarToBytes,
		BytesToVar,
		GenRange,
		ResourceLoad,
		Inst2Dict,
		Dict2Inst,
		ValidateJson,
		ParseJson,
		ToJson,
		Hash,
		Color8,
		Colorn,
		PrintStack,
		GetStack,
		InstanceFromId,
		Len,
		IsInstanceValid,
		DeepEqual,
		FuncMax
	}
	public class GodotScriptFile
	{
		public const uint Magic = 1129530439u;

		public const uint Version = 13u;

		public const byte UselessXorKey = 182;

		public const uint TokenLineMask = 16777215u;

		public List<string> Identifiers = new List<string>();

		public List<Variant> Constants = new List<Variant>();

		public List<ValueTuple<uint, uint>> Lines = new List<ValueTuple<uint, uint>>();

		public List<Token> Tokens = new List<Token>();

		public GodotScriptFile(BinaryReader br)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			if (br.ReadUInt32() != 1129530439)
			{
				throw new InvalidDataException("Invalid file header");
			}
			if (br.ReadUInt32() != 13)
			{
				throw new InvalidDataException("Invalid file version");
			}
			uint num = br.ReadUInt32();
			uint num2 = br.ReadUInt32();
			uint num3 = br.ReadUInt32();
			uint num4 = br.ReadUInt32();
			for (int i = 0; i < num; i++)
			{
				uint num5 = br.ReadUInt32();
				byte[] array = br.ReadBytes((int)num5);
				for (int j = 0; j < num5; j++)
				{
					array[j] ^= 182;
				}
				string str = Encoding.UTF8.GetString(array);
				MemoryUtils.TrimNullTerminator(ref str);
				Identifiers.Add(str);
			}
			for (int k = 0; k < num2; k++)
			{
				Variant variant = VariantParser.Read(br);
				Constants.Add(variant);
			}
			for (int l = 0; l < num3; l++)
			{
				uint num6 = br.ReadUInt32();
				uint num7 = br.ReadUInt32();
				Lines.Add(new ValueTuple<uint, uint>(num6, num7));
			}
			for (int m = 0; m < num4; m++)
			{
				Tokens.Add(TokenParser.Read(br));
			}
		}

		public void Write(BinaryWriter bw)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			bw.Write(1129530439u);
			bw.Write(13u);
			bw.Write(Identifiers.Count);
			bw.Write(Constants.Count);
			bw.Write(Lines.Count);
			bw.Write(Tokens.Count);
			Enumerator<string> enumerator = Identifiers.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					string current = enumerator.Current;
					byte[] bytes = Encoding.UTF8.GetBytes(current + "\0");
					int num = 4 - bytes.Length % 4;
					if (num == 4)
					{
						num = 0;
					}
					for (int i = 0; i < bytes.Length; i++)
					{
						bytes[i] ^= 182;
					}
					bw.Write((uint)(bytes.Length + num));
					bw.Write(bytes);
					if (num > 0)
					{
						bw.Write(new byte[num]);
					}
				}
			}
			finally
			{
				((global::System.IDisposable)enumerator).Dispose();
			}
			Enumerator<Variant> enumerator2 = Constants.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					Variant current2 = enumerator2.Current;
					VariantParser.Write(bw, current2);
				}
			}
			finally
			{
				((global::System.IDisposable)enumerator2).Dispose();
			}
			Enumerator<ValueTuple<uint, uint>> enumerator3 = Lines.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					ValueTuple<uint, uint> current3 = enumerator3.Current;
					uint item = current3.Item1;
					uint item2 = current3.Item2;
					bw.Write(item);
					bw.Write(item2);
				}
			}
			finally
			{
				((global::System.IDisposable)enumerator3).Dispose();
			}
			Enumerator<Token> enumerator4 = Tokens.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					Token current4 = enumerator4.Current;
					TokenParser.Write(bw, current4);
				}
			}
			finally
			{
				((global::System.IDisposable)enumerator4).Dispose();
			}
		}
	}
	public class Token
	{
		public TokenType Type;

		public uint? AssociatedData;

		public Token(TokenType type, uint? associatedData = null)
		{
			Type = type;
			AssociatedData = associatedData;
		}

		public virtual string ToString()
		{
			return $"Token({Type}, {AssociatedData})";
		}
	}
	[RequiredMember]
	public class ConstantToken : Token
	{
		[RequiredMember]
		public Variant Value;

		[SetsRequiredMembers]
		public ConstantToken(Variant value)
			: base(TokenType.Constant)
		{
			Value = value;
		}

		[SetsRequiredMembers]
		public ConstantToken(TokenType type, uint? associatedData, Variant value)
			: base(type, associatedData)
		{
			Value = value;
		}

		public override string ToString()
		{
			return $"ConstantToken({Type}, {AssociatedData}, {Value})";
		}
	}
	[RequiredMember]
	public class IdentifierToken : Token
	{
		[RequiredMember]
		public string Name;

		[SetsRequiredMembers]
		public IdentifierToken(string name)
			: base(TokenType.Identifier)
		{
			Name = name;
		}

		[SetsRequiredMembers]
		public IdentifierToken(TokenType type, uint? associatedData, string name)
			: base(type, associatedData)
		{
			Name = name;
		}

		public override string ToString()
		{
			return $"IdentifierToken({Type}, {AssociatedData}, {Name})";
		}
	}
	public class TokenParser
	{
		public const int TokenByteMask = 128;

		public const int TokenBits = 8;

		public const int TokenMask = 255;

		public static Token Read(BinaryReader br)
		{
			byte b = br.ReadByte();
			if ((b & 0x80u) != 0)
			{
				br.BaseStream.Seek(-1L, (SeekOrigin)1);
				int num = (int)(br.ReadUInt32() & -129);
				TokenType type = (TokenType)(num & 0xFF);
				uint num2 = (uint)num >> 8;
				return new Token(type, num2);
			}
			return new Token((TokenType)b);
		}

		public static void Write(BinaryWriter bw, Token token)
		{
			if (token.AssociatedData.HasValue)
			{
				byte[] bytes = BitConverter.GetBytes((uint)token.Type | (token.AssociatedData.Value << 8) | 0x80u);
				for (int i = 0; i < 4; i++)
				{
					bw.Write(bytes[i]);
				}
			}
			else
			{
				bw.Write((byte)token.Type);
			}
		}
	}
	public enum TokenType
	{
		Empty,
		Identifier,
		Constant,
		Self,
		BuiltInType,
		BuiltInFunc,
		OpIn,
		OpEqual,
		OpNotEqual,
		OpLess,
		OpLessEqual,
		OpGreater,
		OpGreaterEqual,
		OpAnd,

GDWeave/core/Iced.dll

Decompiled 3 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using Iced.Intel.BlockEncoderInternal;
using Iced.Intel.DecoderInternal;
using Iced.Intel.EncoderInternal;
using Iced.Intel.FastFormatterInternal;
using Iced.Intel.FormatterInternal;
using Iced.Intel.GasFormatterInternal;
using Iced.Intel.InstructionInfoInternal;
using Iced.Intel.IntelFormatterInternal;
using Iced.Intel.Internal;
using Iced.Intel.MasmFormatterInternal;
using Iced.Intel.NasmFormatterInternal;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("iced project and contributors <https://github.com/icedland>")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (C) 2018-present iced project and contributors")]
[assembly: AssemblyDescription("x86/x64 disassembler, assembler, instruction decoder")]
[assembly: AssemblyFileVersion("1.17.0.0")]
[assembly: AssemblyInformationalVersion("1.17.0+c7aa5116314e90d391a3350878f9fb99192aafb6")]
[assembly: AssemblyProduct("Iced")]
[assembly: AssemblyTitle("Iced")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/icedland/iced")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.17.0.0")]
[module: UnverifiableCode]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
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 NullablePublicOnlyAttribute : Attribute
	{
		public readonly bool IncludesInternals;

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
}
namespace Iced.Intel
{
	public class Assembler
	{
		[Flags]
		private enum PrefixFlags
		{
			None = 0,
			Lock = 1,
			Repe = 2,
			Repne = 4,
			Notrack = 8,
			PreferVex = 0x10,
			PreferEvex = 0x20
		}

		private readonly InstructionList instructions;

		private ulong currentLabelId;

		private Label currentLabel;

		private Label currentAnonLabel;

		private Label nextAnonLabel;

		private bool definedAnonLabel;

		private PrefixFlags prefixFlags;

		public int Bitness { get; }

		public bool PreferVex { get; set; }

		public bool PreferShortBranch { get; set; }

		internal bool InstructionPreferVex
		{
			get
			{
				if ((prefixFlags & (PrefixFlags.PreferVex | PrefixFlags.PreferEvex)) != 0)
				{
					return (prefixFlags & PrefixFlags.PreferVex) != 0;
				}
				return PreferVex;
			}
		}

		public IReadOnlyList<Instruction> Instructions => instructions;

		public Label CurrentLabel => currentLabel;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public Label B
		{
			get
			{
				if (currentAnonLabel.IsEmpty)
				{
					throw new InvalidOperationException("No anonymous label has been created yet");
				}
				return currentAnonLabel;
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public Label F
		{
			get
			{
				if (nextAnonLabel.IsEmpty)
				{
					nextAnonLabel = CreateLabel();
				}
				return nextAnonLabel;
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public Assembler @lock
		{
			get
			{
				prefixFlags |= PrefixFlags.Lock;
				return this;
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public Assembler xacquire
		{
			get
			{
				prefixFlags |= PrefixFlags.Repne;
				return this;
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public Assembler xrelease
		{
			get
			{
				prefixFlags |= PrefixFlags.Repe;
				return this;
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public Assembler rep
		{
			get
			{
				prefixFlags |= PrefixFlags.Repe;
				return this;
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public Assembler repe
		{
			get
			{
				prefixFlags |= PrefixFlags.Repe;
				return this;
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public Assembler repz => repe;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public Assembler repne
		{
			get
			{
				prefixFlags |= PrefixFlags.Repne;
				return this;
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public Assembler repnz => repne;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public Assembler bnd
		{
			get
			{
				prefixFlags |= PrefixFlags.Repne;
				return this;
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public Assembler notrack
		{
			get
			{
				prefixFlags |= PrefixFlags.Notrack;
				return this;
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public Assembler vex
		{
			get
			{
				prefixFlags |= PrefixFlags.PreferVex;
				return this;
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public Assembler evex
		{
			get
			{
				prefixFlags |= PrefixFlags.PreferEvex;
				return this;
			}
		}

		public Assembler(int bitness)
		{
			if (bitness != 16 && bitness != 32 && bitness != 64)
			{
				throw new ArgumentOutOfRangeException("bitness");
			}
			Bitness = bitness;
			instructions = new InstructionList();
			currentLabelId = 0uL;
			currentLabel = default(Label);
			currentAnonLabel = default(Label);
			nextAnonLabel = default(Label);
			definedAnonLabel = false;
			prefixFlags = PrefixFlags.None;
			PreferVex = true;
			PreferShortBranch = true;
		}

		public void Reset()
		{
			instructions.Clear();
			currentLabelId = 0uL;
			currentLabel = default(Label);
			currentAnonLabel = default(Label);
			nextAnonLabel = default(Label);
			definedAnonLabel = false;
			prefixFlags = PrefixFlags.None;
		}

		public Label CreateLabel(string? name = null)
		{
			currentLabelId++;
			return new Label(name, currentLabelId);
		}

		public void Label(ref Label label)
		{
			if (label.IsEmpty)
			{
				throw new ArgumentException("Invalid label. Must be created via CreateLabel", "label");
			}
			if (label.InstructionIndex >= 0)
			{
				throw new ArgumentException($"Cannot reuse label. The specified label is already associated with an instruction at index {label.InstructionIndex}.", "label");
			}
			if (!currentLabel.IsEmpty)
			{
				throw new ArgumentException("At most one label per instruction is allowed");
			}
			label.InstructionIndex = instructions.Count;
			currentLabel = label;
		}

		public void AnonymousLabel()
		{
			if (definedAnonLabel)
			{
				throw new InvalidOperationException("At most one anonymous label per instruction is allowed");
			}
			if (nextAnonLabel.IsEmpty)
			{
				currentAnonLabel = CreateLabel();
			}
			else
			{
				currentAnonLabel = nextAnonLabel;
			}
			nextAnonLabel = default(Label);
			definedAnonLabel = true;
		}

		public void AddInstruction(Instruction instruction)
		{
			AddInstruction(ref instruction);
		}

		public void AddInstruction(ref Instruction instruction)
		{
			if (!currentLabel.IsEmpty && definedAnonLabel)
			{
				throw new InvalidOperationException("You can't create both an anonymous label and a normal label");
			}
			if (!currentLabel.IsEmpty)
			{
				instruction.IP = currentLabel.Id;
			}
			else if (definedAnonLabel)
			{
				instruction.IP = currentAnonLabel.Id;
			}
			if (prefixFlags != 0)
			{
				if ((prefixFlags & PrefixFlags.Lock) != 0)
				{
					instruction.HasLockPrefix = true;
				}
				if ((prefixFlags & PrefixFlags.Repe) != 0)
				{
					instruction.HasRepePrefix = true;
				}
				else if ((prefixFlags & PrefixFlags.Repne) != 0)
				{
					instruction.HasRepnePrefix = true;
				}
				if ((prefixFlags & PrefixFlags.Notrack) != 0)
				{
					instruction.SegmentPrefix = Register.DS;
				}
			}
			instructions.Add(in instruction);
			currentLabel = default(Label);
			definedAnonLabel = false;
			prefixFlags = PrefixFlags.None;
		}

		private void AddInstruction(Instruction instruction, AssemblerOperandFlags flags)
		{
			if (flags != 0)
			{
				if ((flags & AssemblerOperandFlags.Broadcast) != 0)
				{
					instruction.IsBroadcast = true;
				}
				if ((flags & AssemblerOperandFlags.Zeroing) != 0)
				{
					instruction.ZeroingMasking = true;
				}
				if ((flags & AssemblerOperandFlags.K7) != 0)
				{
					instruction.OpMask = (Register)(173 + ((int)(flags & AssemblerOperandFlags.K7) >> 6));
				}
				if ((flags & AssemblerOperandFlags.SuppressAllExceptions) != 0)
				{
					instruction.SuppressAllExceptions = true;
				}
				if ((flags & AssemblerOperandFlags.RoundControlMask) != 0)
				{
					instruction.RoundingControl = (RoundingControl)((int)(flags & AssemblerOperandFlags.RoundControlMask) >> 3);
				}
			}
			AddInstruction(ref instruction);
		}

		public void db(byte[] array)
		{
			if (array == null)
			{
				ThrowHelper.ThrowArgumentNullException_array();
			}
			db(array, 0, array.Length);
		}

		public void db(byte[] array, int index, int length)
		{
			if (array == null)
			{
				ThrowHelper.ThrowArgumentNullException_array();
			}
			if (index < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException_index();
			}
			if (length < 0 || (uint)(index + length) > (uint)array.Length)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException_length();
			}
			int result;
			int num = Math.DivRem(length, 16, out result);
			int num2 = index;
			for (int i = 0; i < num; i++)
			{
				AddInstruction(Instruction.CreateDeclareByte(array, num2, 16));
				num2 += 16;
			}
			if (result > 0)
			{
				AddInstruction(Instruction.CreateDeclareByte(array, num2, result));
			}
		}

		public void db(ReadOnlySpan<byte> data)
		{
			int result;
			int num = Math.DivRem(data.Length, 16, out result);
			int num2 = 0;
			for (int i = 0; i < num; i++)
			{
				AddInstruction(Instruction.CreateDeclareByte(data.Slice(num2, 16)));
				num2 += 16;
			}
			if (result > 0)
			{
				AddInstruction(Instruction.CreateDeclareByte(data.Slice(num2, result)));
			}
		}

		public void call(ushort selector, uint offset)
		{
			AddInstruction(Instruction.CreateBranch((Bitness >= 32) ? Code.Call_ptr1632 : Code.Call_ptr1616, selector, offset));
		}

		public void jmp(ushort selector, uint offset)
		{
			AddInstruction(Instruction.CreateBranch((Bitness >= 32) ? Code.Jmp_ptr1632 : Code.Jmp_ptr1616, selector, offset));
		}

		public void xlatb()
		{
			MemoryOperand memory = new MemoryOperand(Bitness switch
			{
				64 => Register.RBX, 
				32 => Register.EBX, 
				_ => Register.BX, 
			}, Register.AL);
			AddInstruction(Instruction.Create(Code.Xlat_m8, in memory));
		}

		public void nop(int sizeInBytes)
		{
			if (sizeInBytes < 0)
			{
				throw new ArgumentOutOfRangeException("sizeInBytes");
			}
			if (prefixFlags != 0)
			{
				throw new InvalidOperationException("No prefixes are allowed");
			}
			if (sizeInBytes != 0)
			{
				int result;
				int num = Math.DivRem(sizeInBytes, 9, out result);
				for (int i = 0; i < num; i++)
				{
					AppendNop(9);
				}
				if (result > 0)
				{
					AppendNop(result);
				}
			}
			void AppendNop(int amount)
			{
				switch (amount)
				{
				case 1:
					db(144);
					break;
				case 2:
					db(102, 144);
					break;
				case 3:
					db(15, 31, 0);
					break;
				case 4:
					db(15, 31, 64, 0);
					break;
				case 5:
					if (Bitness != 16)
					{
						db(15, 31, 68, 0, 0);
					}
					else
					{
						db(15, 31, 128, 0, 0);
					}
					break;
				case 6:
					if (Bitness != 16)
					{
						db(102, 15, 31, 68, 0, 0);
					}
					else
					{
						db(102, 15, 31, 128, 0, 0);
					}
					break;
				case 7:
					if (Bitness != 16)
					{
						db(15, 31, 128, 0, 0, 0, 0);
					}
					else
					{
						db(103, 102, 15, 31, 68, 0, 0);
					}
					break;
				case 8:
					if (Bitness != 16)
					{
						db(15, 31, 132, 0, 0, 0, 0, 0);
					}
					else
					{
						db(103, 15, 31, 128, 0, 0, 0, 0);
					}
					break;
				case 9:
					if (Bitness != 16)
					{
						db(102, 15, 31, 132, 0, 0, 0, 0, 0);
					}
					else
					{
						db(103, 15, 31, 132, 0, 0, 0, 0, 0);
					}
					break;
				}
			}
		}

		public AssemblerResult Assemble(CodeWriter writer, ulong rip, BlockEncoderOptions options = BlockEncoderOptions.None)
		{
			if (!TryAssemble(writer, rip, out string errorMessage, out AssemblerResult assemblerResult, options))
			{
				throw new InvalidOperationException(errorMessage);
			}
			return assemblerResult;
		}

		public bool TryAssemble(CodeWriter writer, ulong rip, [NotNullWhen(false)] out string? errorMessage, out AssemblerResult assemblerResult, BlockEncoderOptions options = BlockEncoderOptions.None)
		{
			if (writer == null)
			{
				ThrowHelper.ThrowArgumentNullException_writer();
			}
			assemblerResult = default(AssemblerResult);
			if (prefixFlags != 0)
			{
				errorMessage = $"Unused prefixes {prefixFlags}. You must emit an instruction after using an instruction prefix.";
				return false;
			}
			if (!currentLabel.IsEmpty)
			{
				errorMessage = $"Unused label {currentLabel}. You must emit an instruction after emitting a label.";
				return false;
			}
			if (definedAnonLabel)
			{
				errorMessage = "Unused anonymous label. You must emit an instruction after emitting a label.";
				return false;
			}
			if (!nextAnonLabel.IsEmpty)
			{
				errorMessage = "Found an @F anonymous label reference but there was no call to AnonymousLabel";
				return false;
			}
			InstructionBlock[] blocks = new InstructionBlock[1]
			{
				new InstructionBlock(writer, instructions, rip)
			};
			if (BlockEncoder.TryEncode(Bitness, blocks, out errorMessage, out BlockEncoderResult[] result, options))
			{
				assemblerResult = new AssemblerResult(result);
				return true;
			}
			assemblerResult = new AssemblerResult(Array2.Empty<BlockEncoderResult>());
			return false;
		}

		private InvalidOperationException NoOpCodeFoundFor(Mnemonic mnemonic, params object[] argNames)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("Unable to calculate an OpCode for `" + mnemonic.ToString().ToLowerInvariant());
			for (int i = 0; i < argNames.Length; i++)
			{
				stringBuilder.Append((i == 0) ? " " : ", ");
				stringBuilder.Append(argNames[i]);
			}
			stringBuilder.Append($"`. Combination of arguments and/or current bitness {Bitness} is not compatible with any existing OpCode encoding.");
			return new InvalidOperationException(stringBuilder.ToString());
		}

		public void aaa()
		{
			AddInstruction(Instruction.Create(Code.Aaa));
		}

		public void aad(sbyte imm)
		{
			AddInstruction(Instruction.Create(Code.Aad_imm8, imm));
		}

		public void aad(byte imm)
		{
			AddInstruction(Instruction.Create(Code.Aad_imm8, (uint)imm));
		}

		public void aam(sbyte imm)
		{
			AddInstruction(Instruction.Create(Code.Aam_imm8, imm));
		}

		public void aam(byte imm)
		{
			AddInstruction(Instruction.Create(Code.Aam_imm8, (uint)imm));
		}

		public void aas()
		{
			AddInstruction(Instruction.Create(Code.Aas));
		}

		public void adc(AssemblerRegister8 dst, AssemblerRegister8 src)
		{
			AddInstruction(Instruction.Create(Code.Adc_rm8_r8, dst, src));
		}

		public void adc(AssemblerMemoryOperand dst, AssemblerRegister8 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Adc_rm8_r8, in memory, src));
		}

		public void adc(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Adc_rm16_r16, dst, src));
		}

		public void adc(AssemblerMemoryOperand dst, AssemblerRegister16 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Adc_rm16_r16, in memory, src));
		}

		public void adc(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Adc_rm32_r32, dst, src));
		}

		public void adc(AssemblerMemoryOperand dst, AssemblerRegister32 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Adc_rm32_r32, in memory, src));
		}

		public void adc(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Adc_rm64_r64, dst, src));
		}

		public void adc(AssemblerMemoryOperand dst, AssemblerRegister64 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Adc_rm64_r64, in memory, src));
		}

		public void adc(AssemblerRegister8 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Adc_r8_rm8, register, in memory));
		}

		public void adc(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Adc_r16_rm16, register, in memory));
		}

		public void adc(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Adc_r32_rm32, register, in memory));
		}

		public void adc(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Adc_r64_rm64, register, in memory));
		}

		public void adc(AssemblerRegister8 dst, sbyte imm)
		{
			Code code = (((Register)dst == Register.AL) ? Code.Adc_AL_imm8 : Code.Adc_rm8_imm8);
			AddInstruction(Instruction.Create(code, dst, imm));
		}

		public void adc(AssemblerRegister16 dst, short imm)
		{
			Code code = (((Register)dst != Register.AX) ? ((imm >= -128 && imm <= 127) ? Code.Adc_rm16_imm8 : Code.Adc_rm16_imm16) : Code.Adc_AX_imm16);
			AddInstruction(Instruction.Create(code, dst, imm));
		}

		public void adc(AssemblerRegister32 dst, int imm)
		{
			Code code = (((Register)dst != Register.EAX) ? ((imm >= -128 && imm <= 127) ? Code.Adc_rm32_imm8 : Code.Adc_rm32_imm32) : Code.Adc_EAX_imm32);
			AddInstruction(Instruction.Create(code, dst, imm));
		}

		public void adc(AssemblerRegister64 dst, int imm)
		{
			Code code = (((Register)dst != Register.RAX) ? ((imm >= -128 && imm <= 127) ? Code.Adc_rm64_imm8 : Code.Adc_rm64_imm32) : Code.Adc_RAX_imm32);
			AddInstruction(Instruction.Create(code, dst, imm));
		}

		public void adc(AssemblerMemoryOperand dst, int imm)
		{
			Code code;
			if (dst.Size == MemoryOperandSize.Qword)
			{
				code = ((imm >= -128 && imm <= 127) ? Code.Adc_rm64_imm8 : Code.Adc_rm64_imm32);
			}
			else if (dst.Size == MemoryOperandSize.Dword)
			{
				code = ((imm >= -128 && imm <= 127) ? Code.Adc_rm32_imm8 : Code.Adc_rm32_imm32);
			}
			else if (dst.Size == MemoryOperandSize.Word)
			{
				code = ((imm >= -128 && imm <= 127) ? Code.Adc_rm16_imm8 : Code.Adc_rm16_imm16);
			}
			else
			{
				if (dst.Size != MemoryOperandSize.Byte)
				{
					throw NoOpCodeFoundFor(Mnemonic.Adc, dst, imm);
				}
				code = Code.Adc_rm8_imm8;
			}
			Code code2 = code;
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, in memory, imm));
		}

		public void adc(AssemblerRegister8 dst, byte imm)
		{
			Code code = (((Register)dst == Register.AL) ? Code.Adc_AL_imm8 : Code.Adc_rm8_imm8);
			AddInstruction(Instruction.Create(code, (Register)dst, (uint)imm));
		}

		public void adc(AssemblerRegister16 dst, ushort imm)
		{
			Code code = (((Register)dst != Register.AX) ? ((imm <= 127 || (65408 <= imm && imm <= ushort.MaxValue)) ? Code.Adc_rm16_imm8 : Code.Adc_rm16_imm16) : Code.Adc_AX_imm16);
			AddInstruction(Instruction.Create(code, (Register)dst, (uint)imm));
		}

		public void adc(AssemblerRegister32 dst, uint imm)
		{
			Code code = (((Register)dst != Register.EAX) ? ((imm <= 127 || 4294967168u <= imm) ? Code.Adc_rm32_imm8 : Code.Adc_rm32_imm32) : Code.Adc_EAX_imm32);
			AddInstruction(Instruction.Create(code, dst, imm));
		}

		public void adc(AssemblerMemoryOperand dst, uint imm)
		{
			Code code;
			if (dst.Size == MemoryOperandSize.Dword)
			{
				code = ((imm <= 127 || 4294967168u <= imm) ? Code.Adc_rm32_imm8 : Code.Adc_rm32_imm32);
			}
			else if (dst.Size == MemoryOperandSize.Word)
			{
				code = ((imm <= 127 || (65408 <= imm && imm <= 65535)) ? Code.Adc_rm16_imm8 : Code.Adc_rm16_imm16);
			}
			else
			{
				if (dst.Size != MemoryOperandSize.Byte)
				{
					throw NoOpCodeFoundFor(Mnemonic.Adc, dst, imm);
				}
				code = Code.Adc_rm8_imm8;
			}
			Code code2 = code;
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, in memory, imm));
		}

		public void adcx(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Adcx_r32_rm32, dst, src));
		}

		public void adcx(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Adcx_r64_rm64, dst, src));
		}

		public void adcx(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Adcx_r32_rm32, register, in memory));
		}

		public void adcx(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Adcx_r64_rm64, register, in memory));
		}

		public void add(AssemblerRegister8 dst, AssemblerRegister8 src)
		{
			AddInstruction(Instruction.Create(Code.Add_rm8_r8, dst, src));
		}

		public void add(AssemblerMemoryOperand dst, AssemblerRegister8 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Add_rm8_r8, in memory, src));
		}

		public void add(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Add_rm16_r16, dst, src));
		}

		public void add(AssemblerMemoryOperand dst, AssemblerRegister16 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Add_rm16_r16, in memory, src));
		}

		public void add(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Add_rm32_r32, dst, src));
		}

		public void add(AssemblerMemoryOperand dst, AssemblerRegister32 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Add_rm32_r32, in memory, src));
		}

		public void add(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Add_rm64_r64, dst, src));
		}

		public void add(AssemblerMemoryOperand dst, AssemblerRegister64 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Add_rm64_r64, in memory, src));
		}

		public void add(AssemblerRegister8 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Add_r8_rm8, register, in memory));
		}

		public void add(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Add_r16_rm16, register, in memory));
		}

		public void add(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Add_r32_rm32, register, in memory));
		}

		public void add(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Add_r64_rm64, register, in memory));
		}

		public void add(AssemblerRegister8 dst, sbyte imm)
		{
			Code code = (((Register)dst == Register.AL) ? Code.Add_AL_imm8 : Code.Add_rm8_imm8);
			AddInstruction(Instruction.Create(code, dst, imm));
		}

		public void add(AssemblerRegister16 dst, short imm)
		{
			Code code = (((Register)dst != Register.AX) ? ((imm >= -128 && imm <= 127) ? Code.Add_rm16_imm8 : Code.Add_rm16_imm16) : Code.Add_AX_imm16);
			AddInstruction(Instruction.Create(code, dst, imm));
		}

		public void add(AssemblerRegister32 dst, int imm)
		{
			Code code = (((Register)dst != Register.EAX) ? ((imm >= -128 && imm <= 127) ? Code.Add_rm32_imm8 : Code.Add_rm32_imm32) : Code.Add_EAX_imm32);
			AddInstruction(Instruction.Create(code, dst, imm));
		}

		public void add(AssemblerRegister64 dst, int imm)
		{
			Code code = (((Register)dst != Register.RAX) ? ((imm >= -128 && imm <= 127) ? Code.Add_rm64_imm8 : Code.Add_rm64_imm32) : Code.Add_RAX_imm32);
			AddInstruction(Instruction.Create(code, dst, imm));
		}

		public void add(AssemblerMemoryOperand dst, int imm)
		{
			Code code;
			if (dst.Size == MemoryOperandSize.Qword)
			{
				code = ((imm >= -128 && imm <= 127) ? Code.Add_rm64_imm8 : Code.Add_rm64_imm32);
			}
			else if (dst.Size == MemoryOperandSize.Dword)
			{
				code = ((imm >= -128 && imm <= 127) ? Code.Add_rm32_imm8 : Code.Add_rm32_imm32);
			}
			else if (dst.Size == MemoryOperandSize.Word)
			{
				code = ((imm >= -128 && imm <= 127) ? Code.Add_rm16_imm8 : Code.Add_rm16_imm16);
			}
			else
			{
				if (dst.Size != MemoryOperandSize.Byte)
				{
					throw NoOpCodeFoundFor(Mnemonic.Add, dst, imm);
				}
				code = Code.Add_rm8_imm8;
			}
			Code code2 = code;
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, in memory, imm));
		}

		public void add(AssemblerRegister8 dst, byte imm)
		{
			Code code = (((Register)dst == Register.AL) ? Code.Add_AL_imm8 : Code.Add_rm8_imm8);
			AddInstruction(Instruction.Create(code, (Register)dst, (uint)imm));
		}

		public void add(AssemblerRegister16 dst, ushort imm)
		{
			Code code = (((Register)dst != Register.AX) ? ((imm <= 127 || (65408 <= imm && imm <= ushort.MaxValue)) ? Code.Add_rm16_imm8 : Code.Add_rm16_imm16) : Code.Add_AX_imm16);
			AddInstruction(Instruction.Create(code, (Register)dst, (uint)imm));
		}

		public void add(AssemblerRegister32 dst, uint imm)
		{
			Code code = (((Register)dst != Register.EAX) ? ((imm <= 127 || 4294967168u <= imm) ? Code.Add_rm32_imm8 : Code.Add_rm32_imm32) : Code.Add_EAX_imm32);
			AddInstruction(Instruction.Create(code, dst, imm));
		}

		public void add(AssemblerMemoryOperand dst, uint imm)
		{
			Code code;
			if (dst.Size == MemoryOperandSize.Dword)
			{
				code = ((imm <= 127 || 4294967168u <= imm) ? Code.Add_rm32_imm8 : Code.Add_rm32_imm32);
			}
			else if (dst.Size == MemoryOperandSize.Word)
			{
				code = ((imm <= 127 || (65408 <= imm && imm <= 65535)) ? Code.Add_rm16_imm8 : Code.Add_rm16_imm16);
			}
			else
			{
				if (dst.Size != MemoryOperandSize.Byte)
				{
					throw NoOpCodeFoundFor(Mnemonic.Add, dst, imm);
				}
				code = Code.Add_rm8_imm8;
			}
			Code code2 = code;
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, in memory, imm));
		}

		public void addpd(AssemblerRegisterXMM dst, AssemblerRegisterXMM src)
		{
			AddInstruction(Instruction.Create(Code.Addpd_xmm_xmmm128, dst, src));
		}

		public void addpd(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Addpd_xmm_xmmm128, register, in memory));
		}

		public void addps(AssemblerRegisterXMM dst, AssemblerRegisterXMM src)
		{
			AddInstruction(Instruction.Create(Code.Addps_xmm_xmmm128, dst, src));
		}

		public void addps(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Addps_xmm_xmmm128, register, in memory));
		}

		public void addsd(AssemblerRegisterXMM dst, AssemblerRegisterXMM src)
		{
			AddInstruction(Instruction.Create(Code.Addsd_xmm_xmmm64, dst, src));
		}

		public void addsd(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Addsd_xmm_xmmm64, register, in memory));
		}

		public void addss(AssemblerRegisterXMM dst, AssemblerRegisterXMM src)
		{
			AddInstruction(Instruction.Create(Code.Addss_xmm_xmmm32, dst, src));
		}

		public void addss(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Addss_xmm_xmmm32, register, in memory));
		}

		public void addsubpd(AssemblerRegisterXMM dst, AssemblerRegisterXMM src)
		{
			AddInstruction(Instruction.Create(Code.Addsubpd_xmm_xmmm128, dst, src));
		}

		public void addsubpd(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Addsubpd_xmm_xmmm128, register, in memory));
		}

		public void addsubps(AssemblerRegisterXMM dst, AssemblerRegisterXMM src)
		{
			AddInstruction(Instruction.Create(Code.Addsubps_xmm_xmmm128, dst, src));
		}

		public void addsubps(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Addsubps_xmm_xmmm128, register, in memory));
		}

		public void adox(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Adox_r32_rm32, dst, src));
		}

		public void adox(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Adox_r64_rm64, dst, src));
		}

		public void adox(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Adox_r32_rm32, register, in memory));
		}

		public void adox(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Adox_r64_rm64, register, in memory));
		}

		public void aesdec(AssemblerRegisterXMM dst, AssemblerRegisterXMM src)
		{
			AddInstruction(Instruction.Create(Code.Aesdec_xmm_xmmm128, dst, src));
		}

		public void aesdec(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Aesdec_xmm_xmmm128, register, in memory));
		}

		public void aesdec128kl(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Aesdec128kl_xmm_m384, register, in memory));
		}

		public void aesdec256kl(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Aesdec256kl_xmm_m512, register, in memory));
		}

		public void aesdeclast(AssemblerRegisterXMM dst, AssemblerRegisterXMM src)
		{
			AddInstruction(Instruction.Create(Code.Aesdeclast_xmm_xmmm128, dst, src));
		}

		public void aesdeclast(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Aesdeclast_xmm_xmmm128, register, in memory));
		}

		public void aesdecwide128kl(AssemblerMemoryOperand dst)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Aesdecwide128kl_m384, in memory));
		}

		public void aesdecwide256kl(AssemblerMemoryOperand dst)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Aesdecwide256kl_m512, in memory));
		}

		public void aesenc(AssemblerRegisterXMM dst, AssemblerRegisterXMM src)
		{
			AddInstruction(Instruction.Create(Code.Aesenc_xmm_xmmm128, dst, src));
		}

		public void aesenc(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Aesenc_xmm_xmmm128, register, in memory));
		}

		public void aesenc128kl(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Aesenc128kl_xmm_m384, register, in memory));
		}

		public void aesenc256kl(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Aesenc256kl_xmm_m512, register, in memory));
		}

		public void aesenclast(AssemblerRegisterXMM dst, AssemblerRegisterXMM src)
		{
			AddInstruction(Instruction.Create(Code.Aesenclast_xmm_xmmm128, dst, src));
		}

		public void aesenclast(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Aesenclast_xmm_xmmm128, register, in memory));
		}

		public void aesencwide128kl(AssemblerMemoryOperand dst)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Aesencwide128kl_m384, in memory));
		}

		public void aesencwide256kl(AssemblerMemoryOperand dst)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Aesencwide256kl_m512, in memory));
		}

		public void aesimc(AssemblerRegisterXMM dst, AssemblerRegisterXMM src)
		{
			AddInstruction(Instruction.Create(Code.Aesimc_xmm_xmmm128, dst, src));
		}

		public void aesimc(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Aesimc_xmm_xmmm128, register, in memory));
		}

		public void aeskeygenassist(AssemblerRegisterXMM dst, AssemblerRegisterXMM src1, sbyte imm)
		{
			AddInstruction(Instruction.Create(Code.Aeskeygenassist_xmm_xmmm128_imm8, dst, src1, imm));
		}

		public void aeskeygenassist(AssemblerRegisterXMM dst, AssemblerMemoryOperand src1, sbyte imm)
		{
			Register register = dst;
			MemoryOperand memory = src1.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Aeskeygenassist_xmm_xmmm128_imm8, register, in memory, imm));
		}

		public void aeskeygenassist(AssemblerRegisterXMM dst, AssemblerRegisterXMM src1, byte imm)
		{
			AddInstruction(Instruction.Create(Code.Aeskeygenassist_xmm_xmmm128_imm8, (Register)dst, (Register)src1, (uint)imm));
		}

		public void aeskeygenassist(AssemblerRegisterXMM dst, AssemblerMemoryOperand src1, byte imm)
		{
			Register register = dst;
			MemoryOperand memory = src1.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Aeskeygenassist_xmm_xmmm128_imm8, register, in memory, (uint)imm));
		}

		public void altinst()
		{
			AddInstruction(Instruction.Create(Code.Altinst));
		}

		public void and(AssemblerRegister8 dst, AssemblerRegister8 src)
		{
			AddInstruction(Instruction.Create(Code.And_rm8_r8, dst, src));
		}

		public void and(AssemblerMemoryOperand dst, AssemblerRegister8 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.And_rm8_r8, in memory, src));
		}

		public void and(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.And_rm16_r16, dst, src));
		}

		public void and(AssemblerMemoryOperand dst, AssemblerRegister16 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.And_rm16_r16, in memory, src));
		}

		public void and(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.And_rm32_r32, dst, src));
		}

		public void and(AssemblerMemoryOperand dst, AssemblerRegister32 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.And_rm32_r32, in memory, src));
		}

		public void and(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.And_rm64_r64, dst, src));
		}

		public void and(AssemblerMemoryOperand dst, AssemblerRegister64 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.And_rm64_r64, in memory, src));
		}

		public void and(AssemblerRegister8 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.And_r8_rm8, register, in memory));
		}

		public void and(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.And_r16_rm16, register, in memory));
		}

		public void and(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.And_r32_rm32, register, in memory));
		}

		public void and(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.And_r64_rm64, register, in memory));
		}

		public void and(AssemblerRegister8 dst, sbyte imm)
		{
			Code code = (((Register)dst == Register.AL) ? Code.And_AL_imm8 : Code.And_rm8_imm8);
			AddInstruction(Instruction.Create(code, dst, imm));
		}

		public void and(AssemblerRegister16 dst, short imm)
		{
			Code code = (((Register)dst != Register.AX) ? ((imm >= -128 && imm <= 127) ? Code.And_rm16_imm8 : Code.And_rm16_imm16) : Code.And_AX_imm16);
			AddInstruction(Instruction.Create(code, dst, imm));
		}

		public void and(AssemblerRegister32 dst, int imm)
		{
			Code code = (((Register)dst != Register.EAX) ? ((imm >= -128 && imm <= 127) ? Code.And_rm32_imm8 : Code.And_rm32_imm32) : Code.And_EAX_imm32);
			AddInstruction(Instruction.Create(code, dst, imm));
		}

		public void and(AssemblerRegister64 dst, int imm)
		{
			Code code = (((Register)dst != Register.RAX) ? ((imm >= -128 && imm <= 127) ? Code.And_rm64_imm8 : Code.And_rm64_imm32) : Code.And_RAX_imm32);
			AddInstruction(Instruction.Create(code, dst, imm));
		}

		public void and(AssemblerMemoryOperand dst, int imm)
		{
			Code code;
			if (dst.Size == MemoryOperandSize.Qword)
			{
				code = ((imm >= -128 && imm <= 127) ? Code.And_rm64_imm8 : Code.And_rm64_imm32);
			}
			else if (dst.Size == MemoryOperandSize.Dword)
			{
				code = ((imm >= -128 && imm <= 127) ? Code.And_rm32_imm8 : Code.And_rm32_imm32);
			}
			else if (dst.Size == MemoryOperandSize.Word)
			{
				code = ((imm >= -128 && imm <= 127) ? Code.And_rm16_imm8 : Code.And_rm16_imm16);
			}
			else
			{
				if (dst.Size != MemoryOperandSize.Byte)
				{
					throw NoOpCodeFoundFor(Mnemonic.And, dst, imm);
				}
				code = Code.And_rm8_imm8;
			}
			Code code2 = code;
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, in memory, imm));
		}

		public void and(AssemblerRegister8 dst, byte imm)
		{
			Code code = (((Register)dst == Register.AL) ? Code.And_AL_imm8 : Code.And_rm8_imm8);
			AddInstruction(Instruction.Create(code, (Register)dst, (uint)imm));
		}

		public void and(AssemblerRegister16 dst, ushort imm)
		{
			Code code = (((Register)dst != Register.AX) ? ((imm <= 127 || (65408 <= imm && imm <= ushort.MaxValue)) ? Code.And_rm16_imm8 : Code.And_rm16_imm16) : Code.And_AX_imm16);
			AddInstruction(Instruction.Create(code, (Register)dst, (uint)imm));
		}

		public void and(AssemblerRegister32 dst, uint imm)
		{
			Code code = (((Register)dst != Register.EAX) ? ((imm <= 127 || 4294967168u <= imm) ? Code.And_rm32_imm8 : Code.And_rm32_imm32) : Code.And_EAX_imm32);
			AddInstruction(Instruction.Create(code, dst, imm));
		}

		public void and(AssemblerMemoryOperand dst, uint imm)
		{
			Code code;
			if (dst.Size == MemoryOperandSize.Dword)
			{
				code = ((imm <= 127 || 4294967168u <= imm) ? Code.And_rm32_imm8 : Code.And_rm32_imm32);
			}
			else if (dst.Size == MemoryOperandSize.Word)
			{
				code = ((imm <= 127 || (65408 <= imm && imm <= 65535)) ? Code.And_rm16_imm8 : Code.And_rm16_imm16);
			}
			else
			{
				if (dst.Size != MemoryOperandSize.Byte)
				{
					throw NoOpCodeFoundFor(Mnemonic.And, dst, imm);
				}
				code = Code.And_rm8_imm8;
			}
			Code code2 = code;
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, in memory, imm));
		}

		public void andn(AssemblerRegister32 dst, AssemblerRegister32 src1, AssemblerRegister32 src2)
		{
			AddInstruction(Instruction.Create(Code.VEX_Andn_r32_r32_rm32, dst, src1, src2));
		}

		public void andn(AssemblerRegister64 dst, AssemblerRegister64 src1, AssemblerRegister64 src2)
		{
			AddInstruction(Instruction.Create(Code.VEX_Andn_r64_r64_rm64, dst, src1, src2));
		}

		public void andn(AssemblerRegister32 dst, AssemblerRegister32 src1, AssemblerMemoryOperand src2)
		{
			Register register = dst;
			Register register2 = src1;
			MemoryOperand memory = src2.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.VEX_Andn_r32_r32_rm32, register, register2, in memory));
		}

		public void andn(AssemblerRegister64 dst, AssemblerRegister64 src1, AssemblerMemoryOperand src2)
		{
			Register register = dst;
			Register register2 = src1;
			MemoryOperand memory = src2.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.VEX_Andn_r64_r64_rm64, register, register2, in memory));
		}

		public void andnpd(AssemblerRegisterXMM dst, AssemblerRegisterXMM src)
		{
			AddInstruction(Instruction.Create(Code.Andnpd_xmm_xmmm128, dst, src));
		}

		public void andnpd(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Andnpd_xmm_xmmm128, register, in memory));
		}

		public void andnps(AssemblerRegisterXMM dst, AssemblerRegisterXMM src)
		{
			AddInstruction(Instruction.Create(Code.Andnps_xmm_xmmm128, dst, src));
		}

		public void andnps(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Andnps_xmm_xmmm128, register, in memory));
		}

		public void andpd(AssemblerRegisterXMM dst, AssemblerRegisterXMM src)
		{
			AddInstruction(Instruction.Create(Code.Andpd_xmm_xmmm128, dst, src));
		}

		public void andpd(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Andpd_xmm_xmmm128, register, in memory));
		}

		public void andps(AssemblerRegisterXMM dst, AssemblerRegisterXMM src)
		{
			AddInstruction(Instruction.Create(Code.Andps_xmm_xmmm128, dst, src));
		}

		public void andps(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Andps_xmm_xmmm128, register, in memory));
		}

		public void arpl(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Arpl_rm16_r16, dst, src));
		}

		public void arpl(AssemblerMemoryOperand dst, AssemblerRegister16 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Arpl_rm16_r16, in memory, src));
		}

		public void arpl(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Arpl_r32m16_r32, dst, src));
		}

		public void arpl(AssemblerMemoryOperand dst, AssemblerRegister32 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Arpl_r32m16_r32, in memory, src));
		}

		public void bb0_reset()
		{
			AddInstruction(Instruction.Create(Code.Bb0_reset));
		}

		public void bb1_reset()
		{
			AddInstruction(Instruction.Create(Code.Bb1_reset));
		}

		public void bextr(AssemblerRegister32 dst, AssemblerRegister32 src1, AssemblerRegister32 src2)
		{
			AddInstruction(Instruction.Create(Code.VEX_Bextr_r32_rm32_r32, dst, src1, src2));
		}

		public void bextr(AssemblerRegister32 dst, AssemblerMemoryOperand src1, AssemblerRegister32 src2)
		{
			Register register = dst;
			MemoryOperand memory = src1.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.VEX_Bextr_r32_rm32_r32, register, in memory, src2));
		}

		public void bextr(AssemblerRegister64 dst, AssemblerRegister64 src1, AssemblerRegister64 src2)
		{
			AddInstruction(Instruction.Create(Code.VEX_Bextr_r64_rm64_r64, dst, src1, src2));
		}

		public void bextr(AssemblerRegister64 dst, AssemblerMemoryOperand src1, AssemblerRegister64 src2)
		{
			Register register = dst;
			MemoryOperand memory = src1.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.VEX_Bextr_r64_rm64_r64, register, in memory, src2));
		}

		public void bextr(AssemblerRegister32 dst, AssemblerRegister32 src1, int imm)
		{
			AddInstruction(Instruction.Create(Code.XOP_Bextr_r32_rm32_imm32, dst, src1, imm));
		}

		public void bextr(AssemblerRegister64 dst, AssemblerRegister64 src1, int imm)
		{
			AddInstruction(Instruction.Create(Code.XOP_Bextr_r64_rm64_imm32, dst, src1, imm));
		}

		public void bextr(AssemblerRegister32 dst, AssemblerMemoryOperand src1, int imm)
		{
			Register register = dst;
			MemoryOperand memory = src1.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Bextr_r32_rm32_imm32, register, in memory, imm));
		}

		public void bextr(AssemblerRegister64 dst, AssemblerMemoryOperand src1, int imm)
		{
			Register register = dst;
			MemoryOperand memory = src1.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Bextr_r64_rm64_imm32, register, in memory, imm));
		}

		public void bextr(AssemblerRegister32 dst, AssemblerRegister32 src1, uint imm)
		{
			AddInstruction(Instruction.Create(Code.XOP_Bextr_r32_rm32_imm32, dst, src1, imm));
		}

		public void bextr(AssemblerRegister64 dst, AssemblerRegister64 src1, uint imm)
		{
			AddInstruction(Instruction.Create(Code.XOP_Bextr_r64_rm64_imm32, dst, src1, imm));
		}

		public void bextr(AssemblerRegister32 dst, AssemblerMemoryOperand src1, uint imm)
		{
			Register register = dst;
			MemoryOperand memory = src1.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Bextr_r32_rm32_imm32, register, in memory, imm));
		}

		public void bextr(AssemblerRegister64 dst, AssemblerMemoryOperand src1, uint imm)
		{
			Register register = dst;
			MemoryOperand memory = src1.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Bextr_r64_rm64_imm32, register, in memory, imm));
		}

		public void blcfill(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.XOP_Blcfill_r32_rm32, dst, src));
		}

		public void blcfill(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.XOP_Blcfill_r64_rm64, dst, src));
		}

		public void blcfill(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Blcfill_r32_rm32, register, in memory));
		}

		public void blcfill(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Blcfill_r64_rm64, register, in memory));
		}

		public void blci(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.XOP_Blci_r32_rm32, dst, src));
		}

		public void blci(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.XOP_Blci_r64_rm64, dst, src));
		}

		public void blci(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Blci_r32_rm32, register, in memory));
		}

		public void blci(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Blci_r64_rm64, register, in memory));
		}

		public void blcic(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.XOP_Blcic_r32_rm32, dst, src));
		}

		public void blcic(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.XOP_Blcic_r64_rm64, dst, src));
		}

		public void blcic(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Blcic_r32_rm32, register, in memory));
		}

		public void blcic(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Blcic_r64_rm64, register, in memory));
		}

		public void blcmsk(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.XOP_Blcmsk_r32_rm32, dst, src));
		}

		public void blcmsk(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.XOP_Blcmsk_r64_rm64, dst, src));
		}

		public void blcmsk(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Blcmsk_r32_rm32, register, in memory));
		}

		public void blcmsk(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Blcmsk_r64_rm64, register, in memory));
		}

		public void blcs(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.XOP_Blcs_r32_rm32, dst, src));
		}

		public void blcs(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.XOP_Blcs_r64_rm64, dst, src));
		}

		public void blcs(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Blcs_r32_rm32, register, in memory));
		}

		public void blcs(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Blcs_r64_rm64, register, in memory));
		}

		public void blendpd(AssemblerRegisterXMM dst, AssemblerRegisterXMM src1, sbyte imm)
		{
			AddInstruction(Instruction.Create(Code.Blendpd_xmm_xmmm128_imm8, dst, src1, imm));
		}

		public void blendpd(AssemblerRegisterXMM dst, AssemblerMemoryOperand src1, sbyte imm)
		{
			Register register = dst;
			MemoryOperand memory = src1.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Blendpd_xmm_xmmm128_imm8, register, in memory, imm));
		}

		public void blendpd(AssemblerRegisterXMM dst, AssemblerRegisterXMM src1, byte imm)
		{
			AddInstruction(Instruction.Create(Code.Blendpd_xmm_xmmm128_imm8, (Register)dst, (Register)src1, (uint)imm));
		}

		public void blendpd(AssemblerRegisterXMM dst, AssemblerMemoryOperand src1, byte imm)
		{
			Register register = dst;
			MemoryOperand memory = src1.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Blendpd_xmm_xmmm128_imm8, register, in memory, (uint)imm));
		}

		public void blendps(AssemblerRegisterXMM dst, AssemblerRegisterXMM src1, sbyte imm)
		{
			AddInstruction(Instruction.Create(Code.Blendps_xmm_xmmm128_imm8, dst, src1, imm));
		}

		public void blendps(AssemblerRegisterXMM dst, AssemblerMemoryOperand src1, sbyte imm)
		{
			Register register = dst;
			MemoryOperand memory = src1.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Blendps_xmm_xmmm128_imm8, register, in memory, imm));
		}

		public void blendps(AssemblerRegisterXMM dst, AssemblerRegisterXMM src1, byte imm)
		{
			AddInstruction(Instruction.Create(Code.Blendps_xmm_xmmm128_imm8, (Register)dst, (Register)src1, (uint)imm));
		}

		public void blendps(AssemblerRegisterXMM dst, AssemblerMemoryOperand src1, byte imm)
		{
			Register register = dst;
			MemoryOperand memory = src1.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Blendps_xmm_xmmm128_imm8, register, in memory, (uint)imm));
		}

		public void blendvpd(AssemblerRegisterXMM dst, AssemblerRegisterXMM src)
		{
			AddInstruction(Instruction.Create(Code.Blendvpd_xmm_xmmm128, dst, src));
		}

		public void blendvpd(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Blendvpd_xmm_xmmm128, register, in memory));
		}

		public void blendvps(AssemblerRegisterXMM dst, AssemblerRegisterXMM src)
		{
			AddInstruction(Instruction.Create(Code.Blendvps_xmm_xmmm128, dst, src));
		}

		public void blendvps(AssemblerRegisterXMM dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Blendvps_xmm_xmmm128, register, in memory));
		}

		public void blsfill(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.XOP_Blsfill_r32_rm32, dst, src));
		}

		public void blsfill(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.XOP_Blsfill_r64_rm64, dst, src));
		}

		public void blsfill(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Blsfill_r32_rm32, register, in memory));
		}

		public void blsfill(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Blsfill_r64_rm64, register, in memory));
		}

		public void blsi(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.VEX_Blsi_r32_rm32, dst, src));
		}

		public void blsi(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.VEX_Blsi_r64_rm64, dst, src));
		}

		public void blsi(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.VEX_Blsi_r32_rm32, register, in memory));
		}

		public void blsi(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.VEX_Blsi_r64_rm64, register, in memory));
		}

		public void blsic(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.XOP_Blsic_r32_rm32, dst, src));
		}

		public void blsic(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.XOP_Blsic_r64_rm64, dst, src));
		}

		public void blsic(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Blsic_r32_rm32, register, in memory));
		}

		public void blsic(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.XOP_Blsic_r64_rm64, register, in memory));
		}

		public void blsmsk(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.VEX_Blsmsk_r32_rm32, dst, src));
		}

		public void blsmsk(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.VEX_Blsmsk_r64_rm64, dst, src));
		}

		public void blsmsk(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.VEX_Blsmsk_r32_rm32, register, in memory));
		}

		public void blsmsk(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.VEX_Blsmsk_r64_rm64, register, in memory));
		}

		public void blsr(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.VEX_Blsr_r32_rm32, dst, src));
		}

		public void blsr(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.VEX_Blsr_r64_rm64, dst, src));
		}

		public void blsr(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.VEX_Blsr_r32_rm32, register, in memory));
		}

		public void blsr(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.VEX_Blsr_r64_rm64, register, in memory));
		}

		public void bndcl(AssemblerRegisterBND dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Bndcl_bnd_rm32, dst, src));
		}

		public void bndcl(AssemblerRegisterBND dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Bndcl_bnd_rm64, dst, src));
		}

		public void bndcl(AssemblerRegisterBND dst, AssemblerMemoryOperand src)
		{
			Code code;
			if (src.Size == MemoryOperandSize.Qword)
			{
				code = Code.Bndcl_bnd_rm64;
			}
			else
			{
				if (src.Size != MemoryOperandSize.Dword)
				{
					throw NoOpCodeFoundFor(Mnemonic.Bndcl, dst, src);
				}
				code = Code.Bndcl_bnd_rm32;
			}
			Code code2 = code;
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, register, in memory));
		}

		public void bndcn(AssemblerRegisterBND dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Bndcn_bnd_rm32, dst, src));
		}

		public void bndcn(AssemblerRegisterBND dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Bndcn_bnd_rm64, dst, src));
		}

		public void bndcn(AssemblerRegisterBND dst, AssemblerMemoryOperand src)
		{
			Code code;
			if (src.Size == MemoryOperandSize.Qword)
			{
				code = Code.Bndcn_bnd_rm64;
			}
			else
			{
				if (src.Size != MemoryOperandSize.Dword)
				{
					throw NoOpCodeFoundFor(Mnemonic.Bndcn, dst, src);
				}
				code = Code.Bndcn_bnd_rm32;
			}
			Code code2 = code;
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, register, in memory));
		}

		public void bndcu(AssemblerRegisterBND dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Bndcu_bnd_rm32, dst, src));
		}

		public void bndcu(AssemblerRegisterBND dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Bndcu_bnd_rm64, dst, src));
		}

		public void bndcu(AssemblerRegisterBND dst, AssemblerMemoryOperand src)
		{
			Code code;
			if (src.Size == MemoryOperandSize.Qword)
			{
				code = Code.Bndcu_bnd_rm64;
			}
			else
			{
				if (src.Size != MemoryOperandSize.Dword)
				{
					throw NoOpCodeFoundFor(Mnemonic.Bndcu, dst, src);
				}
				code = Code.Bndcu_bnd_rm32;
			}
			Code code2 = code;
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, register, in memory));
		}

		public void bndldx(AssemblerRegisterBND dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Bndldx_bnd_mib, register, in memory));
		}

		public void bndmk(AssemblerRegisterBND dst, AssemblerMemoryOperand src)
		{
			Code code;
			if (src.Size == MemoryOperandSize.Qword)
			{
				code = Code.Bndmk_bnd_m64;
			}
			else
			{
				if (src.Size != MemoryOperandSize.Dword)
				{
					throw NoOpCodeFoundFor(Mnemonic.Bndmk, dst, src);
				}
				code = Code.Bndmk_bnd_m32;
			}
			Code code2 = code;
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, register, in memory));
		}

		public void bndmov(AssemblerRegisterBND dst, AssemblerRegisterBND src)
		{
			Code code = ((Bitness == 64) ? Code.Bndmov_bnd_bndm128 : Code.Bndmov_bnd_bndm64);
			AddInstruction(Instruction.Create(code, dst, src));
		}

		public void bndmov(AssemblerMemoryOperand dst, AssemblerRegisterBND src)
		{
			Code code = ((Bitness == 64) ? Code.Bndmov_bndm128_bnd : Code.Bndmov_bndm64_bnd);
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code, in memory, src));
		}

		public void bndmov(AssemblerRegisterBND dst, AssemblerMemoryOperand src)
		{
			Code code = ((Bitness == 64) ? Code.Bndmov_bnd_bndm128 : Code.Bndmov_bnd_bndm64);
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code, register, in memory));
		}

		public void bndstx(AssemblerMemoryOperand dst, AssemblerRegisterBND src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Bndstx_mib_bnd, in memory, src));
		}

		public void bound(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Bound_r16_m1616, register, in memory));
		}

		public void bound(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Bound_r32_m3232, register, in memory));
		}

		public void bsf(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Bsf_r16_rm16, dst, src));
		}

		public void bsf(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Bsf_r32_rm32, dst, src));
		}

		public void bsf(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Bsf_r64_rm64, dst, src));
		}

		public void bsf(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Bsf_r16_rm16, register, in memory));
		}

		public void bsf(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Bsf_r32_rm32, register, in memory));
		}

		public void bsf(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Bsf_r64_rm64, register, in memory));
		}

		public void bsr(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Bsr_r16_rm16, dst, src));
		}

		public void bsr(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Bsr_r32_rm32, dst, src));
		}

		public void bsr(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Bsr_r64_rm64, dst, src));
		}

		public void bsr(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Bsr_r16_rm16, register, in memory));
		}

		public void bsr(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Bsr_r32_rm32, register, in memory));
		}

		public void bsr(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Bsr_r64_rm64, register, in memory));
		}

		public void bswap(AssemblerRegister16 dst)
		{
			AddInstruction(Instruction.Create(Code.Bswap_r16, dst));
		}

		public void bswap(AssemblerRegister32 dst)
		{
			AddInstruction(Instruction.Create(Code.Bswap_r32, dst));
		}

		public void bswap(AssemblerRegister64 dst)
		{
			AddInstruction(Instruction.Create(Code.Bswap_r64, dst));
		}

		public void bt(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Bt_rm16_r16, dst, src));
		}

		public void bt(AssemblerMemoryOperand dst, AssemblerRegister16 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Bt_rm16_r16, in memory, src));
		}

		public void bt(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Bt_rm32_r32, dst, src));
		}

		public void bt(AssemblerMemoryOperand dst, AssemblerRegister32 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Bt_rm32_r32, in memory, src));
		}

		public void bt(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Bt_rm64_r64, dst, src));
		}

		public void bt(AssemblerMemoryOperand dst, AssemblerRegister64 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Bt_rm64_r64, in memory, src));
		}

		public void bt(AssemblerRegister16 dst, sbyte imm)
		{
			AddInstruction(Instruction.Create(Code.Bt_rm16_imm8, dst, imm));
		}

		public void bt(AssemblerRegister32 dst, sbyte imm)
		{
			AddInstruction(Instruction.Create(Code.Bt_rm32_imm8, dst, imm));
		}

		public void bt(AssemblerRegister64 dst, sbyte imm)
		{
			AddInstruction(Instruction.Create(Code.Bt_rm64_imm8, dst, imm));
		}

		public void bt(AssemblerMemoryOperand dst, sbyte imm)
		{
			Code code;
			if (dst.Size == MemoryOperandSize.Qword)
			{
				code = Code.Bt_rm64_imm8;
			}
			else if (dst.Size == MemoryOperandSize.Dword)
			{
				code = Code.Bt_rm32_imm8;
			}
			else
			{
				if (dst.Size != MemoryOperandSize.Word)
				{
					throw NoOpCodeFoundFor(Mnemonic.Bt, dst, imm);
				}
				code = Code.Bt_rm16_imm8;
			}
			Code code2 = code;
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, in memory, imm));
		}

		public void bt(AssemblerRegister16 dst, byte imm)
		{
			AddInstruction(Instruction.Create(Code.Bt_rm16_imm8, (Register)dst, (uint)imm));
		}

		public void bt(AssemblerRegister32 dst, byte imm)
		{
			AddInstruction(Instruction.Create(Code.Bt_rm32_imm8, (Register)dst, (uint)imm));
		}

		public void bt(AssemblerRegister64 dst, byte imm)
		{
			AddInstruction(Instruction.Create(Code.Bt_rm64_imm8, (Register)dst, (uint)imm));
		}

		public void bt(AssemblerMemoryOperand dst, byte imm)
		{
			Code code;
			if (dst.Size == MemoryOperandSize.Qword)
			{
				code = Code.Bt_rm64_imm8;
			}
			else if (dst.Size == MemoryOperandSize.Dword)
			{
				code = Code.Bt_rm32_imm8;
			}
			else
			{
				if (dst.Size != MemoryOperandSize.Word)
				{
					throw NoOpCodeFoundFor(Mnemonic.Bt, dst, imm);
				}
				code = Code.Bt_rm16_imm8;
			}
			Code code2 = code;
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, in memory, (uint)imm));
		}

		public void btc(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Btc_rm16_r16, dst, src));
		}

		public void btc(AssemblerMemoryOperand dst, AssemblerRegister16 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Btc_rm16_r16, in memory, src));
		}

		public void btc(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Btc_rm32_r32, dst, src));
		}

		public void btc(AssemblerMemoryOperand dst, AssemblerRegister32 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Btc_rm32_r32, in memory, src));
		}

		public void btc(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Btc_rm64_r64, dst, src));
		}

		public void btc(AssemblerMemoryOperand dst, AssemblerRegister64 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Btc_rm64_r64, in memory, src));
		}

		public void btc(AssemblerRegister16 dst, sbyte imm)
		{
			AddInstruction(Instruction.Create(Code.Btc_rm16_imm8, dst, imm));
		}

		public void btc(AssemblerRegister32 dst, sbyte imm)
		{
			AddInstruction(Instruction.Create(Code.Btc_rm32_imm8, dst, imm));
		}

		public void btc(AssemblerRegister64 dst, sbyte imm)
		{
			AddInstruction(Instruction.Create(Code.Btc_rm64_imm8, dst, imm));
		}

		public void btc(AssemblerMemoryOperand dst, sbyte imm)
		{
			Code code;
			if (dst.Size == MemoryOperandSize.Qword)
			{
				code = Code.Btc_rm64_imm8;
			}
			else if (dst.Size == MemoryOperandSize.Dword)
			{
				code = Code.Btc_rm32_imm8;
			}
			else
			{
				if (dst.Size != MemoryOperandSize.Word)
				{
					throw NoOpCodeFoundFor(Mnemonic.Btc, dst, imm);
				}
				code = Code.Btc_rm16_imm8;
			}
			Code code2 = code;
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, in memory, imm));
		}

		public void btc(AssemblerRegister16 dst, byte imm)
		{
			AddInstruction(Instruction.Create(Code.Btc_rm16_imm8, (Register)dst, (uint)imm));
		}

		public void btc(AssemblerRegister32 dst, byte imm)
		{
			AddInstruction(Instruction.Create(Code.Btc_rm32_imm8, (Register)dst, (uint)imm));
		}

		public void btc(AssemblerRegister64 dst, byte imm)
		{
			AddInstruction(Instruction.Create(Code.Btc_rm64_imm8, (Register)dst, (uint)imm));
		}

		public void btc(AssemblerMemoryOperand dst, byte imm)
		{
			Code code;
			if (dst.Size == MemoryOperandSize.Qword)
			{
				code = Code.Btc_rm64_imm8;
			}
			else if (dst.Size == MemoryOperandSize.Dword)
			{
				code = Code.Btc_rm32_imm8;
			}
			else
			{
				if (dst.Size != MemoryOperandSize.Word)
				{
					throw NoOpCodeFoundFor(Mnemonic.Btc, dst, imm);
				}
				code = Code.Btc_rm16_imm8;
			}
			Code code2 = code;
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, in memory, (uint)imm));
		}

		public void btr(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Btr_rm16_r16, dst, src));
		}

		public void btr(AssemblerMemoryOperand dst, AssemblerRegister16 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Btr_rm16_r16, in memory, src));
		}

		public void btr(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Btr_rm32_r32, dst, src));
		}

		public void btr(AssemblerMemoryOperand dst, AssemblerRegister32 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Btr_rm32_r32, in memory, src));
		}

		public void btr(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Btr_rm64_r64, dst, src));
		}

		public void btr(AssemblerMemoryOperand dst, AssemblerRegister64 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Btr_rm64_r64, in memory, src));
		}

		public void btr(AssemblerRegister16 dst, sbyte imm)
		{
			AddInstruction(Instruction.Create(Code.Btr_rm16_imm8, dst, imm));
		}

		public void btr(AssemblerRegister32 dst, sbyte imm)
		{
			AddInstruction(Instruction.Create(Code.Btr_rm32_imm8, dst, imm));
		}

		public void btr(AssemblerRegister64 dst, sbyte imm)
		{
			AddInstruction(Instruction.Create(Code.Btr_rm64_imm8, dst, imm));
		}

		public void btr(AssemblerMemoryOperand dst, sbyte imm)
		{
			Code code;
			if (dst.Size == MemoryOperandSize.Qword)
			{
				code = Code.Btr_rm64_imm8;
			}
			else if (dst.Size == MemoryOperandSize.Dword)
			{
				code = Code.Btr_rm32_imm8;
			}
			else
			{
				if (dst.Size != MemoryOperandSize.Word)
				{
					throw NoOpCodeFoundFor(Mnemonic.Btr, dst, imm);
				}
				code = Code.Btr_rm16_imm8;
			}
			Code code2 = code;
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, in memory, imm));
		}

		public void btr(AssemblerRegister16 dst, byte imm)
		{
			AddInstruction(Instruction.Create(Code.Btr_rm16_imm8, (Register)dst, (uint)imm));
		}

		public void btr(AssemblerRegister32 dst, byte imm)
		{
			AddInstruction(Instruction.Create(Code.Btr_rm32_imm8, (Register)dst, (uint)imm));
		}

		public void btr(AssemblerRegister64 dst, byte imm)
		{
			AddInstruction(Instruction.Create(Code.Btr_rm64_imm8, (Register)dst, (uint)imm));
		}

		public void btr(AssemblerMemoryOperand dst, byte imm)
		{
			Code code;
			if (dst.Size == MemoryOperandSize.Qword)
			{
				code = Code.Btr_rm64_imm8;
			}
			else if (dst.Size == MemoryOperandSize.Dword)
			{
				code = Code.Btr_rm32_imm8;
			}
			else
			{
				if (dst.Size != MemoryOperandSize.Word)
				{
					throw NoOpCodeFoundFor(Mnemonic.Btr, dst, imm);
				}
				code = Code.Btr_rm16_imm8;
			}
			Code code2 = code;
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, in memory, (uint)imm));
		}

		public void bts(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Bts_rm16_r16, dst, src));
		}

		public void bts(AssemblerMemoryOperand dst, AssemblerRegister16 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Bts_rm16_r16, in memory, src));
		}

		public void bts(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Bts_rm32_r32, dst, src));
		}

		public void bts(AssemblerMemoryOperand dst, AssemblerRegister32 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Bts_rm32_r32, in memory, src));
		}

		public void bts(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Bts_rm64_r64, dst, src));
		}

		public void bts(AssemblerMemoryOperand dst, AssemblerRegister64 src)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Bts_rm64_r64, in memory, src));
		}

		public void bts(AssemblerRegister16 dst, sbyte imm)
		{
			AddInstruction(Instruction.Create(Code.Bts_rm16_imm8, dst, imm));
		}

		public void bts(AssemblerRegister32 dst, sbyte imm)
		{
			AddInstruction(Instruction.Create(Code.Bts_rm32_imm8, dst, imm));
		}

		public void bts(AssemblerRegister64 dst, sbyte imm)
		{
			AddInstruction(Instruction.Create(Code.Bts_rm64_imm8, dst, imm));
		}

		public void bts(AssemblerMemoryOperand dst, sbyte imm)
		{
			Code code;
			if (dst.Size == MemoryOperandSize.Qword)
			{
				code = Code.Bts_rm64_imm8;
			}
			else if (dst.Size == MemoryOperandSize.Dword)
			{
				code = Code.Bts_rm32_imm8;
			}
			else
			{
				if (dst.Size != MemoryOperandSize.Word)
				{
					throw NoOpCodeFoundFor(Mnemonic.Bts, dst, imm);
				}
				code = Code.Bts_rm16_imm8;
			}
			Code code2 = code;
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, in memory, imm));
		}

		public void bts(AssemblerRegister16 dst, byte imm)
		{
			AddInstruction(Instruction.Create(Code.Bts_rm16_imm8, (Register)dst, (uint)imm));
		}

		public void bts(AssemblerRegister32 dst, byte imm)
		{
			AddInstruction(Instruction.Create(Code.Bts_rm32_imm8, (Register)dst, (uint)imm));
		}

		public void bts(AssemblerRegister64 dst, byte imm)
		{
			AddInstruction(Instruction.Create(Code.Bts_rm64_imm8, (Register)dst, (uint)imm));
		}

		public void bts(AssemblerMemoryOperand dst, byte imm)
		{
			Code code;
			if (dst.Size == MemoryOperandSize.Qword)
			{
				code = Code.Bts_rm64_imm8;
			}
			else if (dst.Size == MemoryOperandSize.Dword)
			{
				code = Code.Bts_rm32_imm8;
			}
			else
			{
				if (dst.Size != MemoryOperandSize.Word)
				{
					throw NoOpCodeFoundFor(Mnemonic.Bts, dst, imm);
				}
				code = Code.Bts_rm16_imm8;
			}
			Code code2 = code;
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, in memory, (uint)imm));
		}

		public void bzhi(AssemblerRegister32 dst, AssemblerRegister32 src1, AssemblerRegister32 src2)
		{
			AddInstruction(Instruction.Create(Code.VEX_Bzhi_r32_rm32_r32, dst, src1, src2));
		}

		public void bzhi(AssemblerRegister32 dst, AssemblerMemoryOperand src1, AssemblerRegister32 src2)
		{
			Register register = dst;
			MemoryOperand memory = src1.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.VEX_Bzhi_r32_rm32_r32, register, in memory, src2));
		}

		public void bzhi(AssemblerRegister64 dst, AssemblerRegister64 src1, AssemblerRegister64 src2)
		{
			AddInstruction(Instruction.Create(Code.VEX_Bzhi_r64_rm64_r64, dst, src1, src2));
		}

		public void bzhi(AssemblerRegister64 dst, AssemblerMemoryOperand src1, AssemblerRegister64 src2)
		{
			Register register = dst;
			MemoryOperand memory = src1.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.VEX_Bzhi_r64_rm64_r64, register, in memory, src2));
		}

		public void call(AssemblerRegister16 dst)
		{
			AddInstruction(Instruction.Create(Code.Call_rm16, dst));
		}

		public void call(AssemblerRegister32 dst)
		{
			AddInstruction(Instruction.Create(Code.Call_rm32, dst));
		}

		public void call(AssemblerRegister64 dst)
		{
			AddInstruction(Instruction.Create(Code.Call_rm64, dst));
		}

		public void call(AssemblerMemoryOperand dst)
		{
			Code code;
			if (dst.Size == MemoryOperandSize.Tbyte)
			{
				code = Code.Call_m1664;
			}
			else if (dst.Size == MemoryOperandSize.Qword)
			{
				code = Code.Call_rm64;
			}
			else if (dst.Size == MemoryOperandSize.Fword)
			{
				code = Code.Call_m1632;
			}
			else if (dst.Size == MemoryOperandSize.Dword)
			{
				code = ((Bitness >= 32) ? Code.Call_rm32 : Code.Call_m1616);
			}
			else
			{
				if (dst.Size != MemoryOperandSize.Word)
				{
					throw NoOpCodeFoundFor(Mnemonic.Call, dst);
				}
				code = Code.Call_rm16;
			}
			Code code2 = code;
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(code2, in memory));
		}

		public void call(Label dst)
		{
			Code code = ((Bitness != 64) ? ((Bitness >= 32) ? Code.Call_rel32_32 : Code.Call_rel16) : Code.Call_rel32_64);
			AddInstruction(Instruction.CreateBranch(code, dst.Id));
		}

		public void call(ulong dst)
		{
			Code code = ((Bitness != 64) ? ((Bitness >= 32) ? Code.Call_rel32_32 : Code.Call_rel16) : Code.Call_rel32_64);
			AddInstruction(Instruction.CreateBranch(code, dst));
		}

		public void cbw()
		{
			AddInstruction(Instruction.Create(Code.Cbw));
		}

		public void ccs_encrypt()
		{
			Code code = ((Bitness != 64) ? ((Bitness >= 32) ? Code.Ccs_encrypt_32 : Code.Ccs_encrypt_16) : Code.Ccs_encrypt_64);
			AddInstruction(Instruction.Create(code));
		}

		public void ccs_hash()
		{
			Code code = ((Bitness != 64) ? ((Bitness >= 32) ? Code.Ccs_hash_32 : Code.Ccs_hash_16) : Code.Ccs_hash_64);
			AddInstruction(Instruction.Create(code));
		}

		public void cdq()
		{
			AddInstruction(Instruction.Create(Code.Cdq));
		}

		public void cdqe()
		{
			AddInstruction(Instruction.Create(Code.Cdqe));
		}

		public void cl1invmb()
		{
			AddInstruction(Instruction.Create(Code.Cl1invmb));
		}

		public void clac()
		{
			AddInstruction(Instruction.Create(Code.Clac));
		}

		public void clc()
		{
			AddInstruction(Instruction.Create(Code.Clc));
		}

		public void cld()
		{
			AddInstruction(Instruction.Create(Code.Cld));
		}

		public void cldemote(AssemblerMemoryOperand dst)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cldemote_m8, in memory));
		}

		public void clflush(AssemblerMemoryOperand dst)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Clflush_m8, in memory));
		}

		public void clflushopt(AssemblerMemoryOperand dst)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Clflushopt_m8, in memory));
		}

		public void clgi()
		{
			AddInstruction(Instruction.Create(Code.Clgi));
		}

		public void cli()
		{
			AddInstruction(Instruction.Create(Code.Cli));
		}

		public void clrssbsy(AssemblerMemoryOperand dst)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Clrssbsy_m64, in memory));
		}

		public void clts()
		{
			AddInstruction(Instruction.Create(Code.Clts));
		}

		public void clui()
		{
			AddInstruction(Instruction.Create(Code.Clui));
		}

		public void clwb(AssemblerMemoryOperand dst)
		{
			MemoryOperand memory = dst.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Clwb_m8, in memory));
		}

		public void clzero()
		{
			Code code = ((Bitness != 64) ? ((Bitness >= 32) ? Code.Clzerod : Code.Clzerow) : Code.Clzeroq);
			AddInstruction(Instruction.Create(code));
		}

		public void cmc()
		{
			AddInstruction(Instruction.Create(Code.Cmc));
		}

		public void cmova(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Cmova_r16_rm16, dst, src));
		}

		public void cmova(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Cmova_r32_rm32, dst, src));
		}

		public void cmova(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Cmova_r64_rm64, dst, src));
		}

		public void cmova(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmova_r16_rm16, register, in memory));
		}

		public void cmova(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmova_r32_rm32, register, in memory));
		}

		public void cmova(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmova_r64_rm64, register, in memory));
		}

		public void cmovae(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovae_r16_rm16, dst, src));
		}

		public void cmovae(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovae_r32_rm32, dst, src));
		}

		public void cmovae(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovae_r64_rm64, dst, src));
		}

		public void cmovae(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovae_r16_rm16, register, in memory));
		}

		public void cmovae(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovae_r32_rm32, register, in memory));
		}

		public void cmovae(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovae_r64_rm64, register, in memory));
		}

		public void cmovb(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovb_r16_rm16, dst, src));
		}

		public void cmovb(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovb_r32_rm32, dst, src));
		}

		public void cmovb(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovb_r64_rm64, dst, src));
		}

		public void cmovb(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovb_r16_rm16, register, in memory));
		}

		public void cmovb(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovb_r32_rm32, register, in memory));
		}

		public void cmovb(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovb_r64_rm64, register, in memory));
		}

		public void cmovbe(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovbe_r16_rm16, dst, src));
		}

		public void cmovbe(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovbe_r32_rm32, dst, src));
		}

		public void cmovbe(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovbe_r64_rm64, dst, src));
		}

		public void cmovbe(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovbe_r16_rm16, register, in memory));
		}

		public void cmovbe(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovbe_r32_rm32, register, in memory));
		}

		public void cmovbe(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovbe_r64_rm64, register, in memory));
		}

		public void cmovc(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovb_r16_rm16, dst, src));
		}

		public void cmovc(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovb_r32_rm32, dst, src));
		}

		public void cmovc(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovb_r64_rm64, dst, src));
		}

		public void cmovc(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovb_r16_rm16, register, in memory));
		}

		public void cmovc(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovb_r32_rm32, register, in memory));
		}

		public void cmovc(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovb_r64_rm64, register, in memory));
		}

		public void cmove(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Cmove_r16_rm16, dst, src));
		}

		public void cmove(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Cmove_r32_rm32, dst, src));
		}

		public void cmove(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Cmove_r64_rm64, dst, src));
		}

		public void cmove(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmove_r16_rm16, register, in memory));
		}

		public void cmove(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmove_r32_rm32, register, in memory));
		}

		public void cmove(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmove_r64_rm64, register, in memory));
		}

		public void cmovg(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovg_r16_rm16, dst, src));
		}

		public void cmovg(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovg_r32_rm32, dst, src));
		}

		public void cmovg(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovg_r64_rm64, dst, src));
		}

		public void cmovg(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovg_r16_rm16, register, in memory));
		}

		public void cmovg(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovg_r32_rm32, register, in memory));
		}

		public void cmovg(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovg_r64_rm64, register, in memory));
		}

		public void cmovge(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovge_r16_rm16, dst, src));
		}

		public void cmovge(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovge_r32_rm32, dst, src));
		}

		public void cmovge(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovge_r64_rm64, dst, src));
		}

		public void cmovge(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovge_r16_rm16, register, in memory));
		}

		public void cmovge(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovge_r32_rm32, register, in memory));
		}

		public void cmovge(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovge_r64_rm64, register, in memory));
		}

		public void cmovl(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovl_r16_rm16, dst, src));
		}

		public void cmovl(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovl_r32_rm32, dst, src));
		}

		public void cmovl(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovl_r64_rm64, dst, src));
		}

		public void cmovl(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovl_r16_rm16, register, in memory));
		}

		public void cmovl(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovl_r32_rm32, register, in memory));
		}

		public void cmovl(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovl_r64_rm64, register, in memory));
		}

		public void cmovle(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovle_r16_rm16, dst, src));
		}

		public void cmovle(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovle_r32_rm32, dst, src));
		}

		public void cmovle(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovle_r64_rm64, dst, src));
		}

		public void cmovle(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovle_r16_rm16, register, in memory));
		}

		public void cmovle(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovle_r32_rm32, register, in memory));
		}

		public void cmovle(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovle_r64_rm64, register, in memory));
		}

		public void cmovna(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovbe_r16_rm16, dst, src));
		}

		public void cmovna(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovbe_r32_rm32, dst, src));
		}

		public void cmovna(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovbe_r64_rm64, dst, src));
		}

		public void cmovna(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovbe_r16_rm16, register, in memory));
		}

		public void cmovna(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovbe_r32_rm32, register, in memory));
		}

		public void cmovna(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovbe_r64_rm64, register, in memory));
		}

		public void cmovnae(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovb_r16_rm16, dst, src));
		}

		public void cmovnae(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovb_r32_rm32, dst, src));
		}

		public void cmovnae(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovb_r64_rm64, dst, src));
		}

		public void cmovnae(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovb_r16_rm16, register, in memory));
		}

		public void cmovnae(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovb_r32_rm32, register, in memory));
		}

		public void cmovnae(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovb_r64_rm64, register, in memory));
		}

		public void cmovnb(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovae_r16_rm16, dst, src));
		}

		public void cmovnb(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovae_r32_rm32, dst, src));
		}

		public void cmovnb(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovae_r64_rm64, dst, src));
		}

		public void cmovnb(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovae_r16_rm16, register, in memory));
		}

		public void cmovnb(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovae_r32_rm32, register, in memory));
		}

		public void cmovnb(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovae_r64_rm64, register, in memory));
		}

		public void cmovnbe(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Cmova_r16_rm16, dst, src));
		}

		public void cmovnbe(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Cmova_r32_rm32, dst, src));
		}

		public void cmovnbe(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Cmova_r64_rm64, dst, src));
		}

		public void cmovnbe(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmova_r16_rm16, register, in memory));
		}

		public void cmovnbe(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmova_r32_rm32, register, in memory));
		}

		public void cmovnbe(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmova_r64_rm64, register, in memory));
		}

		public void cmovnc(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovae_r16_rm16, dst, src));
		}

		public void cmovnc(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovae_r32_rm32, dst, src));
		}

		public void cmovnc(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovae_r64_rm64, dst, src));
		}

		public void cmovnc(AssemblerRegister16 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovae_r16_rm16, register, in memory));
		}

		public void cmovnc(AssemblerRegister32 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovae_r32_rm32, register, in memory));
		}

		public void cmovnc(AssemblerRegister64 dst, AssemblerMemoryOperand src)
		{
			Register register = dst;
			MemoryOperand memory = src.ToMemoryOperand(Bitness);
			AddInstruction(Instruction.Create(Code.Cmovae_r64_rm64, register, in memory));
		}

		public void cmovne(AssemblerRegister16 dst, AssemblerRegister16 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovne_r16_rm16, dst, src));
		}

		public void cmovne(AssemblerRegister32 dst, AssemblerRegister32 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovne_r32_rm32, dst, src));
		}

		public void cmovne(AssemblerRegister64 dst, AssemblerRegister64 src)
		{
			AddInstruction(Instruction.Create(Code.Cmovne_r64_rm64, dst, src));
		}

		public void cmovne(Assembl

GDWeave/core/Reloaded.Assembler.dll

Decompiled 3 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using Microsoft.CodeAnalysis;
using Reloaded.Assembler.Definitions;
using Reloaded.Assembler.Kernel32;
using Reloaded.Memory.Buffers;
using Reloaded.Memory.Buffers.Internal.Structs;
using Reloaded.Memory.Sources;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCompany("Sewer56")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("LGPL V3")]
[assembly: AssemblyDescription("Minimal .NET wrapper around the simple, easy to use Flat Assembler written by Tomasz Grysztar. Supports both x64 and x86 development.")]
[assembly: AssemblyFileVersion("1.0.14.0")]
[assembly: AssemblyInformationalVersion("1.0.14")]
[assembly: AssemblyProduct("Reloaded")]
[assembly: AssemblyTitle("Reloaded.Assembler")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Reloaded-Project/Reloaded.Assembler")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.14.0")]
[module: UnverifiableCode]
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 NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = P_0;
		}
	}
}
namespace Reloaded.Assembler
{
	public class Assembler : IDisposable
	{
		private object _lock = new object();

		private nuint _textAddress;

		private int _textSize;

		private nuint _resultAddress;

		private int _resultSize;

		private static readonly MemoryBufferHelper _bufferHelper;

		private static readonly Memory _processMemory;

		private readonly FasmDelegates.fasm_Assemble _assembleFunction;

		private readonly FasmDelegates.fasm_GetVersion _getVersionFunction;

		static Assembler()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Expected O, but got Unknown
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			_processMemory = new Memory();
			_bufferHelper = new MemoryBufferHelper(Process.GetCurrentProcess());
		}

		public Assembler(int textSize = 65536, int resultSize = 32768)
		{
			AllocateText(textSize, 3);
			AllocateResult(resultSize, 3);
			IntPtr hModule = Reloaded.Assembler.Kernel32.Kernel32.LoadLibraryW(GetFasmDLLPath());
			IntPtr procAddress = Reloaded.Assembler.Kernel32.Kernel32.GetProcAddress(hModule, "fasm_Assemble");
			IntPtr procAddress2 = Reloaded.Assembler.Kernel32.Kernel32.GetProcAddress(hModule, "fasm_GetVersion");
			_assembleFunction = Marshal.GetDelegateForFunctionPointer<FasmDelegates.fasm_Assemble>(procAddress);
			_getVersionFunction = Marshal.GetDelegateForFunctionPointer<FasmDelegates.fasm_GetVersion>(procAddress2);
		}

		~Assembler()
		{
			Dispose();
		}

		public void Dispose()
		{
			_bufferHelper.Free((UIntPtr)_textAddress);
			_bufferHelper.Free((UIntPtr)_resultAddress);
			GC.SuppressFinalize(this);
		}

		public Version GetVersion()
		{
			int num = _getVersionFunction();
			return new Version(num & 0xFF, (num >> 16) & 0xFF);
		}

		public byte[] AssembleFile(string filePath)
		{
			return Assemble(File.ReadAllLines(filePath), 100);
		}

		public byte[] Assemble(IEnumerable<string> mnemonics, ushort passLimit = 100)
		{
			string mnemonics2 = string.Join(Environment.NewLine, mnemonics);
			return Assemble(mnemonics2, 100);
		}

		public unsafe byte[] Assemble(string mnemonics, ushort passLimit = 100)
		{
			byte[] bytes = Encoding.ASCII.GetBytes(mnemonics + "\0");
			if (bytes.Length > _textSize)
			{
				throw new FasmWrapperException($"Your supplied array of mnemonics to be assembled is too large ({bytes.Length} > {_textSize} bytes)." + "Consider simplifying your code or creating a new Assembler with greater textSize.");
			}
			lock (_lock)
			{
				_processMemory.WriteRaw((UIntPtr)_textAddress, bytes);
				FasmResult num = _assembleFunction((IntPtr)(void*)_textAddress, (IntPtr)(void*)_resultAddress, (IntPtr)_resultSize, passLimit, IntPtr.Zero);
				FasmState fasmState = default(FasmState);
				_processMemory.Read<FasmState>((UIntPtr)_resultAddress, ref fasmState);
				if (num == FasmResult.Ok)
				{
					byte[] array = new byte[fasmState.OutputLength];
					Marshal.Copy((IntPtr)fasmState.OutputData, array, 0, array.Length);
					return array;
				}
				string[] mnemonics2 = mnemonics.Split(new string[1] { Environment.NewLine }, StringSplitOptions.None);
				FasmLineHeader lineHeader = fasmState.GetLineHeader();
				throw new FasmException(fasmState.ErrorCode, fasmState.Condition, lineHeader.LineNumber, mnemonics2);
			}
		}

		private string GetFasmDLLPath()
		{
			if (IntPtr.Size == 4 && File.Exists("FASM.dll"))
			{
				return "FASM.dll";
			}
			if (IntPtr.Size == 8 && File.Exists("FASMX64.dll"))
			{
				return "FASMX64.dll";
			}
			string executingDLLDirectory = GetExecutingDLLDirectory();
			string text = Path.Combine(executingDLLDirectory, "FASM.dll");
			string text2 = Path.Combine(executingDLLDirectory, "FASMX64.dll");
			if (IntPtr.Size == 4 && File.Exists(text))
			{
				return text;
			}
			if (IntPtr.Size == 8 && File.Exists(text2))
			{
				return text2;
			}
			throw new FasmWrapperException("Appropriate FASM DLL for X86/64 has not been found in either current or library directory.");
		}

		private string GetExecutingDLLDirectory()
		{
			return Path.GetDirectoryName(Uri.UnescapeDataString(new UriBuilder(Assembly.GetExecutingAssembly().CodeBase).Path));
		}

		private void AllocateText(int textSize, int retryCount)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			BufferAllocationProperties val = _bufferHelper.Allocate(textSize, (UIntPtr)(nuint)1u, (UIntPtr)(nuint)2147483647u, retryCount);
			_textAddress = val.MemoryAddress;
			_textSize = val.Size;
			if (_textAddress == 0)
			{
				throw new FasmWrapperException("Failed to allocate text memory for Assembler.");
			}
		}

		private void AllocateResult(int resultSize, int retryCount)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			BufferAllocationProperties val = _bufferHelper.Allocate(resultSize, (UIntPtr)(nuint)1u, (UIntPtr)(nuint)2147483647u, retryCount);
			_resultAddress = val.MemoryAddress;
			_resultSize = val.Size;
			if (_resultAddress == 0)
			{
				throw new FasmWrapperException("Failed to allocate result memory for Assembler.");
			}
		}
	}
	public class FasmDelegates
	{
		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		public delegate int fasm_GetVersion();

		[SuppressUnmanagedCodeSecurity]
		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		public delegate FasmResult fasm_Assemble(IntPtr lpSource, IntPtr lpMemory, IntPtr nSize, int nPassesLimit, IntPtr hDisplayPipe);
	}
	[ExcludeFromCodeCoverage]
	public class FasmWrapperException : Exception
	{
		public FasmWrapperException()
		{
		}

		public FasmWrapperException(string message)
			: base(message)
		{
		}

		public FasmWrapperException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		protected FasmWrapperException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
}
namespace Reloaded.Assembler.Kernel32
{
	public class Kernel32
	{
		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		public static extern IntPtr LoadLibraryW(string lpFileName);

		[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
		public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
	}
}
namespace Reloaded.Assembler.Definitions
{
	public enum FasmErrors
	{
		FileNotFound = -101,
		ErrorReadingFile = -102,
		InvalidFileFormat = -103,
		InvalidMacroArguments = -104,
		IncompleteMacro = -105,
		UnexpectedCharacters = -106,
		InvalidArgument = -107,
		IllegalInstruction = -108,
		InvalidOperand = -109,
		InvalidOperandSize = -110,
		OperandSizeNotSpecified = -111,
		OperandSizesDoNotMatch = -112,
		InvalidAddressSize = -113,
		AddressSizesDoNotAgree = -114,
		DisallowedCombinationOfRegisters = -115,
		LongImmediateNotEncodable = -116,
		RelativeJumpOutOfRange = -117,
		InvalidExpression = -118,
		InvalidAddress = -119,
		InvalidValue = -120,
		ValueOutOfRange = -121,
		UndefinedSymbol = -122,
		InvalidUseOfSymbol = -123,
		NameTooLong = -124,
		InvalidName = -125,
		ReservedWordUsedAsSymbol = -126,
		SymbolAlreadyDefined = -127,
		MissingEndQuote = -128,
		MissingEndDirective = -129,
		UnexpectedInstruction = -130,
		ExtraCharactersOnLine = -131,
		SectionNotAlignedEnough = -132,
		SettingAlreadySpecified = -133,
		DataAlreadyDefined = -134,
		TooManyRepeats = -135,
		SymbolOutOfScope = -136,
		UserError = -140,
		AssertionFailed = -141
	}
	public class FasmException : Exception
	{
		public FasmErrors ErrorCode { get; private set; }

		public FasmResult Result { get; private set; }

		public int Line { get; private set; }

		public string[] Mnemonics { get; private set; }

		public FasmException(FasmErrors errorCode, FasmResult condition, int lineNumber, string[] mnemonics)
			: base($"Failed to assemble FASM Mnemonics: Error name: {errorCode.ToString()}, Line Number: {lineNumber}, Result: {condition.ToString()}")
		{
			Result = condition;
			ErrorCode = errorCode;
			Line = lineNumber;
			Mnemonics = mnemonics;
		}
	}
	[StructLayout(LayoutKind.Explicit)]
	public struct FasmLineHeader
	{
		[FieldOffset(0)]
		public int FilePathPtr;

		[FieldOffset(4)]
		public int LineNumber;

		[FieldOffset(8)]
		public int FileOffset;

		[FieldOffset(8)]
		public int MacroCallingFilePtr;

		[FieldOffset(12)]
		public int MacroLinePtr;
	}
	public enum FasmResult
	{
		Ok = 0,
		Working = 1,
		Error = 2,
		InvalidParameter = -1,
		OutOfMemory = -2,
		StackOverflow = -3,
		SourceNotFound = -4,
		UnexpectedEndOfSource = -5,
		CannotGenerateCode = -6,
		FormatLimitationsExcedded = -7,
		WriteFailed = -8
	}
	[StructLayout(LayoutKind.Explicit)]
	public struct FasmState
	{
		[FieldOffset(0)]
		public FasmResult Condition;

		[FieldOffset(4)]
		public int OutputLength;

		[FieldOffset(4)]
		public FasmErrors ErrorCode;

		[FieldOffset(8)]
		public int OutputData;

		[FieldOffset(8)]
		public int ErrorLine;

		public unsafe FasmLineHeader GetLineHeader()
		{
			return *(FasmLineHeader*)ErrorLine;
		}
	}
}

GDWeave/core/Reloaded.Hooks.Definitions.dll

Decompiled 3 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using Microsoft.CodeAnalysis;
using Reloaded.Hooks.Definitions.Enums;
using Reloaded.Hooks.Definitions.Internal;
using Reloaded.Hooks.Definitions.X64;
using Reloaded.Hooks.Definitions.X86;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCompany("Sewer56")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Contains the definitions and attributes used in the Reloaded.Hooks library and their corresponding interfaces.")]
[assembly: AssemblyFileVersion("1.15.0.0")]
[assembly: AssemblyInformationalVersion("1.15.0")]
[assembly: AssemblyProduct("Reloaded.Hooks")]
[assembly: AssemblyTitle("Reloaded.Hooks.Definitions")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Reloaded-Project/Reloaded.Hooks")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.15.0.0")]
[module: UnverifiableCode]
[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 NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = 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 Reloaded.Hooks.Definitions
{
	public class AsmHookOptions
	{
		public bool PreferRelativeJump { get; set; }

		public AsmHookBehaviour Behaviour { get; set; }

		public int hookLength { get; set; } = -1;


		public int MaxOpcodeSize { get; set; } = 7;

	}
	public class FunctionHookOptions : Attribute
	{
		public bool PreferRelativeJump { get; set; }

		public bool SearchInModules { get; set; }

		public bool VerifyJumpTargetsModule { get; set; }
	}
	public interface IAsmHook
	{
		bool IsEnabled { get; }

		IAsmHook Activate();

		void Enable();

		void Disable();
	}
	public interface IFunction<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>
	{
		long Address { get; }

		IReloadedHooks Hooks { get; }

		IHook<TFunction> Hook(TFunction function, int minHookLength);

		IHook<TFunction> Hook(TFunction function);

		unsafe IHook<TFunction> Hook(void* function, int minHookLength);

		unsafe IHook<TFunction> Hook(void* function);

		IHook<TFunction> Hook([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type type, string methodName, int minHookLength);

		IHook<TFunction> Hook([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type type, string methodName);

		unsafe IHook<TFunctionType> HookAs<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunctionType>(void* function, int minHookLength);

		unsafe IHook<TFunctionType> HookAs<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunctionType>(void* function);

		IHook<TFunctionType> HookAs<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunctionType>([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type type, string methodName, int minHookLength);

		IHook<TFunctionType> HookAs<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunctionType>([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type type, string methodName);

		TFunction GetWrapper(out IntPtr wrapperAddress);

		TFunction GetWrapper();

		IAsmHook MakeAsmHook(string[] asmCode, AsmHookBehaviour behaviour = AsmHookBehaviour.ExecuteFirst, int hookLength = -1);

		IAsmHook MakeAsmHook(byte[] asmCode, AsmHookBehaviour behaviour = AsmHookBehaviour.ExecuteFirst, int hookLength = -1);
	}
	public interface IFunctionPtr<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TDelegate> where TDelegate : Delegate
	{
		ulong FunctionPointer { get; }

		TDelegate this[int index] { get; }

		IntPtr GetFunctionAddress(int index = 0);

		TDelegate GetDelegate(int index = 0);
	}
	public interface IHook
	{
		bool IsHookEnabled { get; }

		bool IsHookActivated { get; }

		IntPtr OriginalFunctionAddress { get; }

		IntPtr OriginalFunctionWrapperAddress { get; }

		IHook Activate()
		{
			throw new NotImplementedException("Activate is not implemented. Most likely this code was built before IHook<T> split into IHook and IHook<T>.");
		}

		void Disable()
		{
			throw new NotImplementedException("Disable is not implemented. Most likely this code was built before IHook<T> split into IHook and IHook<T>.");
		}

		void Enable()
		{
			throw new NotImplementedException("Enable is not implemented. Most likely this code was built before IHook<T> split into IHook and IHook<T>.");
		}
	}
	public interface IHook<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction> : IHook
	{
		TFunction OriginalFunction { get; }

		IReverseWrapper<TFunction> ReverseWrapper { get; }

		new bool IsHookEnabled { get; }

		new bool IsHookActivated { get; }

		new IntPtr OriginalFunctionAddress { get; }

		new IntPtr OriginalFunctionWrapperAddress { get; }

		new IHook<TFunction> Activate();

		new void Disable();

		new void Enable();
	}
	public interface IReloadedHooks
	{
		IReloadedHooksUtilities Utilities { get; }

		IFunction<TFunction> CreateFunction<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(long address);

		IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(TFunction function, long functionAddress);

		unsafe IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(void* targetAddress, long functionAddress);

		IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(TFunction function, long functionAddress, int minHookLength);

		unsafe IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(void* targetAddress, long functionAddress, int minHookLength);

		IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(TFunction function, long functionAddress, int minHookLength, FunctionHookOptions options);

		unsafe IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(void* targetAddress, long functionAddress, int minHookLength, FunctionHookOptions options);

		IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type type, string methodName, long functionAddress, int minHookLength, FunctionHookOptions options);

		IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type type, string methodName, long functionAddress, int minHookLength);

		IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type type, string methodName, long functionAddress);

		TFunction CreateWrapper<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(long functionAddress, out IntPtr wrapperAddress);

		IntPtr CreateWrapper<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(long functionAddress);

		IntPtr CreateNativeWrapperX86<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(IntPtr functionAddress, Reloaded.Hooks.Definitions.X86.IFunctionAttribute fromConvention);

		IntPtr CreateNativeWrapperX86<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(IntPtr functionAddress, Reloaded.Hooks.Definitions.X86.IFunctionAttribute fromConvention, Reloaded.Hooks.Definitions.X86.IFunctionAttribute toConvention);

		IntPtr CreateNativeWrapperX64<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(IntPtr functionAddress, Reloaded.Hooks.Definitions.X64.IFunctionAttribute fromConvention, Reloaded.Hooks.Definitions.X64.IFunctionAttribute toConvention);

		IReverseWrapper<TFunction> CreateReverseWrapper<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(TFunction function);

		IReverseWrapper<TFunction> CreateReverseWrapper<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(IntPtr function);

		IVirtualFunctionTable VirtualFunctionTableFromObject(IntPtr objectAddress, int numberOfMethods);

		IVirtualFunctionTable VirtualFunctionTableFromAddress(IntPtr tableAddress, int numberOfMethods);

		IFunctionPtr<TDelegate> CreateFunctionPtr<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TDelegate>(ulong functionPointer) where TDelegate : Delegate;

		IAsmHook CreateAsmHook(string[] asmCode, long functionAddress);

		IAsmHook CreateAsmHook(string asmCode, long functionAddress);

		IAsmHook CreateAsmHook(byte[] asmCode, long functionAddress);

		IAsmHook CreateAsmHook(string[] asmCode, long functionAddress, AsmHookBehaviour behaviour);

		IAsmHook CreateAsmHook(string asmCode, long functionAddress, AsmHookBehaviour behaviour);

		IAsmHook CreateAsmHook(byte[] asmCode, long functionAddress, AsmHookBehaviour behaviour);

		IAsmHook CreateAsmHook(string[] asmCode, long functionAddress, AsmHookBehaviour behaviour, int hookLength);

		IAsmHook CreateAsmHook(string asmCode, long functionAddress, AsmHookBehaviour behaviour, int hookLength);

		IAsmHook CreateAsmHook(byte[] asmCode, long functionAddress, AsmHookBehaviour behaviour, int hookLength);

		IAsmHook CreateAsmHook(string[] asmCode, long functionAddress, AsmHookOptions options);

		IAsmHook CreateAsmHook(string asmCode, long functionAddress, AsmHookOptions options);

		IAsmHook CreateAsmHook(byte[] asmCode, long functionAddress, AsmHookOptions options);

		IVirtualFunctionTable HookedVirtualFunctionTableFromObject(IntPtr objectAddress, int numberOfMethods);
	}
	public interface IReloadedHooksUtilities
	{
		byte[] AssembleAbsoluteJump(IntPtr target, bool is64bit);

		byte[] AssemblePushReturn(IntPtr target, bool is64bit);

		byte[] AssembleRelativeJump(IntPtr relativeJumpOffset, bool is64bit);

		byte[] AssembleRelativeJump(IntPtr currentAddress, IntPtr targetAddress, bool is64bit);

		string GetAbsoluteJumpMnemonics(IntPtr target, bool is64bit);

		string GetAbsoluteCallMnemonics(IntPtr target, bool is64bit);

		string GetAbsoluteJumpMnemonics<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(TFunction function, out IReverseWrapper<TFunction> reverseWrapper) where TFunction : Delegate;

		string GetAbsoluteCallMnemonics<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(TFunction function, out IReverseWrapper<TFunction> reverseWrapper) where TFunction : Delegate;

		string GetPushReturnMnemonics(IntPtr target, bool is64bit);

		string GetRelativeJumpMnemonics(IntPtr relativeJumpOffset, bool is64bit);

		IntPtr InsertJump(byte[] opcodes, bool is64bit, long jumpTarget, long targetAddress = 0L, long maxDisplacement = 2147483647L);

		int GetHookLength(IntPtr hookAddress, int hookLength, bool is64Bit);

		int GetNumberofParameters([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] Type delegateType);

		int GetNumberofParametersWithoutFloats([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] Type delegateType);

		int GetNumberofParameters<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>();

		int GetNumberofParametersWithoutFloats<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>();

		string PushCdeclCallerSavedRegisters();

		string PopCdeclCallerSavedRegisters();

		IntPtr WritePointer(IntPtr target);

		unsafe void* GetFunctionPointer([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type type, string name);

		(long min, long max) GetRelativeJumpMinMax(long targetAddress, long maxDisplacement = 2147483647L);
	}
	public interface IReverseWrapper
	{
		IntPtr NativeFunctionPtr { get; }

		IntPtr WrapperPointer { get; }
	}
	public interface IReverseWrapper<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction> : IReverseWrapper
	{
		TFunction CSharpFunction { get; }

		new IntPtr NativeFunctionPtr { get; }

		new IntPtr WrapperPointer { get; }
	}
	public interface IVirtualFunctionTable
	{
		List<TableEntry> TableEntries { get; set; }

		TableEntry this[int i] { get; set; }

		TFunction CreateWrapperFunction<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(int index);

		IHook<TFunction> CreateFunctionHook<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes)] TFunction>(int index, TFunction delegateType);
	}
	public struct TableEntry
	{
		public IntPtr EntryAddress;

		public IntPtr FunctionPointer;
	}
}
namespace Reloaded.Hooks.Definitions.X86
{
	public enum CallingConventions
	{
		Cdecl,
		Stdcall,
		Fastcall,
		MicrosoftThiscall,
		GCCThiscall,
		Usercall,
		Userpurge,
		ClrCall
	}
	public class FunctionAttribute : Attribute, IFunctionAttribute
	{
		public enum Register
		{
			eax,
			ebx,
			ecx,
			edx,
			esi,
			edi,
			ebp,
			esp
		}

		public enum StackCleanup
		{
			None,
			Caller,
			Callee
		}

		public static FunctionAttribute Cdecl = new FunctionAttribute(CallingConventions.Cdecl);

		public static FunctionAttribute StdCall = new FunctionAttribute(CallingConventions.Stdcall);

		public static FunctionAttribute Fastcall = new FunctionAttribute(CallingConventions.Fastcall);

		public static FunctionAttribute GccThiscall = new FunctionAttribute(CallingConventions.GCCThiscall);

		public static FunctionAttribute MicrosoftThiscall = new FunctionAttribute(CallingConventions.MicrosoftThiscall);

		public static Register[] DefaultSavedRegisters { get; } = new Register[3]
		{
			Register.ebx,
			Register.esi,
			Register.edi
		};


		public Register[] SourceRegisters { get; }

		public Register ReturnRegister { get; }

		public StackCleanup Cleanup { get; }

		public int ReservedStackSpace { get; }

		public Register[] CalleeSavedRegisters { get; } = DefaultSavedRegisters;


		public FunctionAttribute(Register[] sourceRegisters, Register returnRegister, StackCleanup stackCleanup, int reservedStackSpace = 0)
		{
			SourceRegisters = sourceRegisters;
			ReturnRegister = returnRegister;
			Cleanup = stackCleanup;
			ReservedStackSpace = reservedStackSpace;
		}

		public FunctionAttribute(Register[] sourceRegisters, Register returnRegister, StackCleanup stackCleanup, Register[] calleeSavedRegisters, int reservedStackSpace = 0)
		{
			SourceRegisters = sourceRegisters;
			ReturnRegister = returnRegister;
			Cleanup = stackCleanup;
			ReservedStackSpace = reservedStackSpace;
			CalleeSavedRegisters = calleeSavedRegisters;
		}

		public FunctionAttribute(Register sourceRegister, Register returnRegister, StackCleanup stackCleanup, int reservedStackSpace = 0)
		{
			SourceRegisters = new Register[1] { sourceRegister };
			ReturnRegister = returnRegister;
			Cleanup = stackCleanup;
			ReservedStackSpace = reservedStackSpace;
			CalleeSavedRegisters = DefaultSavedRegisters;
		}

		public FunctionAttribute(Register sourceRegister, Register returnRegister, StackCleanup stackCleanup, Register[] calleeSavedRegisters, int reservedStackSpace = 0)
		{
			SourceRegisters = new Register[1] { sourceRegister };
			ReturnRegister = returnRegister;
			Cleanup = stackCleanup;
			ReservedStackSpace = reservedStackSpace;
			CalleeSavedRegisters = calleeSavedRegisters;
		}

		public FunctionAttribute(CallingConventions callingConvention)
		{
			switch (callingConvention)
			{
			case CallingConventions.Cdecl:
				SourceRegisters = new Register[0];
				ReturnRegister = Register.eax;
				Cleanup = StackCleanup.Caller;
				CalleeSavedRegisters = DefaultSavedRegisters;
				break;
			case CallingConventions.Stdcall:
				SourceRegisters = new Register[0];
				ReturnRegister = Register.eax;
				Cleanup = StackCleanup.Callee;
				CalleeSavedRegisters = DefaultSavedRegisters;
				break;
			case CallingConventions.Fastcall:
				SourceRegisters = new Register[2]
				{
					Register.ecx,
					Register.edx
				};
				ReturnRegister = Register.eax;
				Cleanup = StackCleanup.Caller;
				CalleeSavedRegisters = DefaultSavedRegisters;
				break;
			case CallingConventions.MicrosoftThiscall:
				SourceRegisters = new Register[1] { Register.ecx };
				ReturnRegister = Register.eax;
				Cleanup = StackCleanup.Callee;
				CalleeSavedRegisters = DefaultSavedRegisters;
				break;
			case CallingConventions.GCCThiscall:
				SourceRegisters = new Register[0];
				ReturnRegister = Register.eax;
				Cleanup = StackCleanup.Caller;
				CalleeSavedRegisters = DefaultSavedRegisters;
				break;
			case CallingConventions.ClrCall:
				SourceRegisters = new Register[2]
				{
					Register.ecx,
					Register.edx
				};
				ReturnRegister = Register.eax;
				Cleanup = StackCleanup.Callee;
				CalleeSavedRegisters = DefaultSavedRegisters;
				break;
			default:
				throw new ArgumentException("There is no preset for the specified calling convention " + callingConvention.GetType().Name);
			}
		}

		public bool IsEquivalent(UnmanagedFunctionPointerAttribute attribute)
		{
			if (attribute == null)
			{
				return Equals(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? StdCall : Cdecl);
			}
			return attribute.CallingConvention switch
			{
				CallingConvention.Cdecl => Equals(Cdecl), 
				CallingConvention.StdCall => Equals(StdCall), 
				CallingConvention.ThisCall => Equals(MicrosoftThiscall), 
				_ => false, 
			};
		}

		public IFunctionAttribute GetEquivalent(UnmanagedFunctionPointerAttribute attribute)
		{
			if (attribute == null)
			{
				if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
				{
					return Cdecl;
				}
				return StdCall;
			}
			return attribute.CallingConvention switch
			{
				CallingConvention.Cdecl => Cdecl, 
				CallingConvention.StdCall => StdCall, 
				CallingConvention.ThisCall => MicrosoftThiscall, 
				CallingConvention.FastCall => Fastcall, 
				CallingConvention.Winapi => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? StdCall : Cdecl, 
				_ => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? StdCall : Cdecl, 
			};
		}

		public static IFunctionAttribute GetAttribute<TFunction>()
		{
			if (Misc.TryGetAttribute<TFunction, FunctionAttribute>(out var result))
			{
				return result;
			}
			throw new Exception("FunctionAttribute is missing in the " + typeof(TFunction).Name + " delegate declaration.Please mark the " + typeof(TFunction).Name + " with an appropriate FunctionAttribute");
		}

		[ExcludeFromCodeCoverage]
		public override bool Equals(object obj)
		{
			if (!(obj is FunctionAttribute functionAttribute))
			{
				return false;
			}
			if (functionAttribute.Cleanup == Cleanup && functionAttribute.ReturnRegister == ReturnRegister && functionAttribute.SourceRegisters.SequenceEqual(SourceRegisters))
			{
				return functionAttribute.CalleeSavedRegisters.SequenceEqual(CalleeSavedRegisters);
			}
			return false;
		}

		[ExcludeFromCodeCoverage]
		public override int GetHashCode()
		{
			int num = 13;
			Register[] sourceRegisters = SourceRegisters;
			foreach (Register register in sourceRegisters)
			{
				num = (int)(num * 7 + register);
			}
			num = (int)(num * 7 + ReturnRegister);
			num = (int)(num * 7 + Cleanup);
			sourceRegisters = CalleeSavedRegisters;
			foreach (Register register2 in sourceRegisters)
			{
				num = (int)(num * 7 + register2);
			}
			return num;
		}
	}
	public interface IFunctionAttribute
	{
		FunctionAttribute.Register[] SourceRegisters { get; }

		FunctionAttribute.Register ReturnRegister { get; }

		FunctionAttribute.StackCleanup Cleanup { get; }

		int ReservedStackSpace { get; }

		FunctionAttribute.Register[] CalleeSavedRegisters { get; }

		bool IsEquivalent(UnmanagedFunctionPointerAttribute attribute);

		IFunctionAttribute GetEquivalent(UnmanagedFunctionPointerAttribute attribute);
	}
	public class ManagedFunctionAttribute : FunctionAttribute
	{
		public ManagedFunctionAttribute(Register[] sourceRegisters, Register returnRegister, StackCleanup stackCleanup)
			: base(sourceRegisters, returnRegister, stackCleanup)
		{
		}

		public ManagedFunctionAttribute(Register[] sourceRegisters, Register returnRegister, StackCleanup stackCleanup, Register[] calleeSavedRegisters)
			: base(sourceRegisters, returnRegister, stackCleanup, calleeSavedRegisters)
		{
		}

		public ManagedFunctionAttribute(Register sourceRegister, Register returnRegister, StackCleanup stackCleanup)
			: base(sourceRegister, returnRegister, stackCleanup)
		{
		}

		public ManagedFunctionAttribute(Register sourceRegister, Register returnRegister, StackCleanup stackCleanup, Register[] calleeSavedRegisters)
			: base(sourceRegister, returnRegister, stackCleanup, calleeSavedRegisters)
		{
		}

		public ManagedFunctionAttribute(Register[] sourceRegisters, Register returnRegister, StackCleanup stackCleanup, int reservedStackSpace)
			: base(sourceRegisters, returnRegister, stackCleanup, reservedStackSpace)
		{
		}

		public ManagedFunctionAttribute(Register[] sourceRegisters, Register returnRegister, StackCleanup stackCleanup, Register[] calleeSavedRegisters, int reservedStackSpace)
			: base(sourceRegisters, returnRegister, stackCleanup, calleeSavedRegisters, reservedStackSpace)
		{
		}

		public ManagedFunctionAttribute(Register sourceRegister, Register returnRegister, StackCleanup stackCleanup, int reservedStackSpace)
			: base(sourceRegister, returnRegister, stackCleanup, reservedStackSpace)
		{
		}

		public ManagedFunctionAttribute(Register sourceRegister, Register returnRegister, StackCleanup stackCleanup, Register[] calleeSavedRegisters, int reservedStackSpace)
			: base(sourceRegister, returnRegister, stackCleanup, calleeSavedRegisters, reservedStackSpace)
		{
		}

		public ManagedFunctionAttribute(CallingConventions callingConvention)
			: base(callingConvention)
		{
		}
	}
}
namespace Reloaded.Hooks.Definitions.X64
{
	public enum CallingConventions
	{
		Microsoft,
		SystemV,
		Custom
	}
	public class FunctionAttribute : Attribute, IFunctionAttribute
	{
		public enum Register
		{
			rax,
			rbx,
			rcx,
			rdx,
			rsi,
			rdi,
			rbp,
			rsp,
			r8,
			r9,
			r10,
			r11,
			r12,
			r13,
			r14,
			r15
		}

		public static Register[] DefaultSavedRegisters { get; } = new Register[7]
		{
			Register.rbx,
			Register.rdi,
			Register.rsi,
			Register.r12,
			Register.r13,
			Register.r14,
			Register.r15
		};


		public static FunctionAttribute Microsoft { get; } = new FunctionAttribute(CallingConventions.Microsoft);


		public static FunctionAttribute SystemV { get; } = new FunctionAttribute(CallingConventions.SystemV);


		public Register[] SourceRegisters { get; }

		public Register ReturnRegister { get; }

		public bool ShadowSpace { get; } = true;


		public Register[] CalleeSavedRegisters { get; } = DefaultSavedRegisters;


		public FunctionAttribute(Register[] sourceRegisters, Register returnRegister, bool shadowSpace)
		{
			SourceRegisters = sourceRegisters;
			ReturnRegister = returnRegister;
			ShadowSpace = shadowSpace;
		}

		public FunctionAttribute(Register sourceRegister, Register returnRegister, bool shadowSpace)
		{
			SourceRegisters = new Register[1] { sourceRegister };
			ReturnRegister = returnRegister;
			ShadowSpace = shadowSpace;
			CalleeSavedRegisters = DefaultSavedRegisters;
		}

		public FunctionAttribute(Register sourceRegister, Register returnRegister, bool shadowSpace, Register[] calleeSavedRegisters)
		{
			SourceRegisters = new Register[1] { sourceRegister };
			ReturnRegister = returnRegister;
			ShadowSpace = shadowSpace;
			CalleeSavedRegisters = calleeSavedRegisters;
		}

		public FunctionAttribute(Register[] sourceRegisters, Register returnRegister, bool shadowSpace, Register[] calleeSavedRegisters)
		{
			SourceRegisters = sourceRegisters;
			ReturnRegister = returnRegister;
			ShadowSpace = shadowSpace;
			CalleeSavedRegisters = calleeSavedRegisters;
		}

		public FunctionAttribute(CallingConventions callingConvention)
		{
			switch (callingConvention)
			{
			case CallingConventions.Microsoft:
				SourceRegisters = new Register[4]
				{
					Register.rcx,
					Register.rdx,
					Register.r8,
					Register.r9
				};
				CalleeSavedRegisters = new Register[7]
				{
					Register.rbx,
					Register.rdi,
					Register.rsi,
					Register.r12,
					Register.r13,
					Register.r14,
					Register.r15
				};
				ReturnRegister = Register.rax;
				ShadowSpace = true;
				break;
			case CallingConventions.SystemV:
				SourceRegisters = new Register[6]
				{
					Register.rdi,
					Register.rsi,
					Register.rdx,
					Register.rcx,
					Register.r8,
					Register.r9
				};
				CalleeSavedRegisters = new Register[5]
				{
					Register.rbx,
					Register.r12,
					Register.r13,
					Register.r14,
					Register.r15
				};
				ReturnRegister = Register.rax;
				ShadowSpace = false;
				break;
			default:
				throw new ArgumentException("There is no preset for the specified calling convention " + callingConvention.GetType().Name);
			}
		}

		public static IFunctionAttribute GetAttribute<TFunction>()
		{
			object[] customAttributes = typeof(TFunction).GetCustomAttributes(inherit: false);
			for (int i = 0; i < customAttributes.Length; i++)
			{
				if ((Attribute)customAttributes[i] is FunctionAttribute result)
				{
					return result;
				}
			}
			return new FunctionAttribute(CallingConventions.Microsoft);
		}

		[ExcludeFromCodeCoverage]
		public override bool Equals(object obj)
		{
			if (!(obj is FunctionAttribute functionAttribute))
			{
				return false;
			}
			if (functionAttribute.ShadowSpace == ShadowSpace && functionAttribute.ReturnRegister == ReturnRegister && functionAttribute.SourceRegisters.SequenceEqual(SourceRegisters))
			{
				return functionAttribute.CalleeSavedRegisters.SequenceEqual(CalleeSavedRegisters);
			}
			return false;
		}

		[ExcludeFromCodeCoverage]
		public override int GetHashCode()
		{
			int num = 13;
			Register[] sourceRegisters = SourceRegisters;
			foreach (Register register in sourceRegisters)
			{
				num = (int)(num * 7 + register);
			}
			num = (int)(num * 7 + ReturnRegister);
			num = num * 7 + ShadowSpace.GetHashCode();
			sourceRegisters = CalleeSavedRegisters;
			foreach (Register register2 in sourceRegisters)
			{
				num = (int)(num * 7 + register2);
			}
			return num;
		}
	}
	public interface IFunctionAttribute
	{
		FunctionAttribute.Register[] SourceRegisters { get; }

		FunctionAttribute.Register ReturnRegister { get; }

		bool ShadowSpace { get; }

		FunctionAttribute.Register[] CalleeSavedRegisters { get; }
	}
}
namespace Reloaded.Hooks.Definitions.Structs
{
	[ExcludeFromCodeCoverage]
	public struct FuncPtr<TReturn> : IFuncPtr
	{
		public unsafe void* funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<TReturn> Invoke => (delegate* unmanaged[Stdcall]<TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<TReturn> InvokeDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl]<TReturn> InvokeAsCdecl => (delegate* unmanaged[Cdecl]<TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl, SuppressGCTransition]<TReturn> InvokeAsCdeclDangerous => (delegate* unmanaged[Cdecl, SuppressGCTransition]<TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<TReturn> InvokeAsStdcall => (delegate* unmanaged[Stdcall]<TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<TReturn> InvokeAsStdcallDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall]<TReturn> InvokeAsThiscall => (delegate* unmanaged[Thiscall]<TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall, SuppressGCTransition]<TReturn> InvokeAsThiscallDangerous => (delegate* unmanaged[Thiscall, SuppressGCTransition]<TReturn>)funcPtr;

		public int NumberOfParameters => FuncPtr.GetNumberOfParameters(typeof(FuncPtr<TReturn>));

		public int NumberOfParametersWithoutFloats => FuncPtr.GetNumberOfParametersWithoutFloats(typeof(FuncPtr<TReturn>));

		public unsafe FuncPtr(void* ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl]<TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl, SuppressGCTransition]<TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall]<TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall, SuppressGCTransition]<TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall]<TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall, SuppressGCTransition]<TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe static explicit operator void*(FuncPtr<TReturn> func)
		{
			return func.funcPtr;
		}

		public unsafe static implicit operator FuncPtr<TReturn>(void* ptr)
		{
			return new FuncPtr<TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<TReturn>(IntPtr ptr)
		{
			return new FuncPtr<TReturn>((void*)ptr);
		}

		public unsafe static implicit operator FuncPtr<TReturn>(delegate* unmanaged[Cdecl]<TReturn> ptr)
		{
			return new FuncPtr<TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<TReturn>(delegate* unmanaged[Cdecl, SuppressGCTransition]<TReturn> ptr)
		{
			return new FuncPtr<TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<TReturn>(delegate* unmanaged[Stdcall]<TReturn> ptr)
		{
			return new FuncPtr<TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<TReturn>(delegate* unmanaged[Stdcall, SuppressGCTransition]<TReturn> ptr)
		{
			return new FuncPtr<TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<TReturn>(delegate* unmanaged[Thiscall]<TReturn> ptr)
		{
			return new FuncPtr<TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<TReturn>(delegate* unmanaged[Thiscall, SuppressGCTransition]<TReturn> ptr)
		{
			return new FuncPtr<TReturn>(ptr);
		}
	}
	[ExcludeFromCodeCoverage]
	public struct FuncPtr<T1, TReturn> : IFuncPtr
	{
		public unsafe void* funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, TReturn> Invoke => (delegate* unmanaged[Stdcall]<T1, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, TReturn> InvokeDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl]<T1, TReturn> InvokeAsCdecl => (delegate* unmanaged[Cdecl]<T1, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, TReturn> InvokeAsCdeclDangerous => (delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, TReturn> InvokeAsStdcall => (delegate* unmanaged[Stdcall]<T1, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, TReturn> InvokeAsStdcallDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall]<T1, TReturn> InvokeAsThiscall => (delegate* unmanaged[Thiscall]<T1, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, TReturn> InvokeAsThiscallDangerous => (delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, TReturn>)funcPtr;

		public int NumberOfParameters => FuncPtr.GetNumberOfParameters(typeof(FuncPtr<T1, TReturn>));

		public int NumberOfParametersWithoutFloats => FuncPtr.GetNumberOfParametersWithoutFloats(typeof(FuncPtr<T1, TReturn>));

		public unsafe FuncPtr(void* ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl]<T1, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall]<T1, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall]<T1, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe static explicit operator void*(FuncPtr<T1, TReturn> func)
		{
			return func.funcPtr;
		}

		public unsafe static implicit operator FuncPtr<T1, TReturn>(void* ptr)
		{
			return new FuncPtr<T1, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, TReturn>(IntPtr ptr)
		{
			return new FuncPtr<T1, TReturn>((void*)ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, TReturn>(delegate* unmanaged[Cdecl]<T1, TReturn> ptr)
		{
			return new FuncPtr<T1, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, TReturn>(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, TReturn> ptr)
		{
			return new FuncPtr<T1, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, TReturn>(delegate* unmanaged[Stdcall]<T1, TReturn> ptr)
		{
			return new FuncPtr<T1, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, TReturn>(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, TReturn> ptr)
		{
			return new FuncPtr<T1, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, TReturn>(delegate* unmanaged[Thiscall]<T1, TReturn> ptr)
		{
			return new FuncPtr<T1, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, TReturn>(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, TReturn> ptr)
		{
			return new FuncPtr<T1, TReturn>(ptr);
		}
	}
	[ExcludeFromCodeCoverage]
	public struct FuncPtr<T1, T2, TReturn> : IFuncPtr
	{
		public unsafe void* funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, TReturn> Invoke => (delegate* unmanaged[Stdcall]<T1, T2, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, TReturn> InvokeDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl]<T1, T2, TReturn> InvokeAsCdecl => (delegate* unmanaged[Cdecl]<T1, T2, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, TReturn> InvokeAsCdeclDangerous => (delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, TReturn> InvokeAsStdcall => (delegate* unmanaged[Stdcall]<T1, T2, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, TReturn> InvokeAsStdcallDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall]<T1, T2, TReturn> InvokeAsThiscall => (delegate* unmanaged[Thiscall]<T1, T2, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, TReturn> InvokeAsThiscallDangerous => (delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, TReturn>)funcPtr;

		public int NumberOfParameters => FuncPtr.GetNumberOfParameters(typeof(FuncPtr<T1, T2, TReturn>));

		public int NumberOfParametersWithoutFloats => FuncPtr.GetNumberOfParametersWithoutFloats(typeof(FuncPtr<T1, T2, TReturn>));

		public unsafe FuncPtr(void* ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl]<T1, T2, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall]<T1, T2, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall]<T1, T2, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe static explicit operator void*(FuncPtr<T1, T2, TReturn> func)
		{
			return func.funcPtr;
		}

		public unsafe static implicit operator FuncPtr<T1, T2, TReturn>(void* ptr)
		{
			return new FuncPtr<T1, T2, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, TReturn>(IntPtr ptr)
		{
			return new FuncPtr<T1, T2, TReturn>((void*)ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, TReturn>(delegate* unmanaged[Cdecl]<T1, T2, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, TReturn>(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, TReturn>(delegate* unmanaged[Stdcall]<T1, T2, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, TReturn>(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, TReturn>(delegate* unmanaged[Thiscall]<T1, T2, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, TReturn>(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, TReturn>(ptr);
		}
	}
	[ExcludeFromCodeCoverage]
	public struct FuncPtr<T1, T2, T3, TReturn> : IFuncPtr
	{
		public unsafe void* funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, TReturn> Invoke => (delegate* unmanaged[Stdcall]<T1, T2, T3, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, TReturn> InvokeDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl]<T1, T2, T3, TReturn> InvokeAsCdecl => (delegate* unmanaged[Cdecl]<T1, T2, T3, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, TReturn> InvokeAsCdeclDangerous => (delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, TReturn> InvokeAsStdcall => (delegate* unmanaged[Stdcall]<T1, T2, T3, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, TReturn> InvokeAsStdcallDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall]<T1, T2, T3, TReturn> InvokeAsThiscall => (delegate* unmanaged[Thiscall]<T1, T2, T3, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, TReturn> InvokeAsThiscallDangerous => (delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, TReturn>)funcPtr;

		public int NumberOfParameters => FuncPtr.GetNumberOfParameters(typeof(FuncPtr<T1, T2, T3, TReturn>));

		public int NumberOfParametersWithoutFloats => FuncPtr.GetNumberOfParametersWithoutFloats(typeof(FuncPtr<T1, T2, T3, TReturn>));

		public unsafe FuncPtr(void* ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl]<T1, T2, T3, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall]<T1, T2, T3, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall]<T1, T2, T3, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe static explicit operator void*(FuncPtr<T1, T2, T3, TReturn> func)
		{
			return func.funcPtr;
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, TReturn>(void* ptr)
		{
			return new FuncPtr<T1, T2, T3, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, TReturn>(IntPtr ptr)
		{
			return new FuncPtr<T1, T2, T3, TReturn>((void*)ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, TReturn>(delegate* unmanaged[Cdecl]<T1, T2, T3, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, TReturn>(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, TReturn>(delegate* unmanaged[Stdcall]<T1, T2, T3, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, TReturn>(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, TReturn>(delegate* unmanaged[Thiscall]<T1, T2, T3, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, TReturn>(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, TReturn>(ptr);
		}
	}
	[ExcludeFromCodeCoverage]
	public struct FuncPtr<T1, T2, T3, T4, TReturn> : IFuncPtr
	{
		public unsafe void* funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, TReturn> Invoke => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, TReturn> InvokeDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl]<T1, T2, T3, T4, TReturn> InvokeAsCdecl => (delegate* unmanaged[Cdecl]<T1, T2, T3, T4, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, TReturn> InvokeAsCdeclDangerous => (delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, TReturn> InvokeAsStdcall => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, TReturn> InvokeAsStdcallDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall]<T1, T2, T3, T4, TReturn> InvokeAsThiscall => (delegate* unmanaged[Thiscall]<T1, T2, T3, T4, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, TReturn> InvokeAsThiscallDangerous => (delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, TReturn>)funcPtr;

		public int NumberOfParameters => FuncPtr.GetNumberOfParameters(typeof(FuncPtr<T1, T2, T3, T4, TReturn>));

		public int NumberOfParametersWithoutFloats => FuncPtr.GetNumberOfParametersWithoutFloats(typeof(FuncPtr<T1, T2, T3, T4, TReturn>));

		public unsafe FuncPtr(void* ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe static explicit operator void*(FuncPtr<T1, T2, T3, T4, TReturn> func)
		{
			return func.funcPtr;
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, TReturn>(void* ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, TReturn>(IntPtr ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, TReturn>((void*)ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, TReturn>(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, TReturn>(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, TReturn>(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, TReturn>(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, TReturn>(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, TReturn>(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, TReturn>(ptr);
		}
	}
	[ExcludeFromCodeCoverage]
	public struct FuncPtr<T1, T2, T3, T4, T5, TReturn> : IFuncPtr
	{
		public unsafe void* funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, TReturn> Invoke => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, TReturn> InvokeDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, TReturn> InvokeAsCdecl => (delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, TReturn> InvokeAsCdeclDangerous => (delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, TReturn> InvokeAsStdcall => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, TReturn> InvokeAsStdcallDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, TReturn> InvokeAsThiscall => (delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, TReturn> InvokeAsThiscallDangerous => (delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, TReturn>)funcPtr;

		public int NumberOfParameters => FuncPtr.GetNumberOfParameters(typeof(FuncPtr<T1, T2, T3, T4, T5, TReturn>));

		public int NumberOfParametersWithoutFloats => FuncPtr.GetNumberOfParametersWithoutFloats(typeof(FuncPtr<T1, T2, T3, T4, T5, TReturn>));

		public unsafe FuncPtr(void* ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe static explicit operator void*(FuncPtr<T1, T2, T3, T4, T5, TReturn> func)
		{
			return func.funcPtr;
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, TReturn>(void* ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, TReturn>(IntPtr ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, TReturn>((void*)ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, TReturn>(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, TReturn>(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, TReturn>(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, TReturn>(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, TReturn>(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, TReturn>(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, TReturn>(ptr);
		}
	}
	[ExcludeFromCodeCoverage]
	public struct FuncPtr<T1, T2, T3, T4, T5, T6, TReturn> : IFuncPtr
	{
		public unsafe void* funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, TReturn> Invoke => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, TReturn> InvokeDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, TReturn> InvokeAsCdecl => (delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, TReturn> InvokeAsCdeclDangerous => (delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, TReturn> InvokeAsStdcall => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, TReturn> InvokeAsStdcallDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, TReturn> InvokeAsThiscall => (delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, TReturn> InvokeAsThiscallDangerous => (delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, TReturn>)funcPtr;

		public int NumberOfParameters => FuncPtr.GetNumberOfParameters(typeof(FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>));

		public int NumberOfParametersWithoutFloats => FuncPtr.GetNumberOfParametersWithoutFloats(typeof(FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>));

		public unsafe FuncPtr(void* ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe static explicit operator void*(FuncPtr<T1, T2, T3, T4, T5, T6, TReturn> func)
		{
			return func.funcPtr;
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>(void* ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>(IntPtr ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>((void*)ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, TReturn>(ptr);
		}
	}
	[ExcludeFromCodeCoverage]
	public struct FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn> : IFuncPtr
	{
		public unsafe void* funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, TReturn> Invoke => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, TReturn> InvokeDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, TReturn> InvokeAsCdecl => (delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, TReturn> InvokeAsCdeclDangerous => (delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, TReturn> InvokeAsStdcall => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, TReturn> InvokeAsStdcallDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, TReturn> InvokeAsThiscall => (delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, TReturn> InvokeAsThiscallDangerous => (delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, TReturn>)funcPtr;

		public int NumberOfParameters => FuncPtr.GetNumberOfParameters(typeof(FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>));

		public int NumberOfParametersWithoutFloats => FuncPtr.GetNumberOfParametersWithoutFloats(typeof(FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>));

		public unsafe FuncPtr(void* ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe static explicit operator void*(FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn> func)
		{
			return func.funcPtr;
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>(void* ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>(IntPtr ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>((void*)ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, TReturn>(ptr);
		}
	}
	[ExcludeFromCodeCoverage]
	public struct FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> : IFuncPtr
	{
		public unsafe void* funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> Invoke => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> InvokeDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> InvokeAsCdecl => (delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> InvokeAsCdeclDangerous => (delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> InvokeAsStdcall => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> InvokeAsStdcallDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> InvokeAsThiscall => (delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> InvokeAsThiscallDangerous => (delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>)funcPtr;

		public int NumberOfParameters => FuncPtr.GetNumberOfParameters(typeof(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>));

		public int NumberOfParametersWithoutFloats => FuncPtr.GetNumberOfParametersWithoutFloats(typeof(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>));

		public unsafe FuncPtr(void* ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe static explicit operator void*(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> func)
		{
			return func.funcPtr;
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>(void* ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>(IntPtr ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>((void*)ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, TReturn>(ptr);
		}
	}
	[ExcludeFromCodeCoverage]
	public struct FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> : IFuncPtr
	{
		public unsafe void* funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> Invoke => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> InvokeDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> InvokeAsCdecl => (delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> InvokeAsCdeclDangerous => (delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> InvokeAsStdcall => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> InvokeAsStdcallDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> InvokeAsThiscall => (delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> InvokeAsThiscallDangerous => (delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>)funcPtr;

		public int NumberOfParameters => FuncPtr.GetNumberOfParameters(typeof(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>));

		public int NumberOfParametersWithoutFloats => FuncPtr.GetNumberOfParametersWithoutFloats(typeof(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>));

		public unsafe FuncPtr(void* ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe static explicit operator void*(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> func)
		{
			return func.funcPtr;
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>(void* ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>(IntPtr ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>((void*)ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, TReturn>(ptr);
		}
	}
	[ExcludeFromCodeCoverage]
	public struct FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> : IFuncPtr
	{
		public unsafe void* funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> Invoke => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> InvokeDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> InvokeAsCdecl => (delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> InvokeAsCdeclDangerous => (delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> InvokeAsStdcall => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> InvokeAsStdcallDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> InvokeAsThiscall => (delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> InvokeAsThiscallDangerous => (delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>)funcPtr;

		public int NumberOfParameters => FuncPtr.GetNumberOfParameters(typeof(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>));

		public int NumberOfParametersWithoutFloats => FuncPtr.GetNumberOfParametersWithoutFloats(typeof(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>));

		public unsafe FuncPtr(void* ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe static explicit operator void*(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> func)
		{
			return func.funcPtr;
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>(void* ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>(IntPtr ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>((void*)ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TReturn>(ptr);
		}
	}
	[ExcludeFromCodeCoverage]
	public struct FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> : IFuncPtr
	{
		public unsafe void* funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> Invoke => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> InvokeDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> InvokeAsCdecl => (delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> InvokeAsCdeclDangerous => (delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> InvokeAsStdcall => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> InvokeAsStdcallDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> InvokeAsThiscall => (delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> InvokeAsThiscallDangerous => (delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>)funcPtr;

		public int NumberOfParameters => FuncPtr.GetNumberOfParameters(typeof(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>));

		public int NumberOfParametersWithoutFloats => FuncPtr.GetNumberOfParametersWithoutFloats(typeof(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>));

		public unsafe FuncPtr(void* ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe static explicit operator void*(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> func)
		{
			return func.funcPtr;
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>(void* ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>(IntPtr ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>((void*)ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TReturn>(ptr);
		}
	}
	[ExcludeFromCodeCoverage]
	public struct FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> : IFuncPtr
	{
		public unsafe void* funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> Invoke => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> InvokeDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> InvokeAsCdecl => (delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> InvokeAsCdeclDangerous => (delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> InvokeAsStdcall => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> InvokeAsStdcallDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> InvokeAsThiscall => (delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> InvokeAsThiscallDangerous => (delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>)funcPtr;

		public int NumberOfParameters => FuncPtr.GetNumberOfParameters(typeof(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>));

		public int NumberOfParametersWithoutFloats => FuncPtr.GetNumberOfParametersWithoutFloats(typeof(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>));

		public unsafe FuncPtr(void* ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe static explicit operator void*(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> func)
		{
			return func.funcPtr;
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>(void* ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>(IntPtr ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>((void*)ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TReturn>(ptr);
		}
	}
	[ExcludeFromCodeCoverage]
	public struct FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> : IFuncPtr
	{
		public unsafe void* funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> Invoke => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> InvokeDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> InvokeAsCdecl => (delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> InvokeAsCdeclDangerous => (delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> InvokeAsStdcall => (delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> InvokeAsStdcallDangerous => (delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> InvokeAsThiscall => (delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>)funcPtr;

		public unsafe delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> InvokeAsThiscallDangerous => (delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>)funcPtr;

		public int NumberOfParameters => FuncPtr.GetNumberOfParameters(typeof(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>));

		public int NumberOfParametersWithoutFloats => FuncPtr.GetNumberOfParametersWithoutFloats(typeof(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>));

		public unsafe FuncPtr(void* ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe FuncPtr(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> ptr)
		{
			funcPtr = ptr;
		}

		public unsafe static explicit operator void*(FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> func)
		{
			return func.funcPtr;
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>(void* ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>(IntPtr ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>((void*)ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>(delegate* unmanaged[Cdecl]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>(delegate* unmanaged[Cdecl, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>(delegate* unmanaged[Stdcall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>(delegate* unmanaged[Stdcall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>(delegate* unmanaged[Thiscall]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>(ptr);
		}

		public unsafe static implicit operator FuncPtr<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn>(delegate* unmanaged[Thiscall, SuppressGCTransition]<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TReturn> ptr)
		{
			return new FuncPtr<T1, T2, T

GDWeave/core/Reloaded.Hooks.dll

Decompiled 3 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using Iced.Intel;
using Microsoft.CodeAnalysis;
using Reloaded.Assembler;
using Reloaded.Hooks.Definitions;
using Reloaded.Hooks.Definitions.Enums;
using Reloaded.Hooks.Definitions.Helpers;
using Reloaded.Hooks.Definitions.Internal;
using Reloaded.Hooks.Definitions.Structs;
using Reloaded.Hooks.Definitions.X64;
using Reloaded.Hooks.Definitions.X86;
using Reloaded.Hooks.Internal;
using Reloaded.Hooks.Tools;
using Reloaded.Hooks.X64;
using Reloaded.Hooks.X86;
using Reloaded.Memory.Buffers;
using Reloaded.Memory.Sources;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(/*Could not decode attribute arguments.*/)]
[assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCompany("Sewer56")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Advanced native function hooks for x86, x64. Welcome to the next level!")]
[assembly: AssemblyFileVersion("4.3.0.0")]
[assembly: AssemblyInformationalVersion("4.3.0")]
[assembly: AssemblyProduct("Reloaded.Hooks")]
[assembly: AssemblyTitle("Reloaded.Hooks")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Reloaded-Project/Reloaded.Hooks")]
[assembly: SecurityPermission(8, SkipVerification = true)]
[assembly: AssemblyVersion("4.3.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : System.Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(/*Could not decode attribute arguments.*/)]
	internal sealed class NullableAttribute : System.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]
	[Embedded]
	[AttributeUsage(/*Could not decode attribute arguments.*/)]
	internal sealed class RefSafetyRulesAttribute : System.Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
public static class VirtualFunctionTableHelpers
{
	public static List<TableEntry> GetAddresses(nuint tablePointer, int numberOfMethods)
	{
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		List<TableEntry> val = new List<TableEntry>();
		nint functionPointer = default(nint);
		for (int i = 0; i < numberOfMethods; i++)
		{
			nuint num = tablePointer + (nuint)(System.IntPtr.Size * i);
			MemoryExtensions.SafeRead<Memory, nint>(Memory.CurrentProcess, (System.UIntPtr)num, ref functionPointer);
			val.Add(new TableEntry
			{
				EntryAddress = AddressExtensions.ToSigned((System.UIntPtr)num),
				FunctionPointer = functionPointer
			});
		}
		return val;
	}
}
namespace Reloaded.Hooks
{
	public class AsmHook : IAsmHook
	{
		private static Memory _memory = Memory.CurrentProcess;

		private Patch _activateHookPatch;

		private Patch _disableHookPatch;

		private Patch _enableHookPatch;

		private bool _activated;

		private readonly bool _is64Bit;

		private List<Patch>? _otherHookPatches;

		[field: CompilerGenerated]
		public bool IsEnabled
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		private unsafe AsmHook()
		{
			_is64Bit = sizeof(nuint) == 8;
		}

		public AsmHook(string[] asmCode, nuint functionAddress, AsmHookBehaviour behaviour = 0, int hookLength = -1)
			: this(Utilities.Assembler.Assemble((System.Collections.Generic.IEnumerable<string>)asmCode, (ushort)100), functionAddress, new AsmHookOptions
			{
				Behaviour = behaviour,
				hookLength = hookLength
			})
		{
		}//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Expected O, but got Unknown


		public AsmHook(string asmCode, nuint functionAddress, AsmHookBehaviour behaviour = 0, int hookLength = -1)
			: this(Utilities.Assembler.Assemble(asmCode, (ushort)100), functionAddress, new AsmHookOptions
			{
				Behaviour = behaviour,
				hookLength = hookLength
			})
		{
		}//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Expected O, but got Unknown


		public AsmHook(byte[] asmCode, nuint functionAddress, AsmHookBehaviour behaviour = 0, int hookLength = -1)
			: this(asmCode, functionAddress, new AsmHookOptions
			{
				Behaviour = behaviour,
				hookLength = hookLength
			})
		{
		}//IL_0003: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Expected O, but got Unknown


		public AsmHook(string[] asmCode, nuint functionAddress, AsmHookOptions options = null)
			: this(Utilities.Assembler.Assemble((System.Collections.Generic.IEnumerable<string>)asmCode, (ushort)100), functionAddress, options)
		{
		}

		public AsmHook(string asmCode, nuint functionAddress, AsmHookOptions options = null)
			: this(Utilities.Assembler.Assemble(asmCode, (ushort)100), functionAddress, options)
		{
		}

		public AsmHook(byte[] asmCode, nuint functionAddress, AsmHookOptions options = null)
			: this()
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			AsmHook asmHook = this;
			if (options == null)
			{
				options = new AsmHookOptions();
			}
			if (options.hookLength == -1)
			{
				options.hookLength = Utilities.GetHookLength(functionAddress, options.MaxOpcodeSize, _is64Bit);
			}
			byte[] originalFunction = default(byte[]);
			MemoryExtensions.SafeReadRaw<Memory>(Memory.CurrentProcess, (System.UIntPtr)functionAddress, ref originalFunction, options.hookLength);
			nuint jumpBackAddress = functionAddress + (nuint)options.hookLength;
			int num = (originalFunction.Length / 2 + 1) * 4;
			int codeAlignment = 16;
			int num2 = 3;
			int num3 = codeAlignment * num2;
			int num4 = (_is64Bit ? 8 : 4);
			int num5 = num4 * 2;
			int num6 = asmCode.Length + options.hookLength + 8;
			int num7 = options.hookLength + 8 + num4;
			int num8 = 8 + num6 + num7 + num3 + num5 + num;
			ValueTuple<nuint, nuint> relativeJumpMinMax = Utilities.GetRelativeJumpMinMax(functionAddress, 2147483647 - num8);
			MemoryBuffer buffer = Utilities.FindOrCreateBufferInRange(num8, relativeJumpMinMax.Item1, relativeJumpMinMax.Item2);
			buffer.ExecuteWithLock<bool>((Func<bool>)delegate
			{
				try
				{
					return asmHook.MakeAsmHook(asmCode, functionAddress, options, originalFunction, buffer, codeAlignment, jumpBackAddress);
				}
				catch (System.Exception)
				{
					FunctionPatch functionPatch = new FunctionPatcher(asmHook._is64Bit).Patch(Enumerable.ToList<byte>((System.Collections.Generic.IEnumerable<byte>)originalFunction), functionAddress);
					originalFunction = functionPatch.NewFunction.ToArray();
					asmHook._otherHookPatches = functionPatch.Patches;
					return asmHook.MakeAsmHook(asmCode, functionAddress, options, originalFunction, buffer, codeAlignment, jumpBackAddress);
				}
			});
		}

		private bool MakeAsmHook(byte[] asmCode, nuint functionAddress, AsmHookOptions options, byte[] originalFunction, MemoryBuffer buffer, int codeAlignment, nuint jumpBackAddress)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			IcedPatcher patcher = new IcedPatcher(_is64Bit, originalFunction, functionAddress);
			buffer.SetAlignment(codeAlignment);
			nuint targetAddress = MakeHookStub(buffer, patcher, asmCode, originalFunction.Length, jumpBackAddress, options.Behaviour);
			buffer.SetAlignment(codeAlignment);
			nuint targetAddress2 = MakeOriginalStub(buffer, patcher, originalFunction.Length, jumpBackAddress);
			buffer.SetAlignment(codeAlignment);
			MemoryBufferProperties properties = buffer.Properties;
			System.UIntPtr writePointer = ((MemoryBufferProperties)(ref properties)).WritePointer;
			byte[] bytes = Utilities.AssembleRelativeJump(writePointer, targetAddress2, _is64Bit);
			byte[] array = Utilities.AssembleRelativeJump(writePointer, targetAddress, _is64Bit);
			nuint num = buffer.Add(array, codeAlignment);
			_disableHookPatch = new Patch(num, bytes);
			_enableHookPatch = new Patch(num, array);
			List<byte> val = (options.PreferRelativeJump ? Enumerable.ToList<byte>((System.Collections.Generic.IEnumerable<byte>)Utilities.AssembleRelativeJump(functionAddress, num, _is64Bit)) : Enumerable.ToList<byte>((System.Collections.Generic.IEnumerable<byte>)Utilities.AssembleAbsoluteJump(num, _is64Bit)));
			Utilities.FillArrayUntilSize(val, (byte)144, options.hookLength);
			_activateHookPatch = new Patch(functionAddress, val.ToArray());
			return true;
		}

		private nuint MakeHookStub(MemoryBuffer buffer, IcedPatcher patcher, byte[] asmCode, int originalCodeLength, nuint jumpBackAddress, AsmHookBehaviour behaviour)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected I4, but got Unknown
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			List<byte> val = new List<byte>(asmCode.Length + originalCodeLength);
			MemoryBufferProperties properties;
			switch ((int)behaviour)
			{
			case 0:
				val.AddRange((System.Collections.Generic.IEnumerable<byte>)asmCode);
				properties = buffer.Properties;
				val.AddRange((System.Collections.Generic.IEnumerable<byte>)patcher.EncodeForNewAddress((nuint)((nint)(nuint)((MemoryBufferProperties)(ref properties)).WritePointer + val.Count)));
				break;
			case 1:
				properties = buffer.Properties;
				val.AddRange((System.Collections.Generic.IEnumerable<byte>)patcher.EncodeForNewAddress((nuint)((nint)(nuint)((MemoryBufferProperties)(ref properties)).WritePointer + val.Count)));
				val.AddRange((System.Collections.Generic.IEnumerable<byte>)asmCode);
				break;
			case 2:
				val.AddRange((System.Collections.Generic.IEnumerable<byte>)asmCode);
				break;
			default:
				throw new ArgumentOutOfRangeException("behaviour", (object)behaviour, (string)null);
			}
			properties = buffer.Properties;
			byte[] array = Utilities.AssembleRelativeJump((nuint)((nint)(nuint)((MemoryBufferProperties)(ref properties)).WritePointer + val.Count), jumpBackAddress, _is64Bit);
			val.AddRange((System.Collections.Generic.IEnumerable<byte>)array);
			return buffer.Add(val.ToArray(), 1);
		}

		private nuint MakeOriginalStub(MemoryBuffer buffer, IcedPatcher patcher, int originalCodeLength, nuint jumpBackAddress)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			List<byte> val = new List<byte>(originalCodeLength);
			MemoryBufferProperties properties = buffer.Properties;
			val.AddRange((System.Collections.Generic.IEnumerable<byte>)patcher.EncodeForNewAddress(((MemoryBufferProperties)(ref properties)).WritePointer));
			properties = buffer.Properties;
			byte[] array = Utilities.AssembleRelativeJump((nuint)((nint)(nuint)((MemoryBufferProperties)(ref properties)).WritePointer + val.Count), jumpBackAddress, _is64Bit);
			val.AddRange((System.Collections.Generic.IEnumerable<byte>)array);
			return buffer.Add(val.ToArray(), 1);
		}

		public IAsmHook Activate()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			if (_activated)
			{
				return (IAsmHook)(object)this;
			}
			_activated = true;
			_activateHookPatch.Apply();
			_enableHookPatch.ApplyUnsafe();
			if (_otherHookPatches == null)
			{
				return (IAsmHook)(object)this;
			}
			Enumerator<Patch> enumerator = _otherHookPatches.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					enumerator.Current.Apply();
				}
				return (IAsmHook)(object)this;
			}
			finally
			{
				((System.IDisposable)enumerator).Dispose();
			}
		}

		public void Enable()
		{
			_enableHookPatch.ApplyUnsafe();
			IsEnabled = true;
		}

		public void Disable()
		{
			_disableHookPatch.ApplyUnsafe();
			IsEnabled = false;
		}
	}
	internal class Constants
	{
		internal const int MaxAbsJmpSize = 8;
	}
	public class Function<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction> : IFunction<TFunction>
	{
		private bool _wrapperCreated;

		private TFunction _wrapper;

		private nuint _wrapperAddress;

		private nuint _address;

		public long Address => (long)AddressExtensions.ToSigned((System.UIntPtr)_address);

		public IReloadedHooks Hooks
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		public Function(nuint address, IReloadedHooks hooks)
		{
			_address = address;
			Hooks = hooks;
		}

		public IHook<TFunction> Hook(TFunction function, int minHookLength)
		{
			return Hooks.CreateHook<TFunction>(function, Address, minHookLength);
		}

		public IHook<TFunction> Hook(TFunction function)
		{
			return Hook(function, -1);
		}

		public unsafe IHook<TFunction> Hook(void* function, int minHookLength)
		{
			return Hooks.CreateHook<TFunction>(function, Address, minHookLength);
		}

		public unsafe IHook<TFunction> Hook(void* function)
		{
			return Hook(function, -1);
		}

		public IHook<TFunction> Hook([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type type, string methodName, int minHookLength)
		{
			return Hooks.CreateHook<TFunction>(type, methodName, Address, minHookLength);
		}

		public IHook<TFunction> Hook([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type type, string methodName)
		{
			return Hook(type, methodName, -1);
		}

		public unsafe IHook<TFunctionType> HookAs<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunctionType>(void* function, int minHookLength)
		{
			return Hooks.CreateHook<TFunctionType>(function, Address, minHookLength);
		}

		public unsafe IHook<TFunctionType> HookAs<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunctionType>(void* function)
		{
			return HookAs<TFunctionType>(function, -1);
		}

		public IHook<TFunctionType> HookAs<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunctionType>([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type type, string methodName, int minHookLength)
		{
			return Hooks.CreateHook<TFunctionType>(type, methodName, Address, minHookLength);
		}

		public IHook<TFunctionType> HookAs<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunctionType>([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type type, string methodName)
		{
			return HookAs<TFunctionType>(type, methodName, -1);
		}

		public TFunction GetWrapper()
		{
			if (!_wrapperCreated)
			{
				nint num = default(nint);
				_wrapper = Hooks.CreateWrapper<TFunction>(Address, ref num);
				_wrapperAddress = AddressExtensions.ToUnsigned((System.IntPtr)num);
				_wrapperCreated = true;
			}
			return _wrapper;
		}

		public TFunction GetWrapper(out nint wrapperAddress)
		{
			if (!_wrapperCreated)
			{
				nint num = default(nint);
				_wrapper = Hooks.CreateWrapper<TFunction>(Address, ref num);
				_wrapperAddress = AddressExtensions.ToUnsigned((System.IntPtr)num);
				_wrapperCreated = true;
			}
			wrapperAddress = AddressExtensions.ToSigned((System.UIntPtr)_wrapperAddress);
			return _wrapper;
		}

		public IAsmHook MakeAsmHook(string[] asmCode, AsmHookBehaviour behaviour = 0, int hookLength = -1)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			return Hooks.CreateAsmHook(asmCode, Address, behaviour, hookLength);
		}

		public IAsmHook MakeAsmHook(byte[] asmCode, AsmHookBehaviour behaviour = 0, int hookLength = -1)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			return Hooks.CreateAsmHook(asmCode, Address, behaviour, hookLength);
		}
	}
	public class Hook<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction> : IHook<TFunction>, IHook
	{
		private Patch _hookPatch;

		private List<Patch> _otherHookPatches;

		private Patch _disableHookPatch;

		private Patch _enableHookPatch;

		private bool _is64Bit;

		public bool IsHookEnabled
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		public bool IsHookActivated
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		public TFunction OriginalFunction
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		public nint OriginalFunctionAddress
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		public nint OriginalFunctionWrapperAddress
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		public IReverseWrapper<TFunction> ReverseWrapper
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		public unsafe Hook(TFunction function, nuint functionAddress, int minHookLength = -1, FunctionHookOptions options = null)
		{
			_is64Bit = sizeof(nint) == 8;
			ReverseWrapper = CreateReverseWrapper(function);
			CreateHook(functionAddress, minHookLength, options);
		}

		public unsafe Hook(void* targetAddress, nuint functionAddress, int minHookLength = -1, FunctionHookOptions options = null)
		{
			_is64Bit = sizeof(nint) == 8;
			ReverseWrapper = CreateReverseWrapper(targetAddress);
			CreateHook(functionAddress, minHookLength, options);
		}

		private void CreateHook(nuint functionAddress, int minHookLength = -1, FunctionHookOptions options = null)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			if (options == null)
			{
				Misc.TryGetAttribute<TFunction, FunctionHookOptions>(ref options);
				if (options == null)
				{
					options = new FunctionHookOptions();
				}
			}
			bool isRelative;
			List<byte> val = (options.PreferRelativeJump ? Utilities.TryAssembleRelativeJump(functionAddress, AddressExtensions.ToUnsigned(ReverseWrapper.WrapperPointer), _is64Bit, out isRelative) : Enumerable.ToList<byte>((System.Collections.Generic.IEnumerable<byte>)Utilities.AssembleAbsoluteJump(AddressExtensions.ToUnsigned(ReverseWrapper.WrapperPointer), _is64Bit)));
			if (minHookLength == -1)
			{
				minHookLength = Utilities.GetHookLength(functionAddress, val.Count, _is64Bit);
			}
			Utilities.FillArrayUntilSize(val, (byte)144, minHookLength);
			byte[] array = default(byte[]);
			MemoryExtensions.SafeReadRaw<Memory>(Memory.CurrentProcess, (System.UIntPtr)functionAddress, ref array, minHookLength);
			FunctionPatch functionPatch = new FunctionPatcher(_is64Bit, options).Patch(Enumerable.ToList<byte>((System.Collections.Generic.IEnumerable<byte>)array), functionAddress);
			nuint num = functionAddress + (nuint)minHookLength;
			IcedPatcher icedPatcher = new IcedPatcher(_is64Bit, functionPatch.NewFunction.ToArray(), functionAddress);
			OriginalFunctionAddress = AddressExtensions.ToSigned((System.UIntPtr)icedPatcher.ToMemoryBuffer(num));
			OriginalFunction = CreateWrapper(icedPatcher.ToMemoryBuffer(null), out var wrapperAddress);
			OriginalFunctionWrapperAddress = AddressExtensions.ToSigned((System.UIntPtr)wrapperAddress);
			_otherHookPatches = functionPatch.Patches;
			_hookPatch = new Patch(functionAddress, val.ToArray());
		}

		public IHook<TFunction> Activate()
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			byte[] array = Utilities.AssembleAbsoluteJump(AddressExtensions.ToUnsigned((System.IntPtr)OriginalFunctionAddress), _is64Bit);
			byte[] bytes = default(byte[]);
			MemoryExtensions.SafeReadRaw<Memory>(Memory.CurrentProcess, AddressExtensions.ToUnsigned(ReverseWrapper.WrapperPointer), ref bytes, array.Length);
			_disableHookPatch = new Patch(AddressExtensions.ToUnsigned(ReverseWrapper.WrapperPointer), array);
			_enableHookPatch = new Patch(AddressExtensions.ToUnsigned(ReverseWrapper.WrapperPointer), bytes);
			_hookPatch.Apply();
			Enumerator<Patch> enumerator = _otherHookPatches.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					enumerator.Current.Apply();
				}
			}
			finally
			{
				((System.IDisposable)enumerator).Dispose();
			}
			IsHookEnabled = true;
			IsHookActivated = true;
			return this;
		}

		IHook IHook.Activate()
		{
			return (IHook)(object)Activate();
		}

		public void Disable()
		{
			if (IsHookActivated)
			{
				_disableHookPatch.ApplyUnsafe();
				IsHookEnabled = false;
			}
		}

		public void Enable()
		{
			if (IsHookActivated)
			{
				_enableHookPatch.ApplyUnsafe();
				IsHookEnabled = true;
			}
		}

		protected IReverseWrapper<TFunction> CreateReverseWrapper(TFunction function)
		{
			if (_is64Bit)
			{
				return new Reloaded.Hooks.X64.ReverseWrapper<TFunction>(function);
			}
			return new Reloaded.Hooks.X86.ReverseWrapper<TFunction>(function);
		}

		protected unsafe IReverseWrapper<TFunction> CreateReverseWrapper(void* function)
		{
			if (_is64Bit)
			{
				return new Reloaded.Hooks.X64.ReverseWrapper<TFunction>((nuint)function);
			}
			return new Reloaded.Hooks.X86.ReverseWrapper<TFunction>((nuint)function);
		}

		protected TFunction CreateWrapper(nuint functionAddress, out nuint wrapperAddress)
		{
			if (_is64Bit)
			{
				return Reloaded.Hooks.X64.Wrapper.Create<TFunction>(functionAddress, out wrapperAddress);
			}
			return Reloaded.Hooks.X86.Wrapper.Create<TFunction>(functionAddress, out wrapperAddress);
		}
	}
	[ExcludeFromCodeCoverage]
	public class HookException : System.Exception
	{
		public HookException()
		{
		}

		public HookException(string message)
			: base(message)
		{
		}

		public HookException(string message, System.Exception innerException)
			: base(message, innerException)
		{
		}

		protected HookException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}//IL_0002: Unknown result type (might be due to invalid IL or missing references)

	}
	public class ReloadedHooks : IReloadedHooks
	{
		[field: CompilerGenerated]
		public static ReloadedHooks Instance
		{
			[CompilerGenerated]
			get;
		} = new ReloadedHooks();


		[field: CompilerGenerated]
		public IReloadedHooksUtilities Utilities
		{
			[CompilerGenerated]
			get;
		} = (IReloadedHooksUtilities)(object)ReloadedHooksUtilities.Instance;


		public IFunction<TFunction> CreateFunction<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(long address)
		{
			return new Function<TFunction>((nuint)AddressExtensions.ToUnsigned(address), (IReloadedHooks)(object)this);
		}

		public IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(TFunction function, long functionAddress)
		{
			return CreateHook(function, functionAddress, -1);
		}

		public unsafe IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(void* targetAddress, long functionAddress)
		{
			return CreateHook<TFunction>(targetAddress, functionAddress, -1);
		}

		public IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(TFunction function, long functionAddress, int minHookLength)
		{
			return new Hook<TFunction>(function, (nuint)AddressExtensions.ToUnsigned(functionAddress), minHookLength);
		}

		public unsafe IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(void* targetAddress, long functionAddress, int minHookLength)
		{
			return new Hook<TFunction>(targetAddress, (nuint)AddressExtensions.ToUnsigned(functionAddress), minHookLength);
		}

		public IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(TFunction function, long functionAddress, int minHookLength, FunctionHookOptions options)
		{
			return new Hook<TFunction>(function, (nuint)AddressExtensions.ToUnsigned(functionAddress), minHookLength, options);
		}

		public unsafe IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(void* targetAddress, long functionAddress, int minHookLength, FunctionHookOptions options)
		{
			return new Hook<TFunction>(targetAddress, (nuint)AddressExtensions.ToUnsigned(functionAddress), minHookLength, options);
		}

		public unsafe IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type type, string methodName, long functionAddress, int minHookLength)
		{
			return CreateHook<TFunction>(Instance.Utilities.GetFunctionPointer(type, methodName), functionAddress, minHookLength);
		}

		public IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type type, string methodName, long functionAddress)
		{
			return CreateHook<TFunction>(type, methodName, functionAddress, -1);
		}

		public unsafe IHook<TFunction> CreateHook<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type type, string methodName, long functionAddress, int minHookLength, FunctionHookOptions options)
		{
			return CreateHook<TFunction>(Instance.Utilities.GetFunctionPointer(type, methodName), functionAddress, minHookLength, options);
		}

		public nint CreateNativeWrapperX86<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(nint functionAddress, IFunctionAttribute fromConvention)
		{
			return AddressExtensions.ToSigned((System.UIntPtr)Reloaded.Hooks.X86.Wrapper.Create<TFunction>(AddressExtensions.ToUnsigned((System.IntPtr)functionAddress), fromConvention, FunctionAttribute.GetAttribute<TFunction>().GetEquivalent(Misc.TryGetAttributeOrDefault<TFunction, UnmanagedFunctionPointerAttribute>())));
		}

		public nint CreateNativeWrapperX86<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(nint functionAddress, IFunctionAttribute fromConvention, IFunctionAttribute toConvention)
		{
			return AddressExtensions.ToSigned((System.UIntPtr)Reloaded.Hooks.X86.Wrapper.Create<TFunction>(AddressExtensions.ToUnsigned((System.IntPtr)functionAddress), fromConvention, toConvention));
		}

		public nint CreateNativeWrapperX64<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(nint functionAddress, IFunctionAttribute fromConvention, IFunctionAttribute toConvention)
		{
			return AddressExtensions.ToSigned((System.UIntPtr)Reloaded.Hooks.X64.Wrapper.Create<TFunction>(AddressExtensions.ToUnsigned((System.IntPtr)functionAddress), fromConvention, toConvention));
		}

		public unsafe nint CreateWrapper<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(long functionAddress)
		{
			nuint wrapperAddress;
			if (sizeof(nint) == 4)
			{
				return AddressExtensions.ToSigned((System.UIntPtr)Reloaded.Hooks.X86.Wrapper.CreatePointer<TFunction>((nuint)AddressExtensions.ToUnsigned(functionAddress), out wrapperAddress));
			}
			return AddressExtensions.ToSigned((System.UIntPtr)Reloaded.Hooks.X64.Wrapper.CreatePointer<TFunction>((nuint)AddressExtensions.ToUnsigned(functionAddress), out wrapperAddress));
		}

		public unsafe TFunction CreateWrapper<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(long functionAddress, out nint wrapperAddress)
		{
			nuint wrapperAddress2;
			if (sizeof(nint) == 4)
			{
				TFunction result = Reloaded.Hooks.X86.Wrapper.Create<TFunction>((nuint)AddressExtensions.ToUnsigned(functionAddress), out wrapperAddress2);
				wrapperAddress = AddressExtensions.ToSigned((System.UIntPtr)wrapperAddress2);
				return result;
			}
			TFunction result2 = Reloaded.Hooks.X64.Wrapper.Create<TFunction>((nuint)AddressExtensions.ToUnsigned(functionAddress), out wrapperAddress2);
			wrapperAddress = AddressExtensions.ToSigned((System.UIntPtr)wrapperAddress2);
			return result2;
		}

		public unsafe IReverseWrapper<TFunction> CreateReverseWrapper<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(TFunction function)
		{
			if (sizeof(nint) == 4)
			{
				return new Reloaded.Hooks.X86.ReverseWrapper<TFunction>(function);
			}
			return new Reloaded.Hooks.X64.ReverseWrapper<TFunction>(function);
		}

		public unsafe IReverseWrapper<TFunction> CreateReverseWrapper<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(nint function)
		{
			if (sizeof(nint) == 4)
			{
				return new Reloaded.Hooks.X86.ReverseWrapper<TFunction>(AddressExtensions.ToUnsigned((System.IntPtr)function));
			}
			return new Reloaded.Hooks.X64.ReverseWrapper<TFunction>(AddressExtensions.ToUnsigned((System.IntPtr)function));
		}

		public IVirtualFunctionTable HookedVirtualFunctionTableFromObject(nint objectAddress, int numberOfMethods)
		{
			return (IVirtualFunctionTable)(object)HookedObjectVirtualFunctionTable.FromObject(AddressExtensions.ToUnsigned((System.IntPtr)objectAddress), numberOfMethods);
		}

		public IVirtualFunctionTable VirtualFunctionTableFromObject(nint objectAddress, int numberOfMethods)
		{
			return (IVirtualFunctionTable)(object)VirtualFunctionTable.FromObject(AddressExtensions.ToUnsigned((System.IntPtr)objectAddress), numberOfMethods);
		}

		public IVirtualFunctionTable VirtualFunctionTableFromAddress(nint tableAddress, int numberOfMethods)
		{
			return (IVirtualFunctionTable)(object)VirtualFunctionTable.FromAddress(AddressExtensions.ToUnsigned((System.IntPtr)tableAddress), numberOfMethods);
		}

		public IFunctionPtr<TDelegate> CreateFunctionPtr<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TDelegate>(ulong functionPointer) where TDelegate : System.Delegate
		{
			return new FunctionPtr<TDelegate>(functionPointer);
		}

		public IAsmHook CreateAsmHook(string[] asmCode, long functionAddress)
		{
			return CreateAsmHook(asmCode, functionAddress, (AsmHookBehaviour)0, -1);
		}

		public IAsmHook CreateAsmHook(string asmCode, long functionAddress)
		{
			return CreateAsmHook(asmCode, functionAddress, (AsmHookBehaviour)0, -1);
		}

		public IAsmHook CreateAsmHook(byte[] asmCode, long functionAddress)
		{
			return CreateAsmHook(asmCode, functionAddress, (AsmHookBehaviour)0, -1);
		}

		public IAsmHook CreateAsmHook(string[] asmCode, long functionAddress, AsmHookBehaviour behaviour)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return CreateAsmHook(asmCode, functionAddress, behaviour, -1);
		}

		public IAsmHook CreateAsmHook(string asmCode, long functionAddress, AsmHookBehaviour behaviour)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return CreateAsmHook(asmCode, functionAddress, behaviour, -1);
		}

		public IAsmHook CreateAsmHook(byte[] asmCode, long functionAddress, AsmHookBehaviour behaviour)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return CreateAsmHook(asmCode, functionAddress, behaviour, -1);
		}

		public IAsmHook CreateAsmHook(string asmCode, long functionAddress, AsmHookBehaviour behaviour, int hookLength)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return (IAsmHook)(object)new AsmHook(asmCode, (nuint)AddressExtensions.ToUnsigned(functionAddress), behaviour, hookLength);
		}

		public IAsmHook CreateAsmHook(string[] asmCode, long functionAddress, AsmHookBehaviour behaviour, int hookLength)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return (IAsmHook)(object)new AsmHook(asmCode, (nuint)AddressExtensions.ToUnsigned(functionAddress), behaviour, hookLength);
		}

		public IAsmHook CreateAsmHook(byte[] asmCode, long functionAddress, AsmHookBehaviour behaviour, int hookLength)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return (IAsmHook)(object)new AsmHook(asmCode, (nuint)AddressExtensions.ToUnsigned(functionAddress), behaviour, hookLength);
		}

		public IAsmHook CreateAsmHook(string[] asmCode, long functionAddress, AsmHookOptions options)
		{
			return (IAsmHook)(object)new AsmHook(asmCode, (nuint)AddressExtensions.ToUnsigned(functionAddress), options);
		}

		public IAsmHook CreateAsmHook(string asmCode, long functionAddress, AsmHookOptions options)
		{
			return (IAsmHook)(object)new AsmHook(asmCode, (nuint)AddressExtensions.ToUnsigned(functionAddress), options);
		}

		public IAsmHook CreateAsmHook(byte[] asmCode, long functionAddress, AsmHookOptions options)
		{
			return (IAsmHook)(object)new AsmHook(asmCode, (nuint)AddressExtensions.ToUnsigned(functionAddress), options);
		}
	}
	public class ReloadedHooksUtilities : IReloadedHooksUtilities
	{
		[field: CompilerGenerated]
		public static ReloadedHooksUtilities Instance
		{
			[CompilerGenerated]
			get;
		} = new ReloadedHooksUtilities();


		public byte[] AssembleAbsoluteJump(nint target, bool is64bit)
		{
			return Utilities.AssembleAbsoluteJump(AddressExtensions.ToUnsigned((System.IntPtr)target), is64bit);
		}

		public byte[] AssemblePushReturn(nint target, bool is64bit)
		{
			return Utilities.AssemblePushReturn(AddressExtensions.ToUnsigned((System.IntPtr)target), is64bit);
		}

		public byte[] AssembleRelativeJump(nint relativeJumpOffset, bool is64bit)
		{
			return Utilities.AssembleRelativeJump(relativeJumpOffset, is64bit);
		}

		public byte[] AssembleRelativeJump(nint currentAddress, nint targetAddress, bool is64bit)
		{
			return Utilities.AssembleRelativeJump(AddressExtensions.ToUnsigned((System.IntPtr)currentAddress), AddressExtensions.ToUnsigned((System.IntPtr)targetAddress), is64bit);
		}

		public string GetAbsoluteJumpMnemonics(nint target, bool is64bit)
		{
			return Utilities.GetAbsoluteJumpMnemonics(AddressExtensions.ToUnsigned((System.IntPtr)target), is64bit);
		}

		public string GetAbsoluteCallMnemonics(nint target, bool is64bit)
		{
			return Utilities.GetAbsoluteCallMnemonics(AddressExtensions.ToUnsigned((System.IntPtr)target), is64bit);
		}

		public string GetAbsoluteJumpMnemonics<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(TFunction function, out IReverseWrapper<TFunction> reverseWrapper) where TFunction : System.Delegate
		{
			return Utilities.GetAbsoluteJumpMnemonics(function, out reverseWrapper);
		}

		public string GetAbsoluteCallMnemonics<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(TFunction function, out IReverseWrapper<TFunction> reverseWrapper) where TFunction : System.Delegate
		{
			return Utilities.GetAbsoluteCallMnemonics(function, out reverseWrapper);
		}

		public string GetPushReturnMnemonics(nint target, bool is64bit)
		{
			return Utilities.GetPushReturnMnemonics(AddressExtensions.ToUnsigned((System.IntPtr)target), is64bit);
		}

		public string GetRelativeJumpMnemonics(nint relativeJumpOffset, bool is64bit)
		{
			return Utilities.GetRelativeJumpMnemonics(relativeJumpOffset, is64bit);
		}

		public nint InsertJump(byte[] opcodes, bool is64bit, long jumpTarget, long targetAddress = 0L, long maxDisplacement = 2147483647L)
		{
			return AddressExtensions.ToSigned((System.UIntPtr)Utilities.InsertJump(opcodes, is64bit, (nuint)AddressExtensions.ToUnsigned(jumpTarget), (nuint)targetAddress, (nint)maxDisplacement));
		}

		public int GetHookLength(nint hookAddress, int hookLength, bool is64Bit)
		{
			return Utilities.GetHookLength(AddressExtensions.ToUnsigned((System.IntPtr)hookAddress), hookLength, is64Bit);
		}

		public int GetNumberofParameters([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type delegateType)
		{
			return Utilities.GetNumberofParameters(delegateType);
		}

		public int GetNumberofParametersWithoutFloats([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type delegateType)
		{
			return Utilities.GetNumberofParametersWithoutFloats(delegateType);
		}

		public int GetNumberofParameters<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>()
		{
			return Utilities.GetNumberofParameters<TFunction>();
		}

		public int GetNumberofParametersWithoutFloats<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>()
		{
			return Utilities.GetNumberofParametersWithoutFloats<TFunction>();
		}

		public string PushCdeclCallerSavedRegisters()
		{
			return "push eax\npush ecx\npush edx";
		}

		public string PopCdeclCallerSavedRegisters()
		{
			return "pop edx\npop ecx\npop eax";
		}

		public nint WritePointer(nint target)
		{
			return AddressExtensions.ToSigned((System.UIntPtr)Utilities.WritePointer(AddressExtensions.ToUnsigned((System.IntPtr)target)));
		}

		public unsafe void* GetFunctionPointer([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type type, string name)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			RuntimeMethodHandle methodHandle = ((MethodBase)type.GetMethod(name, (BindingFlags)56)).MethodHandle;
			RuntimeHelpers.PrepareMethod(methodHandle);
			return (void*)((RuntimeMethodHandle)(ref methodHandle)).GetFunctionPointer();
		}

		public ValueTuple<long, long> GetRelativeJumpMinMax(long targetAddress, long maxDisplacement = 2147483647L)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			ValueTuple<nuint, nuint> relativeJumpMinMax = Utilities.GetRelativeJumpMinMax((nuint)AddressExtensions.ToUnsigned(targetAddress), (nint)maxDisplacement);
			return new ValueTuple<long, long>((long)AddressExtensions.ToSigned((System.UIntPtr)relativeJumpMinMax.Item1), (long)AddressExtensions.ToSigned((System.UIntPtr)relativeJumpMinMax.Item2));
		}
	}
}
namespace Reloaded.Hooks.X86
{
	public class ReverseWrapper<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction> : IReverseWrapper<TFunction>, IReverseWrapper
	{
		public TFunction CSharpFunction
		{
			[CompilerGenerated]
			get;
		}

		public nint NativeFunctionPtr
		{
			[CompilerGenerated]
			get;
		}

		public nint WrapperPointer
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		public ReverseWrapper(TFunction function)
		{
			CSharpFunction = function;
			if (typeof(TFunction).IsValueType && !typeof(TFunction).IsPrimitive)
			{
				NativeFunctionPtr = System.Runtime.CompilerServices.Unsafe.As<TFunction, nint>(ref function);
			}
			else
			{
				NativeFunctionPtr = Marshal.GetFunctionPointerForDelegate<TFunction>(function);
			}
			WrapperPointer = NativeFunctionPtr;
			Create(this, AddressExtensions.ToUnsigned((System.IntPtr)NativeFunctionPtr));
		}

		public ReverseWrapper(nuint function)
		{
			NativeFunctionPtr = AddressExtensions.ToSigned((System.UIntPtr)function);
			WrapperPointer = NativeFunctionPtr;
			Create(this, function);
		}

		private static void Create(ReverseWrapper<TFunction> reverseFunctionWrapper, nuint functionPtr)
		{
			IFunctionAttribute attribute = FunctionAttribute.GetAttribute<TFunction>();
			ManagedFunctionAttribute val = Misc.TryGetAttributeOrDefault<TFunction, ManagedFunctionAttribute>();
			if (val != null)
			{
				if (((object)val).Equals((object)attribute))
				{
					reverseFunctionWrapper.WrapperPointer = AddressExtensions.ToSigned((System.UIntPtr)Utilities.CreateJump(functionPtr, is64Bit: false, 8));
				}
				else
				{
					reverseFunctionWrapper.WrapperPointer = AddressExtensions.ToSigned((System.UIntPtr)Wrapper.Create<TFunction>(functionPtr, (IFunctionAttribute)(object)val, attribute));
				}
				return;
			}
			UnmanagedFunctionPointerAttribute val2 = Misc.TryGetAttributeOrDefault<TFunction, UnmanagedFunctionPointerAttribute>();
			if (!attribute.IsEquivalent(val2))
			{
				reverseFunctionWrapper.WrapperPointer = AddressExtensions.ToSigned((System.UIntPtr)Wrapper.Create<TFunction>(functionPtr, attribute.GetEquivalent(val2), attribute));
			}
			else
			{
				reverseFunctionWrapper.WrapperPointer = AddressExtensions.ToSigned((System.UIntPtr)Utilities.CreateJump(functionPtr, is64Bit: false, 8));
			}
		}
	}
	public static class Wrapper
	{
		public static TFunction Create<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(nuint functionAddress)
		{
			nuint wrapperAddress;
			return Create<TFunction>(functionAddress, out wrapperAddress);
		}

		public static TFunction Create<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(nuint functionAddress, out nuint wrapperAddress)
		{
			CreatePointer<TFunction>(functionAddress, out wrapperAddress);
			if (typeof(TFunction).IsValueType && !typeof(TFunction).IsPrimitive)
			{
				return System.Runtime.CompilerServices.Unsafe.As<nuint, TFunction>(ref wrapperAddress);
			}
			return Marshal.GetDelegateForFunctionPointer<TFunction>(AddressExtensions.ToSigned((System.UIntPtr)wrapperAddress));
		}

		public static nuint CreatePointer<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(nuint functionAddress, out nuint wrapperAddress)
		{
			IFunctionAttribute attribute = FunctionAttribute.GetAttribute<TFunction>();
			wrapperAddress = functionAddress;
			UnmanagedFunctionPointerAttribute val = Misc.TryGetAttributeOrDefault<TFunction, UnmanagedFunctionPointerAttribute>();
			if (!attribute.IsEquivalent(val))
			{
				wrapperAddress = Create<TFunction>(functionAddress, attribute, attribute.GetEquivalent(val));
			}
			return wrapperAddress;
		}

		public static nuint Create<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(nuint functionAddress, IFunctionAttribute fromConvention, IFunctionAttribute toConvention)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			ValueTuple<nuint, nuint> relativeJumpMinMax = Utilities.GetRelativeJumpMinMax(functionAddress, 2147483391);
			MemoryBuffer buffer = Utilities.FindOrCreateBufferInRange(256, relativeJumpMinMax.Item1, relativeJumpMinMax.Item2);
			int numberOfParameters = Utilities.GetNumberofParameters<TFunction>();
			return buffer.ExecuteWithLock<nuint>((Func<nuint>)delegate
			{
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_0063: Unknown result type (might be due to invalid IL or missing references)
				//IL_0069: Invalid comparison between Unknown and I4
				//IL_008a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0090: Invalid comparison between Unknown and I4
				//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
				//IL_0100: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
				//IL_0203: Unknown result type (might be due to invalid IL or missing references)
				//IL_0228: Unknown result type (might be due to invalid IL or missing references)
				//IL_0246: Unknown result type (might be due to invalid IL or missing references)
				//IL_0277: Unknown result type (might be due to invalid IL or missing references)
				//IL_027c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0296: Unknown result type (might be due to invalid IL or missing references)
				buffer.SetAlignment(16);
				MemoryBufferProperties properties = buffer.Properties;
				nuint writePointer = ((MemoryBufferProperties)(ref properties)).WritePointer;
				List<string> obj = new List<string>();
				obj.Add("use32");
				obj.Add($"org {writePointer}");
				List<string> val = obj;
				int num = (((int)fromConvention.Cleanup == 1) ? ((numberOfParameters - fromConvention.SourceRegisters.Length) * 4) : 0);
				int num2 = (((int)toConvention.Cleanup == 2) ? ((numberOfParameters - toConvention.SourceRegisters.Length) * 4) : 0);
				int num3 = num + fromConvention.ReservedStackSpace;
				val.Add("push ebp");
				val.Add("mov ebp, esp");
				Register[] calleeSavedRegisters = toConvention.CalleeSavedRegisters;
				foreach (Register val2 in calleeSavedRegisters)
				{
					val.Add($"push {val2}");
				}
				if (fromConvention.ReservedStackSpace > 0)
				{
					val.Add($"sub esp, {fromConvention.ReservedStackSpace}");
				}
				if (numberOfParameters > 0)
				{
					val.AddRange((System.Collections.Generic.IEnumerable<string>)AssembleFunctionParameters(numberOfParameters, fromConvention.SourceRegisters, toConvention.SourceRegisters));
				}
				val.Add($"call {functionAddress}");
				if (num3 > 0)
				{
					val.Add($"add esp, {num3}");
				}
				if (fromConvention.ReturnRegister != toConvention.ReturnRegister)
				{
					val.Add($"mov {toConvention.ReturnRegister}, {fromConvention.ReturnRegister}");
				}
				System.Collections.Generic.IEnumerator<Register> enumerator = Enumerable.Reverse<Register>((System.Collections.Generic.IEnumerable<Register>)toConvention.CalleeSavedRegisters).GetEnumerator();
				try
				{
					while (((System.Collections.IEnumerator)enumerator).MoveNext())
					{
						Register current = enumerator.Current;
						val.Add($"pop {current}");
					}
				}
				finally
				{
					((System.IDisposable)enumerator)?.Dispose();
				}
				val.Add("pop ebp");
				val.Add($"ret {num2}");
				return buffer.Add(Utilities.Assembler.Assemble((System.Collections.Generic.IEnumerable<string>)val.ToArray(), (ushort)100), 1);
			});
		}

		private static string[] AssembleFunctionParameters(int parameterCount, Register[] fromRegisters, Register[] toRegisters)
		{
			List<string> val = new List<string>();
			int num = parameterCount - toRegisters.Length;
			int num2 = num * 4 + 4;
			for (int i = 0; i < num; i++)
			{
				val.Add($"push dword [ebp + {num2}]");
				num2 -= 4;
			}
			for (int num3 = Math.Min(toRegisters.Length, parameterCount) - 1; num3 >= 0; num3--)
			{
				val.Add($"push {toRegisters[num3]}");
			}
			for (int j = 0; j < fromRegisters.Length && j < parameterCount; j++)
			{
				val.Add($"pop {fromRegisters[j]}");
			}
			return val.ToArray();
		}
	}
}
namespace Reloaded.Hooks.X64
{
	public class ReverseWrapper<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction> : IReverseWrapper<TFunction>, IReverseWrapper
	{
		public TFunction CSharpFunction
		{
			[CompilerGenerated]
			get;
		}

		public nint NativeFunctionPtr
		{
			[CompilerGenerated]
			get;
		}

		public nint WrapperPointer
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		public ReverseWrapper(TFunction function)
		{
			CSharpFunction = function;
			if (typeof(TFunction).IsValueType && !typeof(TFunction).IsPrimitive)
			{
				NativeFunctionPtr = System.Runtime.CompilerServices.Unsafe.As<TFunction, nint>(ref function);
			}
			else
			{
				NativeFunctionPtr = Marshal.GetFunctionPointerForDelegate<TFunction>(function);
			}
			WrapperPointer = NativeFunctionPtr;
			Create(this, AddressExtensions.ToUnsigned((System.IntPtr)NativeFunctionPtr));
		}

		public ReverseWrapper(nuint function)
		{
			NativeFunctionPtr = AddressExtensions.ToSigned((System.UIntPtr)function);
			WrapperPointer = NativeFunctionPtr;
			Create(this, function);
		}

		private static void Create(ReverseWrapper<TFunction> reverseFunctionWrapper, nuint functionPtr)
		{
			IFunctionAttribute attribute = FunctionAttribute.GetAttribute<TFunction>();
			if (!((object)attribute).Equals((object)FunctionAttribute.Microsoft))
			{
				reverseFunctionWrapper.WrapperPointer = AddressExtensions.ToSigned((System.UIntPtr)Wrapper.Create<TFunction>(functionPtr, (IFunctionAttribute)(object)FunctionAttribute.Microsoft, attribute));
			}
			else
			{
				reverseFunctionWrapper.WrapperPointer = AddressExtensions.ToSigned((System.UIntPtr)Utilities.CreateJump(functionPtr, is64Bit: true, 8));
			}
		}
	}
	public static class Wrapper
	{
		public static TFunction Create<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(nuint functionAddress)
		{
			nuint wrapperAddress;
			return Create<TFunction>(functionAddress, out wrapperAddress);
		}

		public static TFunction Create<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(nuint functionAddress, out nuint wrapperAddress)
		{
			CreatePointer<TFunction>(functionAddress, out wrapperAddress);
			if (typeof(TFunction).IsValueType && !typeof(TFunction).IsPrimitive)
			{
				return System.Runtime.CompilerServices.Unsafe.As<nuint, TFunction>(ref wrapperAddress);
			}
			return Marshal.GetDelegateForFunctionPointer<TFunction>(AddressExtensions.ToSigned((System.UIntPtr)wrapperAddress));
		}

		public static nuint CreatePointer<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(nuint functionAddress, out nuint wrapperAddress)
		{
			IFunctionAttribute attribute = FunctionAttribute.GetAttribute<TFunction>();
			wrapperAddress = functionAddress;
			if (!((object)attribute).Equals((object)FunctionAttribute.Microsoft))
			{
				wrapperAddress = Create<TFunction>(functionAddress, attribute, (IFunctionAttribute)(object)FunctionAttribute.Microsoft);
			}
			return wrapperAddress;
		}

		public static nuint Create<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(nuint functionAddress, IFunctionAttribute fromConvention, IFunctionAttribute toConvention)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			ValueTuple<nuint, nuint> relativeJumpMinMax = Utilities.GetRelativeJumpMinMax(functionAddress, 2147483263);
			MemoryBuffer buffer = Utilities.FindOrCreateBufferInRange(384, relativeJumpMinMax.Item1, relativeJumpMinMax.Item2);
			int numberOfParameters = Utilities.GetNumberofParametersWithoutFloats<TFunction>();
			return buffer.ExecuteWithLock<nuint>((Func<nuint>)delegate
			{
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_008a: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
				//IL_0201: Unknown result type (might be due to invalid IL or missing references)
				//IL_020c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0231: Unknown result type (might be due to invalid IL or missing references)
				//IL_024f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0280: Unknown result type (might be due to invalid IL or missing references)
				//IL_0285: Unknown result type (might be due to invalid IL or missing references)
				//IL_029f: Unknown result type (might be due to invalid IL or missing references)
				buffer.SetAlignment(16);
				MemoryBufferProperties properties = buffer.Properties;
				nuint writePointer = ((MemoryBufferProperties)(ref properties)).WritePointer;
				List<string> obj = new List<string>();
				obj.Add("use64");
				obj.Add($"org {writePointer}");
				List<string> val = obj;
				val.Add("push rbp");
				val.Add("mov rbp, rsp");
				Register[] calleeSavedRegisters = toConvention.CalleeSavedRegisters;
				foreach (Register val2 in calleeSavedRegisters)
				{
					val.Add($"push {val2}");
				}
				int num = numberOfParameters - fromConvention.SourceRegisters.Length;
				num = ((num >= 0) ? num : 0);
				int num2 = num * 8;
				int num3 = (num2 + 8) % 16;
				int num4 = (fromConvention.ShadowSpace ? 32 : 0);
				if (num3 != 0)
				{
					val.Add($"sub rsp, {num3}");
				}
				if (numberOfParameters > 0)
				{
					val.AddRange((System.Collections.Generic.IEnumerable<string>)AssembleFunctionParameters(numberOfParameters, ref fromConvention, ref toConvention));
				}
				if (fromConvention.ShadowSpace)
				{
					val.Add($"sub rsp, {num4}");
				}
				val.Add($"call {functionAddress}");
				if (num2 + num4 + num3 != 0)
				{
					val.Add($"add rsp, {num2 + num4 + num3}");
				}
				if (fromConvention.ReturnRegister != toConvention.ReturnRegister)
				{
					val.Add($"mov {toConvention.ReturnRegister}, {fromConvention.ReturnRegister}");
				}
				System.Collections.Generic.IEnumerator<Register> enumerator = Enumerable.Reverse<Register>((System.Collections.Generic.IEnumerable<Register>)toConvention.CalleeSavedRegisters).GetEnumerator();
				try
				{
					while (((System.Collections.IEnumerator)enumerator).MoveNext())
					{
						Register current = enumerator.Current;
						val.Add($"pop {current}");
					}
				}
				finally
				{
					((System.IDisposable)enumerator)?.Dispose();
				}
				val.Add("pop rbp");
				val.Add("ret");
				return buffer.Add(Utilities.Assembler.Assemble((System.Collections.Generic.IEnumerable<string>)val.ToArray(), (ushort)100), 1);
			});
		}

		private static string[] AssembleFunctionParameters(int parameterCount, ref IFunctionAttribute fromConvention, ref IFunctionAttribute toConvention)
		{
			List<string> val = new List<string>();
			int num = parameterCount - toConvention.SourceRegisters.Length;
			int num2 = (toConvention.ShadowSpace ? 32 : 0) + 8;
			num2 += num * 8;
			for (int i = 0; i < num; i++)
			{
				val.Add($"push qword [rbp + {num2}]");
				num2 -= 8;
			}
			for (int num3 = Math.Min(toConvention.SourceRegisters.Length, parameterCount) - 1; num3 >= 0; num3--)
			{
				val.Add($"push {toConvention.SourceRegisters[num3]}");
			}
			for (int j = 0; j < fromConvention.SourceRegisters.Length && j < parameterCount; j++)
			{
				val.Add($"pop {fromConvention.SourceRegisters[j]}");
			}
			return val.ToArray();
		}
	}
}
namespace Reloaded.Hooks.Tools
{
	[DefaultMember("Item")]
	public class FunctionPtr<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TDelegate> : IFunctionPtr<TDelegate> where TDelegate : System.Delegate
	{
		private readonly Dictionary<nint, TDelegate> _methodCache;

		private TDelegate _delegate;

		private nint _lastFunctionPointer;

		public ulong FunctionPointer
		{
			[CompilerGenerated]
			get;
		}

		public TDelegate this[int index] => GetDelegate(index);

		public FunctionPtr(ulong functionPointer)
		{
			FunctionPointer = functionPointer;
			_methodCache = (Dictionary<nint, TDelegate>)(object)new Dictionary<nint, nint>();
		}

		public unsafe nint GetFunctionAddress(int index)
		{
			nint* ptr = (nint*)FunctionPointer;
			return ptr[index];
		}

		public unsafe TDelegate GetDelegate(int index = 0)
		{
			//IL_006d: Expected I, but got O
			nint functionAddress = GetFunctionAddress(index);
			if (functionAddress == _lastFunctionPointer)
			{
				return _delegate;
			}
			TDelegate result = default(TDelegate);
			if (((Dictionary<nint, nint>)(object)_methodCache).TryGetValue(functionAddress, ref *(nint*)(&result)))
			{
				return result;
			}
			if (sizeof(nint) == 4)
			{
				_delegate = Reloaded.Hooks.X86.Wrapper.Create<TDelegate>(AddressExtensions.ToUnsigned((System.IntPtr)functionAddress), out var _);
			}
			else
			{
				_delegate = Reloaded.Hooks.X64.Wrapper.Create<TDelegate>(AddressExtensions.ToUnsigned((System.IntPtr)functionAddress), out var _);
			}
			((Dictionary<nint, nint>)(object)_methodCache)[functionAddress] = (nint)_delegate;
			_lastFunctionPointer = functionAddress;
			return _delegate;
		}

		public static implicit operator bool(FunctionPtr<TDelegate> value)
		{
			return value.GetFunctionAddress(0) != (nint)System.IntPtr.Zero;
		}
	}
	[DefaultMember("Item")]
	public class HookedObjectVirtualFunctionTable : IVirtualFunctionTable
	{
		internal class VTableEntryHook<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction> : IHook<TFunction>, IHook
		{
			private readonly HookedObjectVirtualFunctionTable _vTableHook;

			private readonly int _index;

			private readonly bool _is64Bit;

			public TFunction OriginalFunction
			{
				[CompilerGenerated]
				get;
			}

			public IReverseWrapper<TFunction> ReverseWrapper
			{
				[CompilerGenerated]
				get;
			}

			public bool IsHookEnabled
			{
				[CompilerGenerated]
				get;
				[CompilerGenerated]
				private set;
			}

			public bool IsHookActivated
			{
				[CompilerGenerated]
				get;
				[CompilerGenerated]
				private set;
			}

			public nint OriginalFunctionAddress
			{
				[CompilerGenerated]
				get;
			}

			public nint OriginalFunctionWrapperAddress
			{
				[CompilerGenerated]
				get;
			}

			internal unsafe VTableEntryHook(HookedObjectVirtualFunctionTable vTableHook, nuint originalVirtualFunctionTableAddress, int index, TFunction function)
			{
				nuint num = default(nuint);
				MemoryExtensions.SafeRead<Memory, nuint>(Memory.CurrentProcess, (System.UIntPtr)(originalVirtualFunctionTableAddress + (nuint)(index * sizeof(nuint))), ref num);
				_vTableHook = vTableHook;
				_index = index;
				_is64Bit = sizeof(nint) == 8;
				ReverseWrapper = CreateReverseWrapper(function);
				OriginalFunction = CreateWrapper(num, out var wrapperAddress);
				OriginalFunctionAddress = AddressExtensions.ToSigned((System.UIntPtr)num);
				OriginalFunctionWrapperAddress = AddressExtensions.ToSigned((System.UIntPtr)wrapperAddress);
				IsHookActivated = false;
			}

			protected IReverseWrapper<TFunction> CreateReverseWrapper(TFunction function)
			{
				if (_is64Bit)
				{
					return new Reloaded.Hooks.X64.ReverseWrapper<TFunction>(function);
				}
				return new Reloaded.Hooks.X86.ReverseWrapper<TFunction>(function);
			}

			protected TFunction CreateWrapper(nuint functionAddress, out nuint wrapperAddress)
			{
				if (_is64Bit)
				{
					return Reloaded.Hooks.X64.Wrapper.Create<TFunction>(functionAddress, out wrapperAddress);
				}
				return Reloaded.Hooks.X86.Wrapper.Create<TFunction>(functionAddress, out wrapperAddress);
			}

			IHook IHook.Activate()
			{
				return (IHook)(object)Activate();
			}

			public IHook<TFunction> Activate()
			{
				_vTableHook.AddHook((IHook)(object)this);
				Enable();
				IsHookActivated = true;
				return this;
			}

			public void Disable()
			{
				_vTableHook.SetHookedVTableEntry(_index, AddressExtensions.ToUnsigned((System.IntPtr)OriginalFunctionAddress));
				IsHookEnabled = false;
			}

			public void Enable()
			{
				_vTableHook.SetHookedVTableEntry(_index, AddressExtensions.ToUnsigned(ReverseWrapper.WrapperPointer));
				IsHookEnabled = true;
			}
		}

		private readonly nuint _originalVirtualFunctionTableAddress;

		private readonly nuint[] _newVTableForObject;

		private readonly GCHandle _pinnedNewVTableForObject;

		private readonly List<IHook> _hooks;

		[field: CompilerGenerated]
		public List<TableEntry> TableEntries
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public nint ObjectAddress
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		public TableEntry this[int i]
		{
			get
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				return TableEntries[i];
			}
			set
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				TableEntries[i] = value;
			}
		}

		public static HookedObjectVirtualFunctionTable FromObject(nuint objectAddress, int numberOfMethods)
		{
			nuint num = default(nuint);
			MemoryExtensions.SafeRead<Memory, nuint>(Memory.CurrentProcess, (System.UIntPtr)objectAddress, ref num);
			List<TableEntry> addresses = VirtualFunctionTableHelpers.GetAddresses(num, numberOfMethods);
			return new HookedObjectVirtualFunctionTable(objectAddress, num, addresses);
		}

		public IHook<TFunction> CreateFunctionHook<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(int index, TFunction delegateType)
		{
			return new VTableEntryHook<TFunction>(this, _originalVirtualFunctionTableAddress, index, delegateType);
		}

		public unsafe TFunction CreateWrapperFunction<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(int index)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			nuint wrapperAddress;
			if (sizeof(nint) == 4)
			{
				return Reloaded.Hooks.X86.Wrapper.Create<TFunction>(AddressExtensions.ToUnsigned(TableEntries[index].FunctionPointer), out wrapperAddress);
			}
			nuint wrapperAddress2;
			if (sizeof(nint) == 8)
			{
				return Reloaded.Hooks.X64.Wrapper.Create<TFunction>(AddressExtensions.ToUnsigned(TableEntries[index].FunctionPointer), out wrapperAddress2);
			}
			throw new System.Exception("Machine does not appear to be of a 32 or 64bit architecture.");
		}

		private HookedObjectVirtualFunctionTable(nuint objectAddress, nuint virtualFunctionTableAddress, List<TableEntry> table)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			ObjectAddress = AddressExtensions.ToSigned((System.UIntPtr)objectAddress);
			TableEntries = table;
			_originalVirtualFunctionTableAddress = virtualFunctionTableAddress;
			_newVTableForObject = new nuint[table.Count];
			_hooks = new List<IHook>();
			for (int i = 0; i < table.Count; i++)
			{
				_newVTableForObject[i] = AddressExtensions.ToUnsigned(table[i].FunctionPointer);
			}
			_pinnedNewVTableForObject = GCHandle.Alloc((object)_newVTableForObject, (GCHandleType)3);
			MemoryExtensions.SafeWrite<Memory, nint>(Memory.CurrentProcess, (System.UIntPtr)objectAddress, (nint)((GCHandle)(ref _pinnedNewVTableForObject)).AddrOfPinnedObject(), false);
		}

		private void SetHookedVTableEntry(int index, nuint newEntry)
		{
			_newVTableForObject[index] = newEntry;
		}

		private void AddHook(IHook hook)
		{
			_hooks.Add(hook);
		}
	}
	public static class Utilities
	{
		private static object _lock;

		private static MemoryBufferHelper _bufferHelper;

		[field: CompilerGenerated]
		public static Assembler Assembler
		{
			[CompilerGenerated]
			get;
		}

		static Utilities()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			_lock = new object();
			Assembler = new Assembler(65536, 32768);
			_bufferHelper = new MemoryBufferHelper(Process.GetCurrentProcess());
		}

		private static string Architecture(bool is64bit)
		{
			if (!is64bit)
			{
				return "use32";
			}
			return "use64";
		}

		private static string SetAddress(nuint address)
		{
			return $"org {address}";
		}

		public unsafe static nuint WritePointer(nuint target)
		{
			return FindOrCreateBufferInRange(sizeof(nuint), 1u, 2147483647u).Add<nuint>(ref target, false, 4);
		}

		public static byte[] AssembleAbsoluteJump(nuint target, bool is64bit)
		{
			return Assembler.Assemble((System.Collections.Generic.IEnumerable<string>)new string[2]
			{
				Architecture(is64bit),
				GetAbsoluteJumpMnemonics(target, is64bit)
			}, (ushort)100);
		}

		public static byte[] AssemblePushReturn(nuint target, bool is64bit)
		{
			return Assembler.Assemble((System.Collections.Generic.IEnumerable<string>)new string[2]
			{
				Architecture(is64bit),
				GetPushReturnMnemonics(target, is64bit)
			}, (ushort)100);
		}

		public static byte[] AssembleRelativeJump(nint relativeJumpOffset, bool is64bit)
		{
			return Assembler.Assemble((System.Collections.Generic.IEnumerable<string>)new string[2]
			{
				Architecture(is64bit),
				GetRelativeJumpMnemonics(relativeJumpOffset, is64bit)
			}, (ushort)100);
		}

		public static byte[] AssembleRelativeJump(nuint currentAddress, nuint targetAddress, bool is64bit)
		{
			bool isProxied;
			return AssembleRelativeJump(currentAddress, targetAddress, is64bit, out isProxied);
		}

		public static byte[] AssembleRelativeJump(nuint currentAddress, nuint targetAddress, bool is64bit, out bool isProxied)
		{
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			long num = (long)targetAddress - (long)currentAddress;
			isProxied = Math.Abs(num) > 2147483647;
			if (!isProxied)
			{
				return Assembler.Assemble((System.Collections.Generic.IEnumerable<string>)new string[3]
				{
					Architecture(is64bit),
					SetAddress(currentAddress),
					is64bit ? $"jmp qword {targetAddress}" : $"jmp dword {targetAddress}"
				}, (ushort)100);
			}
			ValueTuple<nuint, nuint> relativeJumpMinMax = GetRelativeJumpMinMax(currentAddress);
			nuint num2 = FindOrCreateBufferInRange(16, relativeJumpMinMax.Item1, relativeJumpMinMax.Item2).Add(AssembleAbsoluteJump(targetAddress, is64bit), 4);
			return Assembler.Assemble((System.Collections.Generic.IEnumerable<string>)new string[3]
			{
				Architecture(is64bit),
				SetAddress(currentAddress),
				is64bit ? $"jmp qword {num2}" : $"jmp dword {num2}"
			}, (ushort)100);
		}

		public static string GetAbsoluteJumpMnemonics(nuint target, bool is64bit)
		{
			nuint num = FindOrCreateBufferInRange(System.IntPtr.Size, 1u, 4294967295u).Add<nuint>(ref target, false, 4);
			if (is64bit)
			{
				return "jmp qword [qword " + (System.UIntPtr)num + "]";
			}
			return "jmp dword [" + (System.UIntPtr)num + "]";
		}

		public static string GetAbsoluteCallMnemonics(nuint target, bool is64bit)
		{
			nuint num = FindOrCreateBufferInRange(System.IntPtr.Size, 1u, 4294967295u).Add<nuint>(ref target, false, 4);
			if (is64bit)
			{
				return "call qword [qword " + (System.UIntPtr)num + "]";
			}
			return "call dword [" + (System.UIntPtr)num + "]";
		}

		public static string GetAbsoluteJumpMnemonics<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(TFunction function, out IReverseWrapper<TFunction> reverseWrapper) where TFunction : System.Delegate
		{
			ReloadedHooks instance = ReloadedHooks.Instance;
			reverseWrapper = instance.CreateReverseWrapper(function);
			return GetAbsoluteJumpMnemonics(AddressExtensions.ToUnsigned(reverseWrapper.WrapperPointer), System.IntPtr.Size == 8);
		}

		public static string GetAbsoluteCallMnemonics<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(TFunction function, out IReverseWrapper<TFunction> reverseWrapper) where TFunction : System.Delegate
		{
			ReloadedHooks instance = ReloadedHooks.Instance;
			reverseWrapper = instance.CreateReverseWrapper(function);
			return GetAbsoluteCallMnemonics(AddressExtensions.ToUnsigned(reverseWrapper.WrapperPointer), System.IntPtr.Size == 8);
		}

		public static string GetPushReturnMnemonics(nuint target, bool is64bit)
		{
			return $"push {target}\nret";
		}

		public static string GetRelativeJumpMnemonics(nint relativeJumpOffset, bool is64bit)
		{
			if (is64bit)
			{
				return "jmp qword " + (System.IntPtr)relativeJumpOffset;
			}
			return "jmp dword " + (System.IntPtr)relativeJumpOffset;
		}

		public static nuint InsertJump(byte[] opcodes, bool is64bit, nuint jumpTarget, nuint targetAddress = 0u, nint maxDisplacement = 2147483647)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			List<byte> obj = Enumerable.ToList<byte>((System.Collections.Generic.IEnumerable<byte>)opcodes);
			obj.AddRange((System.Collections.Generic.IEnumerable<byte>)AssembleAbsoluteJump(jumpTarget, is64bit));
			byte[] array = obj.ToArray();
			ValueTuple<nuint, nuint> relativeJumpMinMax = GetRelativeJumpMinMax(targetAddress, maxDisplacement);
			return FindOrCreateBufferInRange(array.Length, relativeJumpMinMax.Item1, relativeJumpMinMax.Item2).Add(array, 4);
		}

		public static nuint CreateJump(nuint targetPtr, bool is64Bit, int minBytesUsed = 0)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			int num = 24 + minBytesUsed;
			ValueTuple<nuint, nuint> relativeJumpMinMax = GetRelativeJumpMinMax(targetPtr, 2147483647 - num);
			MemoryBuffer buffer = FindOrCreateBufferInRange(num, relativeJumpMinMax.Item1, relativeJumpMinMax.Item2);
			return buffer.ExecuteWithLock<nuint>((Func<nuint>)delegate
			{
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_004a: Unknown result type (might be due to invalid IL or missing references)
				//IL_004f: Unknown result type (might be due to invalid IL or missing references)
				buffer.SetAlignment(16);
				MemoryBufferProperties properties = buffer.Properties;
				nuint writePointer = ((MemoryBufferProperties)(ref properties)).WritePointer;
				bool isRelative;
				byte[] array = TryAssembleRelativeJumpArray(writePointer, targetPtr, is64Bit, out isRelative);
				System.UIntPtr result = buffer.Add(array, 1);
				properties = buffer.Properties;
				nuint num2 = (nuint)(nint)(nuint)((MemoryBufferProperties)(ref properties)).WritePointer - writePointer;
				int num3 = minBytesUsed - (int)num2;
				if (num3 > 0)
				{
					buffer.Add(num3, 1);
				}
				return result;
			});
		}

		public unsafe static int GetHookLength(nuint hookAddress, int hookLength, bool is64Bit)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			UnmanagedMemoryStream val = new UnmanagedMemoryStream((byte*)hookAddress, 128L);
			try
			{
				Decoder val2 = Decoder.Create(is64Bit ? 64 : 32, (CodeReader)new StreamCodeReader((Stream)(object)val), (DecoderOptions)0);
				int i;
				Instruction val3 = default(Instruction);
				for (i = 0; i < hookLength; i += ((Instruction)(ref val3)).Length)
				{
					val2.Decode(ref val3);
				}
				return i;
			}
			finally
			{
				((System.IDisposable)val)?.Dispose();
			}
		}

		public static int GetNumberofParameters([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type delegateType)
		{
			MethodInfo method = delegateType.GetMethod("Invoke");
			if (!(method != (MethodInfo)null))
			{
				return 0;
			}
			return ((MethodBase)method).GetParameters().Length;
		}

		public static int GetNumberofParametersWithoutFloats([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type delegateType)
		{
			MethodInfo method = delegateType.GetMethod("Invoke");
			if (!(method != (MethodInfo)null))
			{
				return 0;
			}
			return GetNonFloatParameters(method);
		}

		public static int GetNumberofParameters<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>()
		{
			if (TryGetIFuncPtrFromType<TFunction>(out var value))
			{
				return value.NumberOfParameters;
			}
			return GetNumberofParameters(typeof(TFunction));
		}

		public static int GetNumberofParametersWithoutFloats<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>()
		{
			if (TryGetIFuncPtrFromType<TFunction>(out var value))
			{
				return value.NumberOfParametersWithoutFloats;
			}
			return GetNumberofParametersWithoutFloats(typeof(TFunction));
		}

		private static bool TryGetIFuncPtrFromType<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TType>(out IFuncPtr value)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			value = null;
			if (typeof(IFuncPtr).IsAssignableFrom(typeof(TType)))
			{
				value = (IFuncPtr)Activator.CreateInstance(typeof(TType));
				return true;
			}
			FieldInfo[] fields = typeof(TType).GetFields();
			foreach (FieldInfo val in fields)
			{
				if (typeof(IFuncPtr).IsAssignableFrom(val.FieldType))
				{
					value = (IFuncPtr)CreateInstanceSuppressed(val);
					return true;
				}
			}
			return false;
			[CompilerGenerated]
			[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2072", Justification = "Nested parameterless constructor preserved via nested types.")]
			static object CreateInstanceSuppressed(FieldInfo field)
			{
				return Activator.CreateInstance(field.FieldType);
			}
		}

		private static int GetNonFloatParameters(MethodInfo methodInformation)
		{
			return Enumerable.Count<ParameterInfo>((System.Collections.Generic.IEnumerable<ParameterInfo>)((MethodBase)methodInformation).GetParameters(), (Func<ParameterInfo, bool>)((ParameterInfo parameter) => parameter.ParameterType != typeof(float) && parameter.ParameterType != typeof(double)));
		}

		internal unsafe static bool IsBadReadPtr(nint address)
		{
			Native.MEMORY_BASIC_INFORMATION lpBuffer = default(Native.MEMORY_BASIC_INFORMATION);
			if (Native.VirtualQuery(address, ref lpBuffer, (nuint)sizeof(Native.MEMORY_BASIC_INFORMATION)) != (nint)System.IntPtr.Zero)
			{
				bool result = (lpBuffer.Protect & (Native.MEM_PROTECTION.PAGE_READONLY | Native.MEM_PROTECTION.PAGE_READWRITE | Native.MEM_PROTECTION.PAGE_WRITECOPY | Native.MEM_PROTECTION.PAGE_EXECUTE_READ | Native.MEM_PROTECTION.PAGE_EXECUTE_READWRITE | Native.MEM_PROTECTION.PAGE_EXECUTE_WRITECOPY)) == 0;
				if ((lpBuffer.Protect & (Native.MEM_PROTECTION.PAGE_NOACCESS | Native.MEM_PROTECTION.PAGE_GUARD)) != 0)
				{
					result = true;
				}
				return result;
			}
			return true;
		}

		public static void FillArrayUntilSize<T>(List<T> array, T value, int length)
		{
			if (length > array.Count)
			{
				int num = length - array.Count;
				for (int i = 0; i < num; i++)
				{
					array.Add(value);
				}
			}
		}

		public static byte[] TryAssembleRelativeJumpArray(nuint source, nuint target, bool is64Bit, out bool isRelative)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			ValueTuple<nuint, nuint> relativeJumpMinMax = GetRelativeJumpMinMax(source);
			isRelative = new AddressRange(relativeJumpMinMax.Item1, relativeJumpMinMax.Item2).Contains(target);
			if (!isRelative)
			{
				return AssembleAbsoluteJump(target, is64Bit);
			}
			return AssembleRelativeJump(source, target, is64Bit);
		}

		public static List<byte> TryAssembleRelativeJump(nuint source, nuint target, bool is64Bit, out bool isRelative)
		{
			return Enumerable.ToList<byte>((System.Collections.Generic.IEnumerable<byte>)TryAssembleRelativeJumpArray(source, target, is64Bit, out isRelative));
		}

		public static MemoryBuffer FindOrCreateBufferInRange(int size, nuint minimumAddress = 1u, nuint maximumAddress = 2147483647u, int alignment = 4)
		{
			MemoryBuffer[] array = _bufferHelper.FindBuffers(size + alignment, (System.UIntPtr)minimumAddress, (System.UIntPtr)maximumAddress, true);
			if (array.Length == 0)
			{
				return _bufferHelper.CreateMemoryBuffer(size, (System.UIntPtr)minimumAddress, (System.UIntPtr)maximumAddress, 3);
			}
			return array[0];
		}

		public static ValueTuple<nuint, nuint> GetRelativeJumpMinMax(nuint targetAddress, nint maxDisplacement = 2147483647)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			nuint num = targetAddress - (nuint)maxDisplacement;
			if (num > targetAddress)
			{
				num = 1u;
			}
			nuint num2 = targetAddress + (nuint)maxDisplacement;
			if (num2 < targetAddress)
			{
				num2 = unchecked((nuint)(-1));
			}
			if (!Environment.Is64BitProcess && num2 > 4294967295u)
			{
				num2 = 4294967295u;
			}
			return new ValueTuple<nuint, nuint>(num, num2);
		}
	}
	[DefaultMember("Item")]
	public class VirtualFunctionTable : IVirtualFunctionTable
	{
		[field: CompilerGenerated]
		public List<TableEntry> TableEntries
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		public TableEntry this[int i]
		{
			get
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				return TableEntries[i];
			}
			set
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				TableEntries[i] = value;
			}
		}

		private VirtualFunctionTable()
		{
		}

		public static VirtualFunctionTable FromObject(nuint objectAddress, int numberOfMethods)
		{
			return new VirtualFunctionTable
			{
				TableEntries = GetObjectVTableAddresses(objectAddress, numberOfMethods)
			};
		}

		public static VirtualFunctionTable FromAddress(nuint tableAddress, int numberOfMethods)
		{
			return new VirtualFunctionTable
			{
				TableEntries = VirtualFunctionTableHelpers.GetAddresses(tableAddress, numberOfMethods)
			};
		}

		public unsafe TFunction CreateWrapperFunction<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(int index)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			nuint wrapperAddress;
			if (sizeof(nint) == 4)
			{
				return Reloaded.Hooks.X86.Wrapper.Create<TFunction>(AddressExtensions.ToUnsigned(TableEntries[index].FunctionPointer), out wrapperAddress);
			}
			nuint wrapperAddress2;
			if (sizeof(nint) == 8)
			{
				return Reloaded.Hooks.X64.Wrapper.Create<TFunction>(AddressExtensions.ToUnsigned(TableEntries[index].FunctionPointer), out wrapperAddress2);
			}
			throw new System.Exception("Machine does not appear to be of a 32 or 64bit architecture.");
		}

		public IHook<TFunction> CreateFunctionHook<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFunction>(int index, TFunction delegateType)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return new Hook<TFunction>(delegateType, AddressExtensions.ToUnsigned(TableEntries[index].FunctionPointer));
		}

		private static List<TableEntry> GetObjectVTableAddresses(nuint objectAddress, int numberOfMethods)
		{
			nuint tablePointer = default(nuint);
			MemoryExtensions.SafeRead<Memory, nuint>(Memory.CurrentProcess, (System.UIntPtr)objectAddress, ref tablePointer);
			return VirtualFunctionTableHelpers.GetAddresses(tablePointer, numberOfMethods);
		}
	}
}
namespace Reloaded.Hooks.Internal
{
	public struct AddressRange
	{
		public nuint StartPointer;

		public nuint EndPointer;

		public AddressRange(nuint startPointer, nuint endPointer)
		{
			StartPointer = startPointer;
			EndPointer = endPointer;
		}

		public static AddressRange FromStartAndLength(nuint start, nuint length)
		{
			return new AddressRange(start, start + length);
		}

		public bool Contains(nuint point)
		{
			return PointInRange(ref this, point);
		}

		private bool PointInRange(ref AddressRange range, nuint point)
		{
			if (point >= range.StartPointer && point <= range.EndPointer)
			{
				return true;
			}
			return false;
		}
	}
	public class FunctionPatch
	{
		public List<Patch> Patches;

		[field: CompilerGenerated]
		public List<byte> NewFunction
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		public FunctionPatch()
		{
			NewFunction = new List<byte>();
			Patches = new List<Patch>();
		}
	}
	public class FunctionPatcher
	{
		private struct JumpDetails
		{
			public nuint JumpOpcodeEnd;

			public nuint JumpOpcodeTarget;

			public JumpDetails(nuint jumpOpcodeEnd, nuint jumpOpcodeTarget)
			{
				JumpOpcodeEnd = jumpOpcodeEnd;
				JumpOpcodeTarget = jumpOpcodeTarget;
			}
		}

		private bool _is64Bit;

		private FunctionHookOptions _options;

		private ProcessModule[] _modules;

		public FunctionPatcher(bool is64Bit, FunctionHookOptions options = null)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			_is64Bit = is64Bit;
			_options = (FunctionHookOptions)(((object)options) ?? ((object)new FunctionHookOptions()));
		}

		public FunctionPatch Patch(List<byte> oldFunction, nuint baseAddress)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			FunctionPatch functionPatch = new FunctionPatch();
			nuint newAddress = baseAddress + (nuint)oldFunction.Count;
			byte[] array = oldFunction.ToArray();
			Decoder val = Decoder.Create(_is64Bit ? 64 : 32, (CodeReader)new ByteArrayCodeReader(array), (DecoderOptions)0);
			val.IP = baseAddress;
			nuint num = (nuint)oldFunction.Count + baseAddress;
			List<Instruction> val2 = new List<Instruction>();
			while (val.IP < num)
			{
				val2.Add(val.Decode());
			}
			for (int i = 0; i < val2.Count; i++)
			{
				Instruction val3 = val2[i];
				Instruction val4 = (Instruction)((i + 1 < val2.Count) ? val2[i + 1] : default(Instruction));
				JumpDetails jumpDetails;
				if (IsRelativeJump(val3) && !IsJumpTargetInAModule(PC(val3), GetRelativeJumpTarget(val3)))
				{
					jumpDetails = RewriteRelativeJump(val3, functionPatch);
				}
				else if (IsRIPRelativeJump(val3) && !IsJumpTargetInAModule(PC(val3), GetRewriteRIPRelativeJumpTarget(val3)))
				{
					jumpDetails = RewriteRIPRelativeJump(val3, functionPatch);
				}
				else
				{
					Instruction val5 = default(Instruction);
					if (!((ref val4) != (ref val5)) || !IsPushReturn(val3, val4) || IsJumpTargetInAModule(PC(val3), GetPushReturnTarget(val3)))
					{
						ulong num2 = ((Instruction)(ref val3)).IP - baseAddress;
						System.Span<byte> span = MemoryExtensions.AsSpan<byte>(array).Slice((int)num2, ((Instruction)(ref val3)).Length);
						functionPatch.NewFunction.AddRange((System.Collections.Generic.IEnumerable<byte>)span.ToArray());
						continue;
					}
					jumpDetails = RewritePushReturn(val3, val4, functionPatch);
				}
				PatchReturnAddresses(jumpDetails, functionPatch, newAddress);
			}
			return functionPatch;
		}

		private List<Patch> PatchJumpTargets_Internal(AddressRange searchRange, AddressRange originalJmpTarget, nuint newJmpTarget)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			List<Patch> val = new List<Patch>();
			int size = (int)(searchRange.EndPointer - searchRange.StartPointer);
			byte[] array = TryReadFromMemory(searchRange.StartPointer, size);
			Decoder val2 = Decoder.Create(_is64Bit ? 64 : 32, (CodeReader)new ByteArrayCodeReader(array), (DecoderOptions)0);
			val2.IP = searchRange.StartPointer;
			nuint num = (nuint)array.Length + searchRange.StartPointer;
			List<Instruction> val3 = new List<Instruction>();
			while (val2.IP < num)
			{
				val3.Add(val2.Decode());
			}
			for (int i = 0; i < val3.Count; i++)
			{
				Instruction instruction = val3[i];
				Instruction nextInstruction = (Instruction)((i + 1 < val3.Count) ? val3[i + 1] : default(Instruction));
				if (IsRelativeJump(instruction))
				{
					PatchRelativeJump(instruction, ref originalJmpTarget, newJmpTarget, val);
					continue;
				}
				if (IsRIPRelativeJump(instruction))
				{
					PatchRIPRelativeJump(instruction, ref originalJmpTarget, newJmpTarget, val);
					continue;
				}
				Instruction val4 = default(Instruction);
				if ((ref nextInstruction) != (ref val4) && IsPushReturn(instruction, nextInstruction))
				{
					PatchPushReturn(instruction, ref originalJmpTarget, newJmpTarget, val);
				}
			}
			return val;
		}

		private nuint GetPushReturnTarget(Instruction pushInstruction)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return (nuint)GetOperandOffset(pushInstruction);
		}

		private nuint GetRelativeJumpTarget(Instruction instruction)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return (nuint)GetJumpTarget(instruction);
		}

		private nuint GetRewriteRIPRelativeJumpTarget(Instruction instruction)
		{
			ulong iPRelativeMemoryAddress = ((Instruction)(ref instruction)).IPRelativeMemoryAddress;
			nuint result = default(nuint);
			Memory.CurrentProcess.Read<nuint>((System.UIntPtr)(nuint)iPRelativeMemoryAddress, ref result);
			return result;
		}

		private JumpDetails RewriteRelativeJump(Instruction instruction, FunctionPatch patch)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			nuint relativeJumpTarget = GetRelativeJumpTarget(instruction);
			patch.NewFunction.AddRange((System.Collections.Generic.IEnumerable<byte>)Utilities.AssembleAbsoluteJump(relativeJumpTarget, _is64Bit));
			return new JumpDetails(PC(instruction), relativeJumpTarget);
		}

		private JumpDetails RewriteRIPRelativeJump(Instruction instruction, FunctionPatch patch)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			nuint rewriteRIPRelativeJumpTarget = GetRewriteRIPRelativeJumpTarget(instruction);
			patch.NewFunction.AddRange((System.Collections.Generic.IEnumerable<byte>)Utilities.AssembleAbsoluteJump(rewriteRIPRelativeJumpTarget, _is64Bit));
			return new JumpDetails(PC(instruction), rewriteRIPRelativeJumpTarget);
		}

		private JumpDetails RewritePushReturn(Instruction pushInstruction, Instruction retInstruction, FunctionPatch patch)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			nuint pushReturnTarget = GetPushReturnTarget(pushInstruction);
			patch.NewFunction.AddRange((System.Collections.Generic.IEnumerable<byte>)Utilities.AssembleAbsoluteJump(pushReturnTarget, _is64Bit));
			return new JumpDetails(PC(retInstruction), pushReturnTarget);
		}

		private void PatchReturnAddresses(JumpDetails jumpDetails, FunctionPatch patch, nuint newAddress)
		{
			nuint jumpOpcodeTarget = jumpDetails.JumpOpcodeTarget;
			nuint searchPointer = jumpOpcodeTarget;
			GetSearchRange(ref searchPointer, out var searchLength);
			nuint jumpOpcodeEnd = jumpDetails.JumpOpcodeEnd;
			int size = (int)(newAddress - jumpOpcodeEnd);
			nuint newOriginalPrologue = Utilities.InsertJump(TryReadFromMemory(jumpOpcodeEnd, size), maxDisplacement: (nint)(2147483647 - searchLength), is64bit: _is64Bit, jumpTarget: newAddress, targetAddress: jumpOpcodeTarget);
			AddressRange searchRange = new AddressRange(searchPointer, searchPointer + searchLength);
			AddressRange jumpTargetRange = new AddressRange(jumpOpcodeEnd, newAddress);
			patch.Patches = PatchJumpTargets(searchRange, jumpOpcodeTarget, jumpTargetRange, newOriginalPrologue);
		}

		internal List<Patch> PatchJumpTargets(AddressRange searchRange, nuint originalJmpTarget, AddressRange jumpTargetRange, nuint newOriginalPrologue)
		{
			List<Patch> result = new List<Patch>();
			if (TryCodeAlignmentRange(AddressRange.FromStartAndLength(originalJmpTarget / 16 * 16, 64u)))
			{
				return result;
			}
			if (TryCodeAlignmentRange(AddressRange.FromStartAndLength(originalJmpTarget / 16 * 16 - 16, 32u)))
			{
				return result;
			}
			if (TryCodeAlignmentRange(AddressRange.FromStartAndLength(originalJmpTarget, 32u)))
			{
				return result;
			}
			List<Patch> val = PatchJumpTargets_Internal(searchRange, jumpTargetRange, newOriginalPrologue);
			result.AddRange((System.Collections.Generic.IEnumerable<Patch>)val);
			return result;
			[CompilerGenerated]
			bool TryCodeAlignmentRange(AddressRange range)
			{
				if (range.StartPointer < searchRange.StartPointer && Utilities.IsBadReadPtr(AddressExtensions.ToSigned((System.UIntPtr)range.StartPointer)))
				{
					range.StartPointer = searchRange.StartPointer;
				}
				if (range.EndPointer > searchRange.EndPointer && Utilities.IsBadReadPtr(AddressExtensions.ToSigned((System.UIntPtr)range.EndPointer)))
				{
					range.EndPointer = searchRange.EndPointer;
				}
				List<Patch> val2 = PatchJumpTargets_Internal(range, jumpTargetRange, newOriginalPrologue);
				result.AddRange((System.Collections.Generic.IEnumerable<Patch>)val2);
				return val2.Count > 0;
			}
		}

		private void PatchRelativeJump(Instruction instruction, ref AddressRange originalJmpTarget, nuint newJmpTarget, List<Patch> patches)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			nuint point = (nuint)GetJumpTarget(instruction);
			if (originalJmpTarget.Contains(point))
			{
				byte[] bytes = Utilities.AssembleRelativeJump((nuint)((Instruction)(ref instruction)).IP, newJmpTarget, _is64Bit);
				patches.Add(new Patch((nuint)((Instruction)(ref instruction)).IP, bytes));
			}
		}

		private void PatchRIPRelativeJump(Instruction instruction, ref AddressRange originalJmpTarget, nuint newJmpTarget, List<Patch> patches)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			nuint rewriteRIPRelativeJumpTarget = GetRewriteRIPRelativeJumpTarget(instruction);
			if (originalJmpTarget.Contains(rewriteRIPRelativeJumpTarget))
			{
				byte[] bytes = Utilities.AssembleRelativeJump((nuint)((Instruction)(ref instruction)).IP, newJmpTarget, _is64Bit);
				patches.Add(new Patch((nuint)((Instruction)(ref instruction)).IP, bytes));
			}
		}

		private void PatchPushReturn(Instruction instruction, ref AddressRange originalJmpTarget, nuint newJmpTarget, List<Patch> patches)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			ulong num = GetPushReturnTarget(instruction);
			if (originalJmpTarget.Contains((nuint)num))
			{
				byte[] array = Utilities.AssembleAbsoluteJump(newJmpTarget, _is64Bit);
				byte[] bytes = Utilities.AssemblePushReturn(Utilities.FindOrCreateBufferInRange(array.Length, 1u, 2147483647u).Add(array, 4), _is64Bit);
				patches.Add(new Patch((nuint)((Instruction)(ref instruction)).IP, bytes));
			}
		}

		internal void GetSearchRange(ref nuint searchPointer, out nuint searchLength)
		{
			searchLength = 0u;
			if (_options.SearchInModules)
			{
				ProcessModule[] cachedModules = GetCachedModules();
				foreach (ProcessModule val in cachedModules)
				{
					nuint num = AddressExtensions.ToUnsigned(val.BaseAddress);
					nuint num2 = (nuint)((nint)(nuint)AddressExtensions.ToUnsigned(val.BaseAddress) + val.ModuleMemorySize);
					if (searchPointer >= num && searchPointer <= num2)
					{
						searchPointer = num;
						searchLength = (nuint)val.ModuleMemorySize;
					}
				}
			}
			if (searchLength == 0)
			{
				searchLength = (nuint)Environment.SystemPageSize;
				searchPointer -= searchPointer % searchLength;
			}
		}

		private byte[] TryReadFromMemory(nuint address, int size)
		{
			byte[] result = default(byte[]);
			try
			{
				Memory.CurrentProcess.ReadRaw((System.UIntPtr)address, ref result, size);
			}
			catch (System.Exception)
			{
				MemoryExtensions.SafeReadRaw<Memory>(Memory.CurrentProcess, (System.UIntPtr)address, ref result, size);
			}
			return result;
		}

		[MethodImpl(256)]
		private bool IsRelativeJump(Instruction instruction)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Invalid comparison between Unknown and I4
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Invalid comparison between Unknown and I4
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Invalid comparison between Unknown and I4
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Invalid comparison between Unknown and I4
			if ((int)((Instruction)(ref instruction)).Mnemonic == 308 && ((Instruction)(ref instruction)).OpCount > 0)
			{
				if ((int)((Instruction)(ref instruction)).Op0Kind != 1 && (int)((Instruction)(ref instruction)).Op0Kind != 2)
				{
					return (int)((Instruction)(ref instruction)).Op0Kind == 3;
				}
				return true;
			}
			return false;
		}

		[MethodImpl(256)]
		private bool IsPushReturn(Instruction instruction, Instruction nextInstruction)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Invalid comparison between Unknown and I4
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Invalid comparison between Unknown and I4
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Invalid comparison between Unknown and I4
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Invalid comparison between Unknown and I4
			if ((int)((Instruction)(ref instruction)).Mnemonic == 640 && ((Instruction)(ref instruction)).OpCount >= 1)
			{
				OpKind op0Kind = ((Instruction)(ref instruction)).Op0Kind;
				if ((int)op0Kind == 9 || (int)op0Kind == 14)
				{
					return (int)((Instruction)(ref nextInstruction)).Mnemonic == 662;
				}
			}
			return false;
		}

		[MethodImpl(256)]
		private bool IsRIPRelativeJump(Instruction instruction)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Invalid comparison between Unknown and I4
			if ((int)((Instruction)(ref instruction)).Mnemonic == 308 && _is64Bit && ((Instruction)(ref instruction)).OpCount >= 1)
			{
				return ((Instruction)(ref instruction)).IsIPRelativeMemoryOperand;
			}
			return false;
		}

		[MethodImpl(256)]
		private bool IsJumpTargetInAModule(nuint source, nuint target)
		{
			if (!_options.VerifyJumpTargetsModule)
			{
				return false;
			}
			ProcessModule[] cachedModules = GetCachedModules();
			foreach (ProcessModule val in cachedModules)
			{
				AddressRange addressRange = new AddressRange(AddressExtensions.ToUnsigned(val.BaseAddress), AddressExtensions.ToUnsigned((System.IntPtr)((nint)val.BaseAddress + val.ModuleMemorySize)));
				if (addressRange.Contains(source) && addressRange.Contains(target))
				{
					return true;
				}
			}
			return false;
		}

		private ProcessModule[] GetCachedModules()
		{
			if (_modules != null)
			{
				return _mo

GDWeave/core/Reloaded.Memory.Buffers.dll

Decompiled 3 days ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using Microsoft.CodeAnalysis;
using Reloaded.Memory.Buffers.Internal;
using Reloaded.Memory.Buffers.Internal.Kernel32;
using Reloaded.Memory.Buffers.Internal.Structs;
using Reloaded.Memory.Buffers.Internal.Utilities;
using Reloaded.Memory.Kernel32;
using Reloaded.Memory.Sources;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCompany("Sewer56")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("LGPL V3")]
[assembly: AssemblyDescription("An implementation of efficient, shared, concurrent and permanent storage of objects in unmanaged memory in static, non-changing locations that last the lifetime of a given process.")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0")]
[assembly: AssemblyProduct("Project Reloaded")]
[assembly: AssemblyTitle("Reloaded.Memory.Buffers")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Reloaded-Project/Reloaded.Memory.Buffers")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.0.0.0")]
[module: UnverifiableCode]
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 NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = P_0;
		}
	}
}
namespace Reloaded.Memory.Buffers
{
	public class MemoryBuffer : IDisposable
	{
		private Mutex _bufferAddMutex;

		private readonly nuint _headerAddress;

		public IMemory MemorySource { get; private set; }

		public MemoryBufferProperties Properties
		{
			get
			{
				MemoryBufferProperties result = default(MemoryBufferProperties);
				MemorySource.Read<MemoryBufferProperties>((UIntPtr)_headerAddress, ref result);
				return result;
			}
			set
			{
				MemorySource.Write<MemoryBufferProperties>((UIntPtr)_headerAddress, ref value);
			}
		}

		internal unsafe nuint AllocationAddress => (UIntPtr)_headerAddress - sizeof(MemoryBufferMagic);

		internal MemoryBuffer(IMemory memorySource, nuint headerAddress)
		{
			_headerAddress = headerAddress;
			MemorySource = memorySource;
		}

		internal MemoryBuffer(IMemory memorySource, nuint headerAddress, MemoryBufferProperties memoryBufferProperties)
			: this(memorySource, headerAddress)
		{
			Properties = memoryBufferProperties;
		}

		~MemoryBuffer()
		{
			Dispose();
		}

		public void Dispose()
		{
			_bufferAddMutex?.Dispose();
			GC.SuppressFinalize(this);
		}

		internal void SetupMutex(Process process)
		{
			try
			{
				_bufferAddMutex = Mutex.OpenExisting(GetMutexName(process));
			}
			catch (WaitHandleCannotBeOpenedException)
			{
				_bufferAddMutex = new Mutex(initiallyOwned: false, GetMutexName(process));
			}
		}

		internal string GetMutexName(Process process)
		{
			return $"Reloaded.Memory.Buffers.MemoryBuffer | PID: {process.Id} | Memory Address: {((UIntPtr)_headerAddress).ToString()}";
		}

		public T ExecuteWithLock<T>(Func<T> func)
		{
			try
			{
				_bufferAddMutex.WaitOne();
				T result = func();
				_bufferAddMutex.ReleaseMutex();
				return result;
			}
			catch (Exception)
			{
				_bufferAddMutex.ReleaseMutex();
				throw;
			}
		}

		public void SetAlignment(int alignment)
		{
			ExecuteWithLock(delegate
			{
				MemoryBufferProperties properties = Properties;
				properties.SetAlignment(alignment);
				Properties = properties;
				return true;
			});
		}

		public nuint Add(int numBytes, int alignment = 4)
		{
			return ExecuteWithLock(delegate
			{
				MemoryBufferProperties properties = Properties;
				properties.SetAlignment(alignment);
				if (Properties.Remaining < numBytes)
				{
					return 0u;
				}
				nuint writePointer = properties.WritePointer;
				properties.Offset += numBytes;
				Properties = properties;
				return writePointer;
			});
		}

		public nuint Add(byte[] bytesToWrite, int alignment = 4)
		{
			return ExecuteWithLock(delegate
			{
				MemoryBufferProperties properties = Properties;
				properties.SetAlignment(alignment);
				if (Properties.Remaining < bytesToWrite.Length)
				{
					return 0u;
				}
				nuint writePointer = properties.WritePointer;
				MemorySource.WriteRaw((UIntPtr)writePointer, bytesToWrite);
				properties.Offset += bytesToWrite.Length;
				Properties = properties;
				return writePointer;
			});
		}

		public nuint Add<TStructure>(ref TStructure bytesToWrite, bool marshalElement = false, int alignment = 4)
		{
			TStructure bytesToWriteByVal = bytesToWrite;
			return ExecuteWithLock(delegate
			{
				MemoryBufferProperties properties = Properties;
				int size = Struct.GetSize<TStructure>(marshalElement);
				properties.SetAlignment(alignment);
				if (Properties.Remaining < size)
				{
					return 0u;
				}
				nuint writePointer = properties.WritePointer;
				MemorySource.Write<TStructure>((UIntPtr)writePointer, ref bytesToWriteByVal, marshalElement);
				properties.Offset += size;
				Properties = properties;
				return writePointer;
			});
		}

		public bool CanItemFit(int objectSize)
		{
			return Properties.Remaining >= objectSize;
		}

		public bool CanItemFit<TGeneric>(ref TGeneric item, bool marshalElement = false)
		{
			return CanItemFit(Struct.GetSize<TGeneric>(marshalElement));
		}

		public override bool Equals(object obj)
		{
			return obj is MemoryBuffer memoryBuffer && _headerAddress == memoryBuffer._headerAddress;
		}

		[ExcludeFromCodeCoverage]
		public override int GetHashCode()
		{
			return (int)_headerAddress;
		}
	}
	public class MemoryBufferHelper
	{
		internal const int DefaultPageSize = 4096;

		private Mutex _allocateMemoryMutex;

		private MemoryBufferSearcher _bufferSearcher;

		private VirtualQueryUtility.VirtualQueryFunction _virtualQueryFunction;

		public Process Process { get; private set; }

		internal string CreateBufferMutexName()
		{
			return $"Reloaded.Memory.Buffers.MemoryBufferHelper | Allocate Memory | PID: {Process.Id}";
		}

		public MemoryBufferHelper(Process process)
		{
			Process = process;
			_bufferSearcher = new MemoryBufferSearcher(process);
			_virtualQueryFunction = VirtualQueryUtility.GetVirtualQueryFunction(process);
			_allocateMemoryMutex = MutexObtainer.MakeMutex(CreateBufferMutexName());
		}

		public BufferAllocationProperties FindBufferLocation(int size, nuint minimumAddress, nuint maximumAddress, bool isPrivateBuffer = false)
		{
			if (minimumAddress == 0)
			{
				throw new ArgumentException("Please do not set the minimum address to 0 or negative. It collides with the return values of Windows API functionswhere e.g. 0 is returned on failure but you can also allocate successfully on 0.");
			}
			int bufferSize = GetBufferSize(size, isPrivateBuffer);
			List<Kernel32.MEMORY_BASIC_INFORMATION> pages = MemoryPages.GetPages(Process);
			for (int i = 0; i < pages.Count; i++)
			{
				Kernel32.MEMORY_BASIC_INFORMATION pageInfo = pages[i];
				nuint bufferPointerInPageRange = GetBufferPointerInPageRange(in pageInfo, bufferSize, minimumAddress, maximumAddress);
				if (bufferPointerInPageRange != 0)
				{
					return new BufferAllocationProperties(bufferPointerInPageRange, bufferSize);
				}
			}
			throw new Exception($"Unable to find memory location to fit MemoryBuffer of size {size} ({bufferSize}) between {minimumAddress} and {maximumAddress}.");
		}

		public MemoryBuffer CreateMemoryBuffer(int size, nuint minimumAddress = 65536u, nuint maximumAddress = 2147483647u, int retryCount = 3)
		{
			if (minimumAddress == 0)
			{
				throw new ArgumentException("Please do not set the minimum address to 0 or negative. It collides with the return values of Windows API functionswhere e.g. 0 is returned on failure but you can also allocate successfully on 0.");
			}
			Exception ex = new Exception();
			_allocateMemoryMutex.WaitOne();
			while (minimumAddress < maximumAddress)
			{
				try
				{
					return Run(retryCount, delegate
					{
						BufferAllocationProperties bufferAllocationProperties = FindBufferLocation(size, minimumAddress, maximumAddress);
						MemoryBuffer memoryBuffer = MemoryBufferFactory.CreateBuffer(Process, bufferAllocationProperties.MemoryAddress, bufferAllocationProperties.Size);
						_bufferSearcher.AddBuffer(memoryBuffer);
						_allocateMemoryMutex.ReleaseMutex();
						return memoryBuffer;
					});
				}
				catch (Exception ex2)
				{
					ex = ex2;
					minimumAddress += 65536u;
				}
			}
			_allocateMemoryMutex.ReleaseMutex();
			throw ex;
		}

		public PrivateMemoryBuffer CreatePrivateMemoryBuffer(int size, nuint minimumAddress = 65536u, nuint maximumAddress = 2147483647u, int retryCount = 3)
		{
			if (minimumAddress == 0)
			{
				throw new ArgumentException("Please do not set the minimum address to 0 or negative. It collides with the return values of Windows API functionswhere e.g. 0 is returned on failure but you can also allocate successfully on 0.");
			}
			Exception ex = new Exception();
			_allocateMemoryMutex.WaitOne();
			while (minimumAddress < maximumAddress)
			{
				try
				{
					return Run(retryCount, delegate
					{
						BufferAllocationProperties bufferAllocationProperties = FindBufferLocation(size, minimumAddress, maximumAddress, isPrivateBuffer: true);
						PrivateMemoryBuffer result = MemoryBufferFactory.CreatePrivateBuffer(Process, bufferAllocationProperties.MemoryAddress, bufferAllocationProperties.Size);
						_allocateMemoryMutex.ReleaseMutex();
						return result;
					});
				}
				catch (Exception ex2)
				{
					ex = ex2;
					minimumAddress += 65536u;
				}
			}
			_allocateMemoryMutex.ReleaseMutex();
			throw ex;
		}

		public MemoryBuffer[] FindBuffers(int size, bool useCache = true)
		{
			return _bufferSearcher.GetBuffers(size, useCache);
		}

		public MemoryBuffer[] FindBuffers(int size, nuint minimumAddress, nuint maximumAddress, bool useCache = true)
		{
			MemoryBuffer[] buffers = _bufferSearcher.GetBuffers(size, useCache);
			AddressRange addressRange = new AddressRange(minimumAddress, maximumAddress);
			List<MemoryBuffer> list = new List<MemoryBuffer>(buffers.Length);
			MemoryBuffer[] array = buffers;
			foreach (MemoryBuffer memoryBuffer in array)
			{
				MemoryBufferProperties properties = memoryBuffer.Properties;
				AddressRange otherRange = new AddressRange(properties.DataPointer, (UIntPtr)properties.DataPointer + properties.Size);
				if (addressRange.Contains(ref otherRange))
				{
					list.Add(memoryBuffer);
				}
			}
			return list.ToArray();
		}

		public BufferAllocationProperties Allocate(int size, nuint minimumAddress = 65536u, nuint maximumAddress = 2147483647u, int retryCount = 3)
		{
			if (minimumAddress == 0)
			{
				throw new ArgumentException("Please do not set the minimum address to 0 or negative. It collides with the return values of Windows API functionswhere e.g. 0 is returned on failure but you can also allocate successfully on 0.");
			}
			Exception ex = new Exception();
			_allocateMemoryMutex.WaitOne();
			while (minimumAddress < maximumAddress)
			{
				try
				{
					return Run(retryCount, delegate
					{
						BufferAllocationProperties result = FindBufferLocation(size, minimumAddress, maximumAddress, isPrivateBuffer: true);
						VirtualAllocUtility.VirtualAllocFunction virtualAllocFunction = VirtualAllocUtility.GetVirtualAllocFunction(Process);
						UIntPtr uIntPtr = virtualAllocFunction(Process.Handle, result.MemoryAddress, (ulong)result.Size);
						if (uIntPtr == UIntPtr.Zero)
						{
							throw new Exception("Failed to allocate memory using VirtualAlloc/VirtualAllocEx");
						}
						_allocateMemoryMutex.ReleaseMutex();
						return result;
					});
				}
				catch (Exception ex2)
				{
					ex = ex2;
					minimumAddress += 65536u;
				}
			}
			_allocateMemoryMutex.ReleaseMutex();
			throw ex;
		}

		public void Free(nuint address)
		{
			_allocateMemoryMutex.WaitOne();
			try
			{
				VirtualFreeUtility.GetVirtualFreeFunction(Process)(Process.Handle, address);
				_allocateMemoryMutex.ReleaseMutex();
			}
			catch (Exception)
			{
				_allocateMemoryMutex.ReleaseMutex();
				throw;
			}
		}

		public int GetBufferSize(int size, bool isPrivateBuffer = false)
		{
			Kernel32.GetSystemInfo(out var lpSystemInfo);
			int num = 4096;
			if (lpSystemInfo.dwPageSize > num || num % lpSystemInfo.dwPageSize != 0)
			{
				num = (int)lpSystemInfo.dwPageSize;
			}
			if (isPrivateBuffer)
			{
				return Mathematics.RoundUp(size + MemoryBufferFactory.PrivateBufferOverhead, num);
			}
			return Mathematics.RoundUp(size + MemoryBufferFactory.BufferOverhead, num);
		}

		private T Run<T>(int retries, Func<T> function)
		{
			Exception ex = new Exception("This should not throw");
			for (int i = 0; i < retries; i++)
			{
				try
				{
					return function();
				}
				catch (Exception ex2)
				{
					ex = ex2;
				}
			}
			throw ex;
		}

		private nuint GetBufferPointerInPageRange(in Kernel32.MEMORY_BASIC_INFORMATION pageInfo, int bufferSize, nuint minimumPtr, nuint maximumPtr)
		{
			if (pageInfo.State != 65536)
			{
				return 0u;
			}
			nuint multiple = 65536u;
			nuint baseAddress = pageInfo.BaseAddress;
			nuint endPointer = pageInfo.BaseAddress + pageInfo.RegionSize;
			AddressRange otherRange = new AddressRange(minimumPtr, maximumPtr);
			AddressRange addressRange = new AddressRange(baseAddress, endPointer);
			if (!addressRange.Overlaps(ref otherRange))
			{
				return 0u;
			}
			nuint num = Mathematics.RoundDown((UIntPtr)addressRange.EndPointer - bufferSize, multiple);
			AddressRange otherRange2 = new AddressRange(num, (UIntPtr)num + bufferSize);
			if (addressRange.Contains(ref otherRange2) && otherRange.Contains(ref otherRange2))
			{
				return otherRange2.StartPointer;
			}
			nuint num2 = Mathematics.RoundUp(addressRange.StartPointer, multiple);
			AddressRange otherRange3 = new AddressRange(num2, (UIntPtr)num2 + bufferSize);
			if (addressRange.Contains(ref otherRange3) && otherRange.Contains(ref otherRange3))
			{
				return otherRange3.StartPointer;
			}
			nuint num3 = Mathematics.RoundDown((UIntPtr)maximumPtr - bufferSize, multiple);
			AddressRange otherRange4 = new AddressRange(num3, (UIntPtr)num3 + bufferSize);
			if (addressRange.Contains(ref otherRange4) && otherRange.Contains(ref otherRange4))
			{
				return otherRange4.StartPointer;
			}
			nuint num4 = Mathematics.RoundUp(minimumPtr, multiple);
			AddressRange otherRange5 = new AddressRange(num4, (UIntPtr)num4 + bufferSize);
			if (addressRange.Contains(ref otherRange5) && otherRange.Contains(ref otherRange5))
			{
				return otherRange5.StartPointer;
			}
			return 0u;
		}
	}
	public struct MemoryBufferProperties
	{
		public nuint DataPointer { get; internal set; }

		public int Alignment { get; private set; }

		public int Offset { get; internal set; }

		public int Size { get; internal set; }

		public int Remaining => Size - Offset;

		public nuint WritePointer => (UIntPtr)DataPointer + Offset;

		public MemoryBufferProperties(nuint dataPointer, int size)
		{
			Alignment = 4;
			DataPointer = dataPointer;
			Offset = 0;
			Size = size;
		}

		internal void SetAlignment(int alignment)
		{
			Alignment = alignment;
			Align();
		}

		internal void Align()
		{
			Offset = (int)(Mathematics.RoundUp(WritePointer, (ulong)Alignment) - DataPointer);
		}
	}
	public static class MemoryPages
	{
		public static List<Kernel32.MEMORY_BASIC_INFORMATION> GetPages(Process process)
		{
			Kernel32.IsWow64Process(process.Handle, out var Wow64Process);
			Kernel32.GetSystemInfo(out var lpSystemInfo);
			nuint num = 0u;
			nuint num2 = 2147483647u;
			if (lpSystemInfo.wProcessorArchitecture == Kernel32.ProcessorArchitecture.PROCESSOR_ARCHITECTURE_AMD64 && !Wow64Process)
			{
				num2 = lpSystemInfo.lpMaximumApplicationAddress;
			}
			if (IntPtr.Size == 4 && lpSystemInfo.lpMaximumApplicationAddress > num2)
			{
				num2 = lpSystemInfo.lpMaximumApplicationAddress;
			}
			VirtualQueryUtility.VirtualQueryFunction virtualQueryFunction = VirtualQueryUtility.GetVirtualQueryFunction(process);
			List<Kernel32.MEMORY_BASIC_INFORMATION> list = new List<Kernel32.MEMORY_BASIC_INFORMATION>(8192);
			Kernel32.MEMORY_BASIC_INFORMATION memoryInformation;
			for (; num <= num2; num += memoryInformation.RegionSize)
			{
				memoryInformation = default(Kernel32.MEMORY_BASIC_INFORMATION);
				UIntPtr uIntPtr = virtualQueryFunction(process.Handle, num, ref memoryInformation);
				if (uIntPtr == (UIntPtr)0uL)
				{
					break;
				}
				list.Add(memoryInformation);
			}
			return list;
		}
	}
	public class PrivateMemoryBuffer : MemoryBuffer, IDisposable
	{
		internal PrivateMemoryBuffer(IMemory memorySource, nuint headerAddress, MemoryBufferProperties memoryBufferProperties)
			: base(memorySource, headerAddress, memoryBufferProperties)
		{
		}

		~PrivateMemoryBuffer()
		{
			Dispose();
		}

		public new void Dispose()
		{
			base.MemorySource.Free((UIntPtr)base.AllocationAddress);
			base.Dispose();
			GC.SuppressFinalize(this);
		}
	}
}
namespace Reloaded.Memory.Buffers.Internal
{
	internal static class MemoryBufferFactory
	{
		private static MemoryBufferMagic _bufferMagic = new MemoryBufferMagic(initialize: true);

		internal unsafe static int BufferOverhead => sizeof(MemoryBufferProperties) + sizeof(MemoryBufferMagic);

		internal unsafe static int PrivateBufferOverhead => sizeof(MemoryBufferProperties);

		internal unsafe static MemoryBuffer CreateBuffer(Process process, nuint bufferAddress, int allocationSize, bool allocateMemory = true)
		{
			if (allocateMemory)
			{
				AllocateBuffer(process, bufferAddress, allocationSize);
			}
			IMemory memorySource = GetMemorySource(process);
			memorySource.Write<MemoryBufferMagic>((UIntPtr)bufferAddress, ref _bufferMagic);
			nuint headerAddress = (UIntPtr)bufferAddress + sizeof(MemoryBufferMagic);
			nuint dataPointer = (UIntPtr)bufferAddress + BufferOverhead;
			int size = allocationSize - BufferOverhead;
			MemoryBufferProperties memoryBufferProperties = new MemoryBufferProperties(dataPointer, size);
			MemoryBuffer memoryBuffer = new MemoryBuffer(memorySource, headerAddress, memoryBufferProperties);
			memoryBuffer.SetupMutex(process);
			return memoryBuffer;
		}

		internal static PrivateMemoryBuffer CreatePrivateBuffer(Process process, nuint bufferAddress, int allocationSize, bool allocateMemory = true)
		{
			if (allocateMemory)
			{
				AllocateBuffer(process, bufferAddress, allocationSize);
			}
			IMemory memorySource = GetMemorySource(process);
			nuint dataPointer = (UIntPtr)bufferAddress + PrivateBufferOverhead;
			int size = allocationSize - PrivateBufferOverhead;
			MemoryBufferProperties memoryBufferProperties = new MemoryBufferProperties(dataPointer, size);
			PrivateMemoryBuffer privateMemoryBuffer = new PrivateMemoryBuffer(memorySource, bufferAddress, memoryBufferProperties);
			privateMemoryBuffer.SetupMutex(process);
			return privateMemoryBuffer;
		}

		internal unsafe static MemoryBuffer FromAddress(Process process, nuint bufferMagicAddress)
		{
			VirtualQueryUtility.VirtualQueryFunction virtualQueryFunction = VirtualQueryUtility.GetVirtualQueryFunction(process);
			Reloaded.Memory.Buffers.Internal.Kernel32.Kernel32.MEMORY_BASIC_INFORMATION memoryInformation = default(Reloaded.Memory.Buffers.Internal.Kernel32.Kernel32.MEMORY_BASIC_INFORMATION);
			UIntPtr uIntPtr = virtualQueryFunction(process.Handle, bufferMagicAddress, ref memoryInformation);
			if (uIntPtr == (UIntPtr)0uL)
			{
				throw new Exception("VirtualQuery failed. Result is 0.");
			}
			if (memoryInformation.State != 65536 && IsBuffer(process, bufferMagicAddress))
			{
				MemoryBuffer memoryBuffer = new MemoryBuffer(GetMemorySource(process), (UIntPtr)bufferMagicAddress + sizeof(MemoryBufferMagic));
				memoryBuffer.SetupMutex(process);
				return memoryBuffer;
			}
			return null;
		}

		internal static void AllocateBuffer(Process process, nuint bufferAddress, int bufferSize)
		{
			VirtualAllocUtility.VirtualAllocFunction virtualAllocFunction = VirtualAllocUtility.GetVirtualAllocFunction(process);
			UIntPtr uIntPtr = virtualAllocFunction(process.Handle, bufferAddress, (uint)bufferSize);
			if (uIntPtr == UIntPtr.Zero)
			{
				throw new Exception($"Failed to allocate MemoryBuffer of size {bufferSize} at address {bufferAddress}. Last Win32 Error: {Marshal.GetLastWin32Error()}");
			}
		}

		internal static IMemory GetMemorySource(Process process)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			if (process.Id == Process.GetCurrentProcess().Id)
			{
				return (IMemory)new Memory();
			}
			return (IMemory)new ExternalMemory(process);
		}

		internal static bool IsBuffer(Process process, nuint bufferMagicAddress)
		{
			try
			{
				MemoryBufferMagic other = default(MemoryBufferMagic);
				MemoryExtensions.SafeRead<IMemory, MemoryBufferMagic>(GetMemorySource(process), (UIntPtr)bufferMagicAddress, ref other);
				if (_bufferMagic.MagicEquals(ref other))
				{
					return true;
				}
			}
			catch
			{
			}
			return false;
		}
	}
	internal class MemoryBufferSearcher
	{
		private ConcurrentDictionary<nuint, MemoryBuffer> _bufferCache = new ConcurrentDictionary<UIntPtr, MemoryBuffer>();

		private Process _process;

		internal MemoryBufferSearcher(Process targetProcess)
		{
			_process = targetProcess;
		}

		internal void AddBuffer(MemoryBuffer buffer)
		{
			_bufferCache[buffer.AllocationAddress] = buffer;
		}

		internal MemoryBuffer[] FindBuffers()
		{
			List<Reloaded.Memory.Buffers.Internal.Kernel32.Kernel32.MEMORY_BASIC_INFORMATION> pages = MemoryPages.GetPages(_process);
			List<MemoryBuffer> list = new List<MemoryBuffer>();
			for (int i = 0; i < pages.Count; i++)
			{
				if (pages[i].State == 4096 && pages[i].Type == 131072 && pages[i].Protect == 64 && MemoryBufferFactory.IsBuffer(_process, pages[i].BaseAddress))
				{
					nuint baseAddress = pages[i].BaseAddress;
					MemoryBuffer memoryBuffer = MemoryBufferFactory.FromAddress(_process, baseAddress);
					AddBuffer(memoryBuffer);
					list.Add(memoryBuffer);
				}
			}
			return list.ToArray();
		}

		internal MemoryBuffer[] GetBuffers(int size, bool useCache = true)
		{
			if (useCache)
			{
				MemoryBuffer[] array = _bufferCache.Values.Where((MemoryBuffer x) => x.CanItemFit(size)).ToArray();
				if (array.Length != 0)
				{
					return array;
				}
			}
			MemoryBuffer[] source = FindBuffers();
			if (useCache)
			{
				return _bufferCache.Values.Where((MemoryBuffer x) => x.CanItemFit(size)).ToArray();
			}
			return source.Where((MemoryBuffer x) => x.CanItemFit(size)).ToArray();
		}
	}
}
namespace Reloaded.Memory.Buffers.Internal.Utilities
{
	internal static class Mathematics
	{
		internal static int RoundUp(int number, int multiple)
		{
			if (multiple == 0)
			{
				return number;
			}
			int num = number % multiple;
			if (num == 0)
			{
				return number;
			}
			return number + multiple - num;
		}

		internal static long RoundUp(long number, long multiple)
		{
			if (multiple == 0)
			{
				return number;
			}
			long num = number % multiple;
			if (num == 0)
			{
				return number;
			}
			return number + multiple - num;
		}

		internal static ulong RoundUp(ulong number, ulong multiple)
		{
			if (multiple == 0)
			{
				return number;
			}
			ulong num = number % multiple;
			if (num == 0)
			{
				return number;
			}
			return number + multiple - num;
		}

		internal static nuint RoundUp(nuint number, nuint multiple)
		{
			if (multiple == 0)
			{
				return number;
			}
			nuint num = number % multiple;
			if (num == 0)
			{
				return number;
			}
			return number + multiple - num;
		}

		internal static long RoundDown(long number, long multiple)
		{
			if (multiple == 0)
			{
				return number;
			}
			long num = number % multiple;
			if (num == 0)
			{
				return number;
			}
			return number - num;
		}

		internal static nuint RoundDown(nuint number, nuint multiple)
		{
			if (multiple == 0)
			{
				return number;
			}
			nuint num = number % multiple;
			if (num == 0)
			{
				return number;
			}
			return number - num;
		}
	}
	internal static class MutexObtainer
	{
		internal static Mutex MakeMutex(string mutexName)
		{
			try
			{
				return Mutex.OpenExisting(mutexName);
			}
			catch (WaitHandleCannotBeOpenedException)
			{
				return new Mutex(initiallyOwned: false, mutexName);
			}
		}
	}
	public static class VirtualAllocUtility
	{
		public delegate UIntPtr VirtualAllocFunction(IntPtr processHandle, nuint address, ulong size);

		public static VirtualAllocFunction GetVirtualAllocFunction(Process targetProcess)
		{
			VirtualAllocFunction result = VirtualAllocRemote;
			if (Process.GetCurrentProcess().Id == targetProcess.Id)
			{
				result = VirtualAllocLocal;
			}
			return result;
		}

		private static UIntPtr VirtualAllocLocal(IntPtr processHandle, nuint address, ulong size)
		{
			return Kernel32.VirtualAlloc((UIntPtr)address, (UIntPtr)size, (MEM_ALLOCATION_TYPE)12288, (MEM_PROTECTION)64);
		}

		private static UIntPtr VirtualAllocRemote(IntPtr processHandle, nuint address, ulong size)
		{
			return Kernel32.VirtualAllocEx(processHandle, (UIntPtr)address, (UIntPtr)size, (MEM_ALLOCATION_TYPE)12288, (MEM_PROTECTION)64);
		}
	}
	public static class VirtualFreeUtility
	{
		public delegate void VirtualFreeFunction(IntPtr processHandle, nuint address);

		public static VirtualFreeFunction GetVirtualFreeFunction(Process targetProcess)
		{
			VirtualFreeFunction result = VirtualFreeRemote;
			if (Process.GetCurrentProcess().Id == targetProcess.Id)
			{
				result = VirtualFreeLocal;
			}
			return result;
		}

		private static void VirtualFreeLocal(IntPtr processHandle, nuint address)
		{
			Kernel32.VirtualFree((UIntPtr)address, (UIntPtr)0uL, (MEM_ALLOCATION_TYPE)32768);
		}

		private static void VirtualFreeRemote(IntPtr processHandle, nuint address)
		{
			Kernel32.VirtualFreeEx(processHandle, (UIntPtr)address, (UIntPtr)0uL, (MEM_ALLOCATION_TYPE)32768);
		}
	}
	public static class VirtualQueryUtility
	{
		public delegate UIntPtr VirtualQueryFunction(IntPtr processHandle, nuint address, ref Reloaded.Memory.Buffers.Internal.Kernel32.Kernel32.MEMORY_BASIC_INFORMATION memoryInformation);

		[DllImport("kernel32.dll", SetLastError = true)]
		[SuppressUnmanagedCodeSecurity]
		private static extern UIntPtr VirtualQueryEx(IntPtr hProcess, nuint lpAddress, ref Reloaded.Memory.Buffers.Internal.Kernel32.Kernel32.MEMORY_BASIC_INFORMATION lpBuffer, UIntPtr dwLength);

		[DllImport("kernel32.dll", SetLastError = true)]
		[SuppressUnmanagedCodeSecurity]
		private static extern UIntPtr VirtualQuery(nuint lpAddress, ref Reloaded.Memory.Buffers.Internal.Kernel32.Kernel32.MEMORY_BASIC_INFORMATION lpBuffer, UIntPtr dwLength);

		public static VirtualQueryFunction GetVirtualQueryFunction(Process targetProcess)
		{
			VirtualQueryFunction result = VirtualQueryRemote;
			if (Process.GetCurrentProcess().Id == targetProcess.Id)
			{
				result = VirtualQueryLocal;
			}
			return result;
		}

		private unsafe static nuint VirtualQueryLocal(IntPtr processHandle, nuint address, ref Reloaded.Memory.Buffers.Internal.Kernel32.Kernel32.MEMORY_BASIC_INFORMATION memoryInformation)
		{
			return VirtualQuery(address, ref memoryInformation, (UIntPtr)(ulong)sizeof(Reloaded.Memory.Buffers.Internal.Kernel32.Kernel32.MEMORY_BASIC_INFORMATION));
		}

		private unsafe static nuint VirtualQueryRemote(IntPtr processHandle, nuint address, ref Reloaded.Memory.Buffers.Internal.Kernel32.Kernel32.MEMORY_BASIC_INFORMATION memoryInformation)
		{
			return VirtualQueryEx(processHandle, address, ref memoryInformation, (UIntPtr)(ulong)sizeof(Reloaded.Memory.Buffers.Internal.Kernel32.Kernel32.MEMORY_BASIC_INFORMATION));
		}
	}
}
namespace Reloaded.Memory.Buffers.Internal.Testing
{
	public static class Buffers
	{
		public static bool FreeBuffer(MemoryBuffer buffer)
		{
			return buffer.MemorySource.Free((UIntPtr)buffer.AllocationAddress);
		}
	}
}
namespace Reloaded.Memory.Buffers.Internal.Structs
{
	internal struct AddressRange
	{
		public nuint StartPointer;

		public nuint EndPointer;

		public AddressRange(nuint startPointer, nuint endPointer)
		{
			StartPointer = startPointer;
			EndPointer = endPointer;
		}

		public bool Contains(ref AddressRange otherRange)
		{
			if (otherRange.StartPointer >= StartPointer && otherRange.EndPointer <= EndPointer)
			{
				return true;
			}
			return false;
		}

		public bool Overlaps(ref AddressRange otherRange)
		{
			if (PointInRange(ref otherRange, StartPointer))
			{
				return true;
			}
			if (PointInRange(ref otherRange, EndPointer))
			{
				return true;
			}
			if (PointInRange(ref this, otherRange.StartPointer))
			{
				return true;
			}
			if (PointInRange(ref this, otherRange.EndPointer))
			{
				return true;
			}
			return false;
		}

		private bool PointInRange(ref AddressRange range, nuint point)
		{
			if (point >= range.StartPointer && point <= range.EndPointer)
			{
				return true;
			}
			return false;
		}
	}
	public struct BufferAllocationProperties
	{
		public nuint MemoryAddress;

		public int Size;

		public BufferAllocationProperties(nuint memoryAddress, int size)
		{
			MemoryAddress = memoryAddress;
			Size = size;
		}
	}
	public struct MemoryBufferMagic
	{
		public const int InitialSeed = 1;

		public const int MagicCount = 16;

		public unsafe fixed int ReloadedIdentifier[16];

		public MemoryBufferMagic(bool initialize)
		{
			if (initialize)
			{
				PseudoGenerate();
			}
		}

		public unsafe bool MagicEquals(ref MemoryBufferMagic other)
		{
			fixed (int* pointer = ReloadedIdentifier)
			{
				fixed (int* pointer2 = other.ReloadedIdentifier)
				{
					Span<int> span = new Span<int>(pointer, 16);
					Span<int> span2 = new Span<int>(pointer2, 16);
					for (int i = 0; i < 16; i++)
					{
						if (span[i] != span2[i])
						{
							return false;
						}
					}
					return true;
				}
			}
		}

		private unsafe void PseudoGenerate()
		{
			int num = 1;
			for (int i = 0; i < 16; i++)
			{
				ReloadedIdentifier[i] = num;
				num = (num + 13) * 31;
			}
		}
	}
}
namespace Reloaded.Memory.Buffers.Internal.Kernel32
{
	public class Kernel32
	{
		[StructLayout(LayoutKind.Sequential, Pack = 2)]
		public struct SYSTEM_INFO
		{
			public ProcessorArchitecture wProcessorArchitecture;

			public ushort wReserved;

			public uint dwPageSize;

			public nuint lpMinimumApplicationAddress;

			public nuint lpMaximumApplicationAddress;

			public UIntPtr dwActiveProcessorMask;

			public uint dwNumberOfProcessors;

			public uint dwProcessorType;

			public uint dwAllocationGranularity;

			public ushort wProcessorLevel;

			public ushort wProcessorRevision;
		}

		public struct MEMORY_BASIC_INFORMATION
		{
			public nuint BaseAddress;

			public nuint AllocationBase;

			public uint AllocationProtect;

			public nuint RegionSize;

			public uint State;

			public uint Protect;

			public uint Type;
		}

		public enum ProcessorArchitecture : ushort
		{
			PROCESSOR_ARCHITECTURE_INTEL = 0,
			PROCESSOR_ARCHITECTURE_MIPS = 1,
			PROCESSOR_ARCHITECTURE_ALPHA = 2,
			PROCESSOR_ARCHITECTURE_PPC = 3,
			PROCESSOR_ARCHITECTURE_SHX = 4,
			PROCESSOR_ARCHITECTURE_ARM = 5,
			PROCESSOR_ARCHITECTURE_IA64 = 6,
			PROCESSOR_ARCHITECTURE_ALPHA64 = 7,
			PROCESSOR_ARCHITECTURE_MSIL = 8,
			PROCESSOR_ARCHITECTURE_AMD64 = 9,
			PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 = 10,
			PROCESSOR_ARCHITECTURE_NEUTRAL = 11,
			PROCESSOR_ARCHITECTURE_ARM64 = 12,
			PROCESSOR_ARCHITECTURE_ARM32_ON_WIN64 = 13,
			PROCESSOR_ARCHITECTURE_UNKNOWN = ushort.MaxValue
		}

		[DllImport("kernel32.dll", SetLastError = true)]
		[SuppressUnmanagedCodeSecurity]
		[return: MarshalAs(UnmanagedType.Bool)]
		public static extern bool IsWow64Process([In] IntPtr hProcess, [MarshalAs(UnmanagedType.Bool)] out bool Wow64Process);

		[DllImport("kernel32.dll")]
		[SuppressUnmanagedCodeSecurity]
		public static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);
	}
}

GDWeave/core/Reloaded.Memory.dll

Decompiled 3 days ago
using System;
using System.Buffers.Binary;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using Microsoft.CodeAnalysis;
using Reloaded.Memory.Exceptions;
using Reloaded.Memory.Internal;
using Reloaded.Memory.Kernel32;
using Reloaded.Memory.Pointers;
using Reloaded.Memory.Sources;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCompany("Sewer56")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("A fully featured C# memory editing library supporting reading/writing primitive or generic struct types in either current or an external process.")]
[assembly: AssemblyFileVersion("8.0.1.0")]
[assembly: AssemblyInformationalVersion("8.0.1")]
[assembly: AssemblyProduct("Project Reloaded")]
[assembly: AssemblyTitle("Reloaded.Memory")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("8.0.1.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsUnmanagedAttribute : Attribute
	{
	}
	[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.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;
		}
	}
}
namespace Reloaded.Memory
{
	public static class Endian
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static byte Reverse(byte value)
		{
			return BinaryPrimitives.ReverseEndianness(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static sbyte Reverse(sbyte value)
		{
			return BinaryPrimitives.ReverseEndianness(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static short Reverse(short value)
		{
			return BinaryPrimitives.ReverseEndianness(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ushort Reverse(ushort value)
		{
			return BinaryPrimitives.ReverseEndianness(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int Reverse(int value)
		{
			return BinaryPrimitives.ReverseEndianness(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static uint Reverse(uint value)
		{
			return BinaryPrimitives.ReverseEndianness(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static long Reverse(long value)
		{
			return BinaryPrimitives.ReverseEndianness(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ulong Reverse(ulong value)
		{
			return BinaryPrimitives.ReverseEndianness(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Reverse(float value)
		{
			int value2 = Unsafe.As<float, int>(ref value);
			value2 = BinaryPrimitives.ReverseEndianness(value2);
			return Unsafe.As<int, float>(ref value2);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static double Reverse(double value)
		{
			long value2 = Unsafe.As<double, long>(ref value);
			value2 = BinaryPrimitives.ReverseEndianness(value2);
			return Unsafe.As<long, double>(ref value2);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void Reverse<T>(ref T type, out T swapped) where T : unmanaged
		{
			swapped = type;
			Reverse(ref swapped);
		}

		public unsafe static void Reverse<T>(ref T type) where T : unmanaged
		{
			byte* pointer = (byte*)Unsafe.AsPointer(ref type);
			new Span<byte>(pointer, sizeof(T)).Reverse();
		}
	}
	public interface IEndianReversible
	{
		void SwapEndian();
	}
	public static class Struct
	{
		public static IMemory Source { get; set; } = new Reloaded.Memory.Sources.Memory();


		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public static void ToPtr<T>(nuint pointer, T item, bool marshalElement = false)
		{
			ToPtr(pointer, ref item, marshalElement);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public static void ToPtr<T>(nuint pointer, ref T item, bool marshalElement = false)
		{
			ToPtr(pointer, ref item, Source.Write, marshalElement);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public static void FromPtr<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(nuint pointer, out T value, bool marshalElement = false)
		{
			FromPtr(pointer, out value, (Reloaded.Memory.Sources.MemoryExtensions.ReadFunction<T>)Source.Read, marshalElement);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToPtr<T>(nuint pointer, ref T item, Reloaded.Memory.Sources.MemoryExtensions.WriteFunction<T> writeFunction, bool marshalElement = false)
		{
			writeFunction(pointer, ref item, marshalElement);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void FromPtr<T>(nuint pointer, out T value, Reloaded.Memory.Sources.MemoryExtensions.ReadFunction<T> readFunction, bool marshalElement = false)
		{
			readFunction(pointer, out value, marshalElement);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static void FromArray<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(byte[] data, out T value, bool marshalElement, int startIndex)
		{
			fixed (byte* ptr = data)
			{
				value = Marshal.PtrToStructure<T>((IntPtr)(ptr + startIndex));
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void FromArray<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(byte[] data, out T value, bool marshalElement)
		{
			FromArray<T>(data, out value, marshalElement, 0);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void FromArray<T>(byte[] data, out T value, int startIndex) where T : unmanaged
		{
			Span<byte> span = new Span<byte>(data, startIndex, data.Length - startIndex);
			value = MemoryMarshal.Read<T>(span);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void FromArray<T>(byte[] data, out T value) where T : unmanaged
		{
			FromArray<T>(data, out value, 0);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void FromArray<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(Span<byte> data, out T value, bool marshalElement)
		{
			FromArray<T>(data, out value, marshalElement, 0);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static void FromArray<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(Span<byte> data, out T value, bool marshalElement, int startIndex)
		{
			fixed (byte* ptr = data)
			{
				value = Marshal.PtrToStructure<T>((IntPtr)(ptr + startIndex));
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void FromArray<T>(Span<byte> data, out T value) where T : unmanaged
		{
			value = MemoryMarshal.Read<T>(data);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int GetSize<T>(bool marshalElement)
		{
			if (!marshalElement)
			{
				return Unsafe.SizeOf<T>();
			}
			return Marshal.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int GetSize<T>() where T : unmanaged
		{
			return Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public static byte[] GetBytes<T>(T item) where T : unmanaged
		{
			return GetBytes(ref item);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public static Span<byte> GetBytes<T>(T item, Span<byte> buffer) where T : unmanaged
		{
			return GetBytes(ref item, buffer);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public static byte[] GetBytes<T>(T item, bool marshalElement)
		{
			return GetBytes(ref item, marshalElement);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public static Span<byte> GetBytes<T>(T item, bool marshalElement, Span<byte> buffer)
		{
			return GetBytes(ref item, marshalElement, buffer);
		}

		[SkipLocalsInit]
		public unsafe static byte[] GetBytes<T>(ref T item) where T : unmanaged
		{
			byte[] array = GC.AllocateUninitializedArray<byte>(sizeof(T));
			MemoryMarshal.Write(new Span<byte>(array), ref item);
			return array;
		}

		public unsafe static Span<byte> GetBytes<T>(ref T item, Span<byte> buffer) where T : unmanaged
		{
			MemoryMarshal.Write(buffer, ref item);
			return buffer.Slice(0, sizeof(T));
		}

		[SkipLocalsInit]
		public unsafe static byte[] GetBytes<T>(ref T item, bool marshalElement)
		{
			byte[] array = GC.AllocateUninitializedArray<byte>(GetSize<T>(marshalElement));
			fixed (byte* ptr = array)
			{
				Marshal.StructureToPtr(item, (IntPtr)ptr, fDeleteOld: false);
			}
			return array;
		}

		public unsafe static Span<byte> GetBytes<T>(ref T item, bool marshalElement, Span<byte> buffer)
		{
			fixed (byte* ptr = buffer)
			{
				Marshal.StructureToPtr(item, (IntPtr)ptr, fDeleteOld: false);
			}
			return buffer.Slice(0, GetSize<T>(marshalElement));
		}
	}
	public static class StructArray
	{
		private const int MaxStackLimit = 1024;

		public static void FromPtr<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(nuint memoryAddress, out T[] value, int arrayLength, bool marshal = false)
		{
			int size = Struct.GetSize<T>(marshal);
			value = GC.AllocateUninitializedArray<T>(arrayLength);
			for (int i = 0; i < arrayLength; i++)
			{
				Struct.FromPtr<T>((UIntPtr)memoryAddress + size * i, out var value2, marshal);
				value[i] = value2;
			}
		}

		public static void ToPtr<T>(nuint memoryAddress, T[] item, bool marshal = false)
		{
			int size = Struct.GetSize<T>(marshal);
			for (int i = 0; i < item.Length; i++)
			{
				Struct.ToPtr((UIntPtr)memoryAddress + size * i, ref item[i], marshal);
			}
		}

		public static void FromArray<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(byte[] data, out T[] value, bool marshalElement, int length, int startIndex)
		{
			FromArray<T>(data.AsSpan(), out value, marshalElement, length, startIndex);
		}

		public static void FromArray<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(byte[] data, out T[] value, bool marshalElement, int length)
		{
			FromArray<T>(data.AsSpan(), out value, marshalElement, length, 0);
		}

		public static void FromArray<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(byte[] data, out T[] value, bool marshalElement)
		{
			FromArray<T>(data.AsSpan(), out value, marshalElement, 0, 0);
		}

		public static void FromArray<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(Span<byte> data, out T[] value, bool marshalElement, int length, int startIndex)
		{
			int size = Struct.GetSize<T>(marshalElement);
			int num = ((length == 0) ? ((data.Length - startIndex) / size) : length);
			value = new T[num];
			for (int i = 0; i < value.Length; i++)
			{
				int startIndex2 = startIndex + size * i;
				Struct.FromArray<T>(data, out var value2, marshalElement, startIndex2);
				value[i] = value2;
			}
		}

		public static void FromArray<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(Span<byte> data, out T[] value, bool marshalElement, int length)
		{
			FromArray<T>(data, out value, marshalElement, length, 0);
		}

		public static void FromArray<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(Span<byte> data, out T[] value, bool marshalElement)
		{
			FromArray<T>(data, out value, marshalElement, 0, 0);
		}

		public static void FromArray<T>(byte[] data, out T[] value, int startIndex, int length) where T : unmanaged
		{
			int size = Struct.GetSize<T>();
			int length2 = ((length == 0) ? ((data.Length - startIndex) / size) : length);
			value = GC.AllocateUninitializedArray<T>(length2);
			for (int i = 0; i < value.Length; i++)
			{
				int startIndex2 = startIndex + size * i;
				Struct.FromArray<T>(data, out var value2, startIndex2);
				value[i] = value2;
			}
		}

		public static void FromArray<T>(byte[] data, out T[] value, int startIndex) where T : unmanaged
		{
			FromArray<T>(data, out value, startIndex, 0);
		}

		public static void FromArray<T>(byte[] data, out T[] value) where T : unmanaged
		{
			FromArray<T>(data, out value, 0, 0);
		}

		public static void FromArray<T>(Span<byte> data, out T[] value, int length) where T : unmanaged
		{
			int size = Struct.GetSize<T>();
			int length2 = ((length == 0) ? (data.Length / size) : length);
			value = GC.AllocateUninitializedArray<T>(length2);
			for (int i = 0; i < value.Length; i++)
			{
				Struct.FromArray<T>(data, out value[i]);
				data = data.Slice(size);
			}
		}

		public static void FromArray<T>(Span<byte> data, out T[] value) where T : unmanaged
		{
			FromArray<T>(data, out value, 0);
		}

		public static void FromArrayBigEndianPrimitive<T>(byte[] data, out T[] value, int startIndex, int length) where T : unmanaged
		{
			FromArray<T>(data, out value, startIndex, length);
			for (int i = 0; i < value.Length; i++)
			{
				Endian.Reverse(ref value[i], out value[i]);
			}
		}

		public static void FromArrayBigEndianPrimitive<T>(byte[] data, out T[] value, int startIndex) where T : unmanaged
		{
			FromArrayBigEndianPrimitive<T>(data, out value, startIndex, 0);
		}

		public static void FromArrayBigEndianPrimitive<T>(byte[] data, out T[] value) where T : unmanaged
		{
			FromArrayBigEndianPrimitive<T>(data, out value, 0, 0);
		}

		public static void FromArrayBigEndianPrimitive<T>(Span<byte> data, out T[] value, int length) where T : unmanaged
		{
			FromArray<T>(data, out value, length);
			for (int i = 0; i < value.Length; i++)
			{
				Endian.Reverse(ref value[i], out value[i]);
			}
		}

		public static void FromArrayBigEndianPrimitive<T>(Span<byte> data, out T[] value) where T : unmanaged
		{
			FromArrayBigEndianPrimitive<T>(data, out value, 0);
		}

		public static void FromArrayBigEndianStruct<T>(byte[] data, out T[] value, int startIndex, int length) where T : unmanaged, IEndianReversible
		{
			FromArray<T>(data, out value, startIndex, length);
			for (int i = 0; i < value.Length; i++)
			{
				value[i].SwapEndian();
			}
		}

		public static void FromArrayBigEndianStruct<T>(byte[] data, out T[] value, int startIndex) where T : unmanaged, IEndianReversible
		{
			FromArrayBigEndianStruct<T>(data, out value, startIndex, 0);
		}

		public static void FromArrayBigEndianStruct<T>(Span<byte> data, out T[] value, int length) where T : unmanaged, IEndianReversible
		{
			FromArray<T>(data, out value, length);
			for (int i = 0; i < value.Length; i++)
			{
				value[i].SwapEndian();
			}
		}

		public static void FromArrayBigEndianStruct<T>(Span<byte> data, out T[] value) where T : unmanaged, IEndianReversible
		{
			FromArrayBigEndianStruct<T>(data, out value, 0);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int GetSize<T>(int elementCount, bool marshalElement)
		{
			return Struct.GetSize<T>(marshalElement) * elementCount;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int GetSize<T>(int elementCount) where T : unmanaged
		{
			return Struct.GetSize<T>() * elementCount;
		}

		public static byte[] GetBytes<T>(T[] items, bool marshalElements)
		{
			byte[] array = GC.AllocateUninitializedArray<byte>(Struct.GetSize<T>(marshalElements) * items.Length);
			GetBytes(items, marshalElements, array.AsSpan());
			return array;
		}

		public static Span<byte> GetBytes<T>(T[] items, bool marshalElements, Span<byte> buffer)
		{
			int size = Struct.GetSize<T>(marshalElements);
			Span<byte> span = buffer[..(size * items.Length)];
			if (size < 1024)
			{
				Span<byte> currentItem2 = stackalloc byte[size];
				GetBytesInternal(items, size, marshalElements, currentItem2, span);
			}
			else
			{
				Span<byte> currentItem3 = new byte[size];
				GetBytesInternal(items, size, marshalElements, currentItem3, span);
			}
			return span;
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			static void GetBytesInternal(T[] items, int sizeOfItem, bool marshalElements, Span<byte> currentItem, Span<byte> resultSpan)
			{
				for (int i = 0; i < items.Length; i++)
				{
					Struct.GetBytes(ref items[i], marshalElements, currentItem);
					currentItem.CopyTo(resultSpan);
					resultSpan = resultSpan.Slice(sizeOfItem);
				}
			}
		}

		public static byte[] GetBytes<T>(T[] items) where T : unmanaged
		{
			byte[] array = GC.AllocateUninitializedArray<byte>(GetSize<T>(items.Length));
			GetBytes(items, array.AsSpan());
			return array;
		}

		[SkipLocalsInit]
		public unsafe static Span<byte> GetBytes<T>(T[] items, Span<byte> buffer) where T : unmanaged
		{
			Span<byte> span2 = buffer[..GetSize<T>(items.Length)];
			if (sizeof(T) < 1024)
			{
				Span<byte> currentItem2 = stackalloc byte[sizeof(T)];
				GetBytesInternal(items, currentItem2, span2);
			}
			else
			{
				Span<byte> currentItem3 = new byte[sizeof(T)];
				GetBytesInternal(items, currentItem3, span2);
			}
			return span2;
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			static unsafe void GetBytesInternal(T[] items, Span<byte> currentItem, Span<byte> span)
			{
				for (int i = 0; i < items.Length; i++)
				{
					Struct.GetBytes(ref items[i], currentItem);
					currentItem.CopyTo(span);
					span = span.Slice(sizeof(T));
				}
			}
		}
	}
}
namespace Reloaded.Memory.Utilities
{
	public static class Blittable
	{
		private static class IsBlittableCache<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>
		{
			public static readonly bool Value = IsBlittable(typeof(T));
		}

		public static bool IsBlittable<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>()
		{
			return IsBlittableCache<T>.Value;
		}

		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2072", Justification = "Analyzer reflection skill issue in IsBlittable.")]
		public static bool IsBlittable([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type type)
		{
			if (type.IsArray)
			{
				Type elementType = type.GetElementType();
				if (elementType.IsValueType)
				{
					return IsBlittable(elementType);
				}
				return false;
			}
			try
			{
				GCHandle.Alloc(FormatterServices.GetUninitializedObject(type), GCHandleType.Pinned).Free();
				return true;
			}
			catch
			{
				return false;
			}
		}
	}
	public class CircularBuffer : IDisposable
	{
		public enum ItemFit
		{
			No,
			Yes,
			StartOfBuffer
		}

		public IMemory Source { get; }

		public int Offset { get; set; }

		public nuint Address { get; set; }

		public int Size { get; set; }

		public nuint WritePointer => (UIntPtr)Address + Offset;

		private int Remaining => Size - Offset;

		public CircularBuffer(int size, IMemory source)
		{
			Offset = 0;
			Size = size;
			Source = source;
			Address = source.Allocate(Size);
		}

		[ExcludeFromCodeCoverage]
		~CircularBuffer()
		{
			Dispose();
		}

		public nuint Add(byte[] bytesToWrite)
		{
			switch (CanItemFit(bytesToWrite.Length))
			{
			case ItemFit.No:
				return 0u;
			case ItemFit.StartOfBuffer:
				Offset = 0;
				break;
			}
			nuint writePointer = WritePointer;
			Source.WriteRaw(writePointer, bytesToWrite);
			Offset += bytesToWrite.Length;
			return writePointer;
		}

		public nuint Add<TStructure>(ref TStructure item, bool marshalElement = false)
		{
			return Add(Struct.GetBytes(ref item, marshalElement));
		}

		public ItemFit CanItemFit(int objectSize)
		{
			if (Remaining >= objectSize)
			{
				return ItemFit.Yes;
			}
			if (Size >= objectSize)
			{
				return ItemFit.StartOfBuffer;
			}
			return ItemFit.No;
		}

		public ItemFit CanItemFit<TStructure>(ref TStructure item, bool marshalElement = false)
		{
			return CanItemFit(Struct.GetSize<TStructure>(marshalElement));
		}

		public void Dispose()
		{
			Source.Free(Address);
			GC.SuppressFinalize(this);
		}
	}
}
namespace Reloaded.Memory.Streams
{
	public class BufferedStreamReader : IDisposable
	{
		private readonly Stream _stream;

		private readonly byte[] _buffer;

		private readonly int _bufferSize;

		private int _bufferOffset;

		private int _bufferedBytesRemaining;

		private GCHandle _gcHandle;

		private IntPtr _gcHandlePtr;

		private Reloaded.Memory.Sources.Memory _memory = new Reloaded.Memory.Sources.Memory();

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public unsafe void ReadBigEndianPrimitive(out short value)
		{
			int num = 2;
			ReFillIfNecessary(num);
			value = *(short*)(void*)(_gcHandlePtr + _bufferOffset);
			value = Endian.Reverse(value);
			_bufferOffset += num;
			_bufferedBytesRemaining -= num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public short ReadBigEndianPrimitiveInt16()
		{
			ReadBigEndianPrimitive(out short value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public unsafe void PeekBigEndianPrimitive(out short value)
		{
			ReFillIfNecessary(2);
			value = *(short*)(void*)(_gcHandlePtr + _bufferOffset);
			value = Endian.Reverse(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public short PeekBigEndianPrimitiveInt16()
		{
			PeekBigEndianPrimitive(out short value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public unsafe void ReadBigEndianPrimitive(out ushort value)
		{
			int num = 2;
			ReFillIfNecessary(num);
			value = *(ushort*)(void*)(_gcHandlePtr + _bufferOffset);
			value = Endian.Reverse(value);
			_bufferOffset += num;
			_bufferedBytesRemaining -= num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public ushort ReadBigEndianPrimitiveUInt16()
		{
			ReadBigEndianPrimitive(out ushort value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public unsafe void PeekBigEndianPrimitive(out ushort value)
		{
			ReFillIfNecessary(2);
			value = *(ushort*)(void*)(_gcHandlePtr + _bufferOffset);
			value = Endian.Reverse(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public ushort PeekBigEndianPrimitiveUInt16()
		{
			PeekBigEndianPrimitive(out ushort value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public unsafe void ReadBigEndianPrimitive(out int value)
		{
			int num = 4;
			ReFillIfNecessary(num);
			value = *(int*)(void*)(_gcHandlePtr + _bufferOffset);
			value = Endian.Reverse(value);
			_bufferOffset += num;
			_bufferedBytesRemaining -= num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public int ReadBigEndianPrimitiveInt32()
		{
			ReadBigEndianPrimitive(out int value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public unsafe void PeekBigEndianPrimitive(out int value)
		{
			ReFillIfNecessary(4);
			value = *(int*)(void*)(_gcHandlePtr + _bufferOffset);
			value = Endian.Reverse(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public int PeekBigEndianPrimitiveInt32()
		{
			PeekBigEndianPrimitive(out int value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public unsafe void ReadBigEndianPrimitive(out uint value)
		{
			int num = 4;
			ReFillIfNecessary(num);
			value = *(uint*)(void*)(_gcHandlePtr + _bufferOffset);
			value = Endian.Reverse(value);
			_bufferOffset += num;
			_bufferedBytesRemaining -= num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public uint ReadBigEndianPrimitiveUInt32()
		{
			ReadBigEndianPrimitive(out uint value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public unsafe void PeekBigEndianPrimitive(out uint value)
		{
			ReFillIfNecessary(4);
			value = *(uint*)(void*)(_gcHandlePtr + _bufferOffset);
			value = Endian.Reverse(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public uint PeekBigEndianPrimitiveUInt32()
		{
			PeekBigEndianPrimitive(out uint value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public unsafe void ReadBigEndianPrimitive(out long value)
		{
			int num = 8;
			ReFillIfNecessary(num);
			value = *(long*)(void*)(_gcHandlePtr + _bufferOffset);
			value = Endian.Reverse(value);
			_bufferOffset += num;
			_bufferedBytesRemaining -= num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public long ReadBigEndianPrimitiveInt64()
		{
			ReadBigEndianPrimitive(out long value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public unsafe void PeekBigEndianPrimitive(out long value)
		{
			ReFillIfNecessary(8);
			value = *(long*)(void*)(_gcHandlePtr + _bufferOffset);
			value = Endian.Reverse(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public long PeekBigEndianPrimitiveInt64()
		{
			PeekBigEndianPrimitive(out long value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public unsafe void ReadBigEndianPrimitive(out ulong value)
		{
			int num = 8;
			ReFillIfNecessary(num);
			value = *(ulong*)(void*)(_gcHandlePtr + _bufferOffset);
			value = Endian.Reverse(value);
			_bufferOffset += num;
			_bufferedBytesRemaining -= num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public ulong ReadBigEndianPrimitiveUInt64()
		{
			ReadBigEndianPrimitive(out ulong value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public unsafe void PeekBigEndianPrimitive(out ulong value)
		{
			ReFillIfNecessary(8);
			value = *(ulong*)(void*)(_gcHandlePtr + _bufferOffset);
			value = Endian.Reverse(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public ulong PeekBigEndianPrimitiveUInt64()
		{
			PeekBigEndianPrimitive(out ulong value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public unsafe void ReadBigEndianPrimitive(out float value)
		{
			int num = 4;
			ReFillIfNecessary(num);
			value = *(float*)(void*)(_gcHandlePtr + _bufferOffset);
			value = Endian.Reverse(value);
			_bufferOffset += num;
			_bufferedBytesRemaining -= num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public float ReadBigEndianPrimitiveSingle()
		{
			ReadBigEndianPrimitive(out float value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public unsafe void PeekBigEndianPrimitive(out float value)
		{
			ReFillIfNecessary(4);
			value = *(float*)(void*)(_gcHandlePtr + _bufferOffset);
			value = Endian.Reverse(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public float PeekBigEndianPrimitiveSingle()
		{
			PeekBigEndianPrimitive(out float value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public unsafe void ReadBigEndianPrimitive(out double value)
		{
			int num = 8;
			ReFillIfNecessary(num);
			value = *(double*)(void*)(_gcHandlePtr + _bufferOffset);
			value = Endian.Reverse(value);
			_bufferOffset += num;
			_bufferedBytesRemaining -= num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public double ReadBigEndianPrimitiveDouble()
		{
			ReadBigEndianPrimitive(out double value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public unsafe void PeekBigEndianPrimitive(out double value)
		{
			ReFillIfNecessary(8);
			value = *(double*)(void*)(_gcHandlePtr + _bufferOffset);
			value = Endian.Reverse(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public double PeekBigEndianPrimitiveDouble()
		{
			PeekBigEndianPrimitive(out double value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Stream BaseStream()
		{
			return _stream;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public int BufferBytesAvailable()
		{
			return _bufferedBytesRemaining;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public int CurrentBufferSize()
		{
			return _bufferOffset + _bufferedBytesRemaining;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public long Position()
		{
			return _stream.Position - _bufferedBytesRemaining;
		}

		public BufferedStreamReader(Stream stream, int bufferSize)
		{
			_stream = stream;
			_bufferSize = bufferSize;
			_buffer = new byte[bufferSize];
			_bufferOffset = bufferSize;
			_gcHandle = GCHandle.Alloc(_buffer, GCHandleType.Pinned);
			_gcHandlePtr = _gcHandle.AddrOfPinnedObject();
		}

		~BufferedStreamReader()
		{
			Dispose();
		}

		public void Dispose()
		{
			if (_gcHandle.IsAllocated)
			{
				_gcHandle.Free();
			}
			GC.SuppressFinalize(this);
		}

		public void Seek(long offset, SeekOrigin origin)
		{
			switch (origin)
			{
			case SeekOrigin.Current:
				RelativeSeek(offset);
				break;
			case SeekOrigin.Begin:
			{
				long relativeOffset2 = offset - Position();
				RelativeSeek(relativeOffset2);
				break;
			}
			case SeekOrigin.End:
			{
				long relativeOffset = _stream.Length - offset - Position();
				RelativeSeek(relativeOffset);
				break;
			}
			}
		}

		public byte[] ReadBytes(long offset, int count)
		{
			long position = _stream.Position;
			_stream.Position = offset;
			byte[] result = GC.AllocateUninitializedArray<byte>(count);
			if (!_stream.TryReadSafe(result))
			{
				BufferedStreamReaderException.Throw("Could not read enough bytes from stream.");
			}
			_stream.Position = position;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[SkipLocalsInit]
		public unsafe void Read<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(out T value, bool marshal)
		{
			int size = Struct.GetSize<T>(marshal);
			ReFillIfNecessary(size);
			_memory.Read<T>((UIntPtr)(void*)_gcHandlePtr + _bufferOffset, out value, marshal);
			_bufferOffset += size;
			_bufferedBytesRemaining -= size;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[SkipLocalsInit]
		public unsafe void Read<T>(out T value) where T : unmanaged
		{
			int num = sizeof(T);
			ReFillIfNecessary(num);
			value = *(T*)(void*)(_gcHandlePtr + _bufferOffset);
			_bufferOffset += num;
			_bufferedBytesRemaining -= num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public T Read<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(bool marshal)
		{
			Read<T>(out var value, marshal);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public T Read<T>() where T : unmanaged
		{
			Read<T>(out var value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void Peek<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(out T value, bool marshal)
		{
			ReFillIfNecessary(Struct.GetSize<T>(marshal));
			_memory.Read<T>((UIntPtr)(void*)_gcHandlePtr + _bufferOffset, out value, marshal);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void Peek<T>(out T value) where T : unmanaged
		{
			ReFillIfNecessary(sizeof(T));
			value = *(T*)(void*)(_gcHandlePtr + _bufferOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public T Peek<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(bool marshal)
		{
			Peek<T>(out var value, marshal);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public T Peek<T>() where T : unmanaged
		{
			Peek<T>(out var value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[SkipLocalsInit]
		public unsafe void ReadBigEndianPrimitive<T>(out T value) where T : unmanaged
		{
			int num = sizeof(T);
			ReFillIfNecessary(num);
			value = *(T*)(void*)(_gcHandlePtr + _bufferOffset);
			Endian.Reverse(ref value);
			_bufferOffset += num;
			_bufferedBytesRemaining -= num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[SkipLocalsInit]
		public unsafe void ReadBigEndianStruct<T>(out T value) where T : unmanaged, IEndianReversible
		{
			int num = sizeof(T);
			ReFillIfNecessary(num);
			value = *(T*)(void*)(_gcHandlePtr + _bufferOffset);
			value.SwapEndian();
			_bufferOffset += num;
			_bufferedBytesRemaining -= num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public T ReadBigEndianPrimitive<T>() where T : unmanaged
		{
			ReadBigEndianPrimitive(out T value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public T ReadBigEndianStruct<T>() where T : unmanaged, IEndianReversible
		{
			ReadBigEndianStruct<T>(out var value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void PeekBigEndianPrimitive<T>(out T value) where T : unmanaged
		{
			ReFillIfNecessary(sizeof(T));
			value = *(T*)(void*)(_gcHandlePtr + _bufferOffset);
			Endian.Reverse(ref value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void PeekBigEndianStruct<T>(out T value) where T : unmanaged, IEndianReversible
		{
			ReFillIfNecessary(sizeof(T));
			value = *(T*)(void*)(_gcHandlePtr + _bufferOffset);
			value.SwapEndian();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public T PeekBigEndianPrimitive<T>() where T : unmanaged
		{
			PeekBigEndianPrimitive(out T value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public T PeekBigEndianStruct<T>() where T : unmanaged, IEndianReversible
		{
			PeekBigEndianStruct<T>(out var value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool CanRead(int size)
		{
			return size <= _bufferedBytesRemaining;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void ReFillIfNecessary(int size)
		{
			if (!CanRead(size))
			{
				ReFillBuffer();
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void ReFillBuffer()
		{
			_stream.Seek(_bufferedBytesRemaining * -1, SeekOrigin.Current);
			FillBuffer();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void FillBuffer()
		{
			_bufferedBytesRemaining = _stream.Read(_buffer, 0, _bufferSize);
			_bufferOffset = 0;
		}

		private void RelativeSeek(long relativeOffset)
		{
			if (!FastSeekRelativeToCurrent(relativeOffset))
			{
				long offset = Position() + relativeOffset - _stream.Position;
				_stream.Seek(offset, SeekOrigin.Current);
				FillBuffer();
			}
		}

		private bool FastSeekRelativeToCurrent(long offset)
		{
			if (offset >= 0)
			{
				if (offset <= _bufferedBytesRemaining)
				{
					_bufferOffset += (int)offset;
					_bufferedBytesRemaining -= (int)offset;
					return true;
				}
			}
			else if (offset * -1 <= _bufferOffset)
			{
				_bufferOffset += (int)offset;
				_bufferedBytesRemaining -= (int)offset;
				return true;
			}
			return false;
		}
	}
	public class ExtendedMemoryStream : MemoryStream
	{
		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(byte structure)
		{
			structure = Endian.Reverse(structure);
			Write(ref structure);
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(byte[] structures)
		{
			foreach (byte structure in structures)
			{
				WriteBigEndianPrimitive(structure);
			}
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(sbyte structure)
		{
			structure = Endian.Reverse(structure);
			Write(ref structure);
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(sbyte[] structures)
		{
			foreach (sbyte structure in structures)
			{
				WriteBigEndianPrimitive(structure);
			}
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(short structure)
		{
			structure = Endian.Reverse(structure);
			Write(ref structure);
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(short[] structures)
		{
			foreach (short structure in structures)
			{
				WriteBigEndianPrimitive(structure);
			}
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(ushort structure)
		{
			structure = Endian.Reverse(structure);
			Write(ref structure);
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(ushort[] structures)
		{
			foreach (ushort structure in structures)
			{
				WriteBigEndianPrimitive(structure);
			}
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(int structure)
		{
			structure = Endian.Reverse(structure);
			Write(ref structure);
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(int[] structures)
		{
			foreach (int structure in structures)
			{
				WriteBigEndianPrimitive(structure);
			}
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(uint structure)
		{
			structure = Endian.Reverse(structure);
			Write(ref structure);
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(uint[] structures)
		{
			foreach (uint structure in structures)
			{
				WriteBigEndianPrimitive(structure);
			}
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(long structure)
		{
			structure = Endian.Reverse(structure);
			Write(ref structure);
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(long[] structures)
		{
			foreach (long structure in structures)
			{
				WriteBigEndianPrimitive(structure);
			}
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(ulong structure)
		{
			structure = Endian.Reverse(structure);
			Write(ref structure);
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(ulong[] structures)
		{
			foreach (ulong structure in structures)
			{
				WriteBigEndianPrimitive(structure);
			}
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(float structure)
		{
			structure = Endian.Reverse(structure);
			Write(ref structure);
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(float[] structures)
		{
			foreach (float structure in structures)
			{
				WriteBigEndianPrimitive(structure);
			}
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(double structure)
		{
			structure = Endian.Reverse(structure);
			Write(ref structure);
		}

		[ExcludeFromCodeCoverage]
		public void WriteBigEndianPrimitive(double[] structures)
		{
			foreach (double structure in structures)
			{
				WriteBigEndianPrimitive(structure);
			}
		}

		public ExtendedMemoryStream()
		{
		}

		public ExtendedMemoryStream(byte[] buffer)
			: base(buffer)
		{
		}

		public ExtendedMemoryStream(byte[] buffer, bool writable)
			: base(buffer, writable)
		{
		}

		public ExtendedMemoryStream(byte[] buffer, int index, int count)
			: base(buffer, index, count)
		{
		}

		public ExtendedMemoryStream(byte[] buffer, int index, int count, bool writable)
			: base(buffer, index, count, writable)
		{
		}

		public ExtendedMemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible)
			: base(buffer, index, count, writable, publiclyVisible)
		{
		}

		public ExtendedMemoryStream(int capacity)
			: base(capacity)
		{
		}

		public void AddPadding(int alignment = 2048)
		{
			StreamExtensions.AddPadding(this, alignment);
		}

		public void AddPadding(byte value, int alignment = 2048)
		{
			StreamExtensions.AddPadding(this, value, alignment);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Write<T>(T[] structure) where T : unmanaged
		{
			StreamExtensions.Write(this, structure);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Write<T>(T[] structure, bool marshalStructure)
		{
			StreamExtensions.Write(this, structure, marshalStructure);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Write<T>(T structure) where T : unmanaged
		{
			StreamExtensions.Write(this, ref structure);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Write<T>(ref T structure) where T : unmanaged
		{
			StreamExtensions.Write(this, ref structure);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public new void Write(ReadOnlySpan<byte> source)
		{
			base.Write(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Write<T>(T structure, bool marshalStructure)
		{
			StreamExtensions.Write(this, ref structure, marshalStructure);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Write<T>(ref T structure, bool marshalStructure)
		{
			StreamExtensions.Write(this, ref structure, marshalStructure);
		}

		public void Write(byte[] data)
		{
			Write(data, 0, data.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void WriteBigEndianPrimitive<T>(T[] structures) where T : unmanaged
		{
			StreamExtensions.WriteBigEndianPrimitive(this, structures);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void WriteBigEndianStruct<T>(T[] structures) where T : unmanaged, IEndianReversible
		{
			StreamExtensions.WriteBigEndianStruct(this, structures);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void WriteBigEndianPrimitive<T>(T structure) where T : unmanaged
		{
			StreamExtensions.WriteBigEndianPrimitive(this, structure);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void WriteBigEndianStruct<T>(T structure) where T : unmanaged, IEndianReversible
		{
			StreamExtensions.WriteBigEndianStruct(this, structure);
		}
	}
	public static class StreamExtensions
	{
		private const int MaxStackLimit = 1024;

		public static void AddPadding(this Stream stream, int alignment = 2048)
		{
			long num = Reloaded.Memory.Internal.Utilities.RoundUp((int)stream.Position, alignment) - stream.Position;
			if (num > 0)
			{
				stream.Write(new byte[num], 0, (int)num);
			}
		}

		public static void AddPadding(this Stream stream, byte value, int alignment = 2048)
		{
			long num = Reloaded.Memory.Internal.Utilities.RoundUp((int)stream.Position, alignment) - stream.Position;
			if (num > 0)
			{
				byte[] array = GC.AllocateUninitializedArray<byte>((int)num);
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = value;
				}
				stream.Write(array, 0, (int)num);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void Write<T>(this Stream stream, T[] structure) where T : unmanaged
		{
			for (int i = 0; i < structure.Length; i++)
			{
				stream.Write(ref structure[i]);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void Write<T>(this Stream stream, T[] structure, bool marshalStructure)
		{
			for (int i = 0; i < structure.Length; i++)
			{
				stream.Write(ref structure[i], marshalStructure);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void Write<T>(this Stream stream, T structure) where T : unmanaged
		{
			stream.Write(ref structure);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[SkipLocalsInit]
		public unsafe static void Write<T>(this Stream stream, ref T structure) where T : unmanaged
		{
			if (sizeof(T) < 1024)
			{
				Span<T> span = MemoryMarshal.CreateSpan(ref structure, 1);
				stream.Write(MemoryMarshal.Cast<T, byte>(span));
			}
			else
			{
				stream.Write(Struct.GetBytes(structure));
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void Write<T>(this Stream stream, T structure, bool marshalStructure)
		{
			stream.Write(ref structure, marshalStructure);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[SkipLocalsInit]
		public static void Write<T>(this Stream stream, ref T structure, bool marshalStructure)
		{
			int size = Struct.GetSize<T>(marshalElement: true);
			if (size < 1024)
			{
				Span<byte> span = stackalloc byte[size];
				Struct.GetBytes(ref structure, marshalStructure, span);
				stream.Write(span);
			}
			else
			{
				stream.Write(Struct.GetBytes(structure, marshalStructure));
			}
		}

		public static void Write(this Stream stream, byte[] data)
		{
			stream.Write(data, 0, data.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void WriteBigEndianPrimitive<T>(this Stream stream, T[] structures) where T : unmanaged
		{
			for (int i = 0; i < structures.Length; i++)
			{
				stream.WriteBigEndianPrimitive(structures[i]);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void WriteBigEndianStruct<T>(this Stream stream, T[] structures) where T : unmanaged, IEndianReversible
		{
			for (int i = 0; i < structures.Length; i++)
			{
				stream.WriteBigEndianStruct(structures[i]);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void WriteBigEndianPrimitive<T>(this Stream stream, T structure) where T : unmanaged
		{
			Endian.Reverse(ref structure);
			stream.Write(ref structure);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void WriteBigEndianStruct<T>(this Stream stream, T structure) where T : unmanaged, IEndianReversible
		{
			structure.SwapEndian();
			stream.Write(ref structure);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool TryReadSafe(this Stream stream, byte[] result)
		{
			int num = 0;
			int num2 = result.Length;
			while (num2 > 0)
			{
				int num3 = stream.Read(result, num, num2);
				if (num3 <= 0)
				{
					return false;
				}
				num += num3;
				num2 -= num3;
			}
			return true;
		}
	}
}
namespace Reloaded.Memory.Streams.Writers
{
	public class BigEndianMemoryStream : EndianMemoryStream
	{
		public BigEndianMemoryStream(ExtendedMemoryStream stream)
			: base(stream)
		{
		}

		public BigEndianMemoryStream(ExtendedMemoryStream stream, bool disposeUnderlyingStream = true)
			: base(stream, disposeUnderlyingStream)
		{
		}

		public override void Write<T>(T[] structure)
		{
			base.Stream.WriteBigEndianPrimitive(structure);
		}

		public override void Write<T>(T structure)
		{
			base.Stream.WriteBigEndianPrimitive(structure);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void WriteStruct<T>(T[] structures) where T : unmanaged, IEndianReversible
		{
			base.Stream.WriteBigEndianStruct(structures);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void WriteStruct<T>(T structure) where T : unmanaged, IEndianReversible
		{
			base.Stream.WriteBigEndianStruct(structure);
		}

		[ExcludeFromCodeCoverage]
		public override void WriteInt16(short data)
		{
			base.Stream.WriteBigEndianPrimitive(data);
		}

		[ExcludeFromCodeCoverage]
		public override void WriteUInt16(ushort data)
		{
			base.Stream.WriteBigEndianPrimitive(data);
		}

		[ExcludeFromCodeCoverage]
		public override void WriteInt32(int data)
		{
			base.Stream.WriteBigEndianPrimitive(data);
		}

		[ExcludeFromCodeCoverage]
		public override void WriteUInt32(uint data)
		{
			base.Stream.WriteBigEndianPrimitive(data);
		}

		[ExcludeFromCodeCoverage]
		public override void WriteInt64(long data)
		{
			base.Stream.WriteBigEndianPrimitive(data);
		}

		[ExcludeFromCodeCoverage]
		public override void WriteUInt64(ulong data)
		{
			base.Stream.WriteBigEndianPrimitive(data);
		}

		[ExcludeFromCodeCoverage]
		public override void WriteSingle(float data)
		{
			base.Stream.WriteBigEndianPrimitive(data);
		}

		[ExcludeFromCodeCoverage]
		public override void WriteDouble(double data)
		{
			base.Stream.WriteBigEndianPrimitive(data);
		}
	}
	public abstract class EndianMemoryStream : IDisposable
	{
		public ExtendedMemoryStream Stream { get; private set; }

		public bool DisposeUnderlyingStream { get; private set; } = true;


		protected EndianMemoryStream(ExtendedMemoryStream stream)
		{
			Stream = stream;
		}

		protected EndianMemoryStream(ExtendedMemoryStream stream, bool disposeUnderlyingStream)
		{
			Stream = stream;
			DisposeUnderlyingStream = disposeUnderlyingStream;
		}

		~EndianMemoryStream()
		{
			Dispose();
		}

		public void Dispose()
		{
			if (DisposeUnderlyingStream)
			{
				Stream?.Dispose();
			}
			GC.SuppressFinalize(this);
		}

		public void AddPadding(int alignment = 2048)
		{
			Stream.AddPadding(alignment);
		}

		public void AddPadding(byte value, int alignment = 2048)
		{
			Stream.AddPadding(value, alignment);
		}

		public void Write(byte[] data)
		{
			Stream.Write(data);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public abstract void Write<T>(T[] structure) where T : unmanaged;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public abstract void Write<T>(T structure) where T : unmanaged;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public byte[] ToArray()
		{
			return Stream.ToArray();
		}

		[ExcludeFromCodeCoverage]
		public abstract void WriteInt16(short data);

		[ExcludeFromCodeCoverage]
		public abstract void WriteUInt16(ushort data);

		[ExcludeFromCodeCoverage]
		public abstract void WriteInt32(int data);

		[ExcludeFromCodeCoverage]
		public abstract void WriteUInt32(uint data);

		[ExcludeFromCodeCoverage]
		public abstract void WriteInt64(long data);

		[ExcludeFromCodeCoverage]
		public abstract void WriteUInt64(ulong data);

		[ExcludeFromCodeCoverage]
		public abstract void WriteSingle(float data);

		[ExcludeFromCodeCoverage]
		public abstract void WriteDouble(double data);
	}
	public class LittleEndianMemoryStream : EndianMemoryStream
	{
		public LittleEndianMemoryStream(ExtendedMemoryStream stream)
			: base(stream)
		{
		}

		public LittleEndianMemoryStream(ExtendedMemoryStream stream, bool disposeUnderlyingStream = true)
			: base(stream, disposeUnderlyingStream)
		{
		}

		public override void Write<T>(T[] structure)
		{
			base.Stream.Write(structure);
		}

		public override void Write<T>(T structure)
		{
			base.Stream.Write(ref structure);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Write<T>(T[] structure, bool marshalStructure)
		{
			base.Stream.Write(structure, marshalStructure);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Write<T>(T structure, bool marshalStructure)
		{
			base.Stream.Write(ref structure, marshalStructure);
		}

		[ExcludeFromCodeCoverage]
		public override void WriteInt16(short data)
		{
			base.Stream.Write(data);
		}

		[ExcludeFromCodeCoverage]
		public override void WriteUInt16(ushort data)
		{
			base.Stream.Write(data);
		}

		[ExcludeFromCodeCoverage]
		public override void WriteInt32(int data)
		{
			base.Stream.Write(data);
		}

		[ExcludeFromCodeCoverage]
		public override void WriteUInt32(uint data)
		{
			base.Stream.Write(data);
		}

		[ExcludeFromCodeCoverage]
		public override void WriteInt64(long data)
		{
			base.Stream.Write(data);
		}

		[ExcludeFromCodeCoverage]
		public override void WriteUInt64(ulong data)
		{
			base.Stream.Write(data);
		}

		[ExcludeFromCodeCoverage]
		public override void WriteSingle(float data)
		{
			base.Stream.Write(data);
		}

		[ExcludeFromCodeCoverage]
		public override void WriteDouble(double data)
		{
			base.Stream.Write(data);
		}
	}
}
namespace Reloaded.Memory.Streams.Readers
{
	public class BigEndianStreamReader : EndianStreamReader
	{
		public BigEndianStreamReader(BufferedStreamReader streamReader)
			: base(streamReader)
		{
		}

		public BigEndianStreamReader(BufferedStreamReader streamReader, bool disposeUnderlyingStream = true)
			: base(streamReader, disposeUnderlyingStream)
		{
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public override void Read<T>(out T value)
		{
			base.Reader.ReadBigEndianPrimitive(out value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public override T Read<T>()
		{
			return base.Reader.ReadBigEndianPrimitive<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public override void Peek<T>(out T value)
		{
			base.Reader.PeekBigEndianPrimitive(out value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public override T Peek<T>()
		{
			return base.Reader.PeekBigEndianPrimitive<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void ReadStruct<T>(out T value) where T : unmanaged, IEndianReversible
		{
			base.Reader.ReadBigEndianStruct<T>(out value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public T ReadStruct<T>() where T : unmanaged, IEndianReversible
		{
			return base.Reader.ReadBigEndianStruct<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void PeekStruct<T>(out T value) where T : unmanaged, IEndianReversible
		{
			base.Reader.PeekBigEndianStruct<T>(out value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public T PeekStruct<T>() where T : unmanaged, IEndianReversible
		{
			return base.Reader.PeekBigEndianStruct<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Read(out short value)
		{
			value = base.Reader.ReadBigEndianPrimitiveInt16();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override short ReadInt16()
		{
			return base.Reader.ReadBigEndianPrimitiveInt16();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Peek(out short value)
		{
			value = base.Reader.PeekBigEndianPrimitiveInt16();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override short PeekInt16()
		{
			return base.Reader.PeekBigEndianPrimitiveInt16();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Read(out ushort value)
		{
			value = base.Reader.ReadBigEndianPrimitiveUInt16();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override ushort ReadUInt16()
		{
			return base.Reader.ReadBigEndianPrimitiveUInt16();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Peek(out ushort value)
		{
			value = base.Reader.PeekBigEndianPrimitiveUInt16();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override ushort PeekUInt16()
		{
			return base.Reader.PeekBigEndianPrimitiveUInt16();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Read(out int value)
		{
			value = base.Reader.ReadBigEndianPrimitiveInt32();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override int ReadInt32()
		{
			return base.Reader.ReadBigEndianPrimitiveInt32();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Peek(out int value)
		{
			value = base.Reader.PeekBigEndianPrimitiveInt32();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override int PeekInt32()
		{
			return base.Reader.PeekBigEndianPrimitiveInt32();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Read(out uint value)
		{
			value = base.Reader.ReadBigEndianPrimitiveUInt32();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override uint ReadUInt32()
		{
			return base.Reader.ReadBigEndianPrimitiveUInt32();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Peek(out uint value)
		{
			value = base.Reader.PeekBigEndianPrimitiveUInt32();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override uint PeekUInt32()
		{
			return base.Reader.PeekBigEndianPrimitiveUInt32();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Read(out long value)
		{
			value = base.Reader.ReadBigEndianPrimitiveInt64();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override long ReadInt64()
		{
			return base.Reader.ReadBigEndianPrimitiveInt64();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Peek(out long value)
		{
			value = base.Reader.PeekBigEndianPrimitiveInt64();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override long PeekInt64()
		{
			return base.Reader.PeekBigEndianPrimitiveInt64();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Read(out ulong value)
		{
			value = base.Reader.ReadBigEndianPrimitiveUInt64();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override ulong ReadUInt64()
		{
			return base.Reader.ReadBigEndianPrimitiveUInt64();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Peek(out ulong value)
		{
			value = base.Reader.PeekBigEndianPrimitiveUInt64();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override ulong PeekUInt64()
		{
			return base.Reader.PeekBigEndianPrimitiveUInt64();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Read(out float value)
		{
			value = base.Reader.ReadBigEndianPrimitiveSingle();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override float ReadSingle()
		{
			return base.Reader.ReadBigEndianPrimitiveSingle();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Peek(out float value)
		{
			value = base.Reader.PeekBigEndianPrimitiveSingle();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override float PeekSingle()
		{
			return base.Reader.PeekBigEndianPrimitiveSingle();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Read(out double value)
		{
			value = base.Reader.ReadBigEndianPrimitiveDouble();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override double ReadDouble()
		{
			return base.Reader.ReadBigEndianPrimitiveDouble();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Peek(out double value)
		{
			value = base.Reader.PeekBigEndianPrimitiveDouble();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override double PeekDouble()
		{
			return base.Reader.PeekBigEndianPrimitiveDouble();
		}
	}
	public abstract class EndianStreamReader : IDisposable
	{
		public BufferedStreamReader Reader { get; private set; }

		public bool DisposeUnderlyingStream { get; private set; } = true;


		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public Stream BaseStream()
		{
			return Reader.BaseStream();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public int BufferBytesAvailable()
		{
			return Reader.BufferBytesAvailable();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public int CurrentBufferSize()
		{
			return Reader.CurrentBufferSize();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public long Position()
		{
			return Reader.Position();
		}

		protected EndianStreamReader(BufferedStreamReader streamReader)
		{
			Reader = streamReader;
		}

		protected EndianStreamReader(BufferedStreamReader streamReader, bool disposeUnderlyingStream)
		{
			Reader = streamReader;
			DisposeUnderlyingStream = disposeUnderlyingStream;
		}

		~EndianStreamReader()
		{
			Dispose();
		}

		public void Dispose()
		{
			if (DisposeUnderlyingStream)
			{
				Reader?.Dispose();
			}
			GC.SuppressFinalize(this);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public abstract void Read<T>(out T value) where T : unmanaged;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public abstract T Read<T>() where T : unmanaged;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public abstract void Peek<T>(out T value) where T : unmanaged;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public abstract T Peek<T>() where T : unmanaged;

		public void Seek(long offset, SeekOrigin origin)
		{
			Reader.Seek(offset, origin);
		}

		public byte[] ReadBytes(long offset, int count)
		{
			return Reader.ReadBytes(offset, count);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool CanRead(int size)
		{
			return Reader.CanRead(size);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract void Read(out short value);

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract short ReadInt16();

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract void Peek(out short value);

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract short PeekInt16();

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract void Read(out ushort value);

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract ushort ReadUInt16();

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract void Peek(out ushort value);

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract ushort PeekUInt16();

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract void Read(out int value);

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract int ReadInt32();

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract void Peek(out int value);

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract int PeekInt32();

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract void Read(out uint value);

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract uint ReadUInt32();

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract void Peek(out uint value);

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract uint PeekUInt32();

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract void Read(out long value);

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract long ReadInt64();

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract void Peek(out long value);

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract long PeekInt64();

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract void Read(out ulong value);

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract ulong ReadUInt64();

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract void Peek(out ulong value);

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract ulong PeekUInt64();

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract void Read(out float value);

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract float ReadSingle();

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract void Peek(out float value);

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract float PeekSingle();

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract void Read(out double value);

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract double ReadDouble();

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract void Peek(out double value);

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public abstract double PeekDouble();
	}
	public class LittleEndianStreamReader : EndianStreamReader
	{
		public LittleEndianStreamReader(BufferedStreamReader streamReader)
			: base(streamReader)
		{
		}

		public LittleEndianStreamReader(BufferedStreamReader streamReader, bool disposeUnderlyingStream = true)
			: base(streamReader, disposeUnderlyingStream)
		{
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public override void Read<T>(out T value)
		{
			base.Reader.Read<T>(out value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public override T Read<T>()
		{
			return base.Reader.Read<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public override void Peek<T>(out T value)
		{
			base.Reader.Peek<T>(out value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public override T Peek<T>()
		{
			return base.Reader.Peek<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Read<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(out T value, bool marshal)
		{
			base.Reader.Read<T>(out value, marshal);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public T Read<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(bool marshal)
		{
			return base.Reader.Read<T>(marshal);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Peek<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(out T value, bool marshal)
		{
			base.Reader.Peek<T>(out value, marshal);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public T Peek<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(bool marshal)
		{
			return base.Reader.Peek<T>(marshal);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Read(out short value)
		{
			value = base.Reader.Read<short>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override short ReadInt16()
		{
			return base.Reader.Read<short>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Peek(out short value)
		{
			value = base.Reader.Peek<short>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override short PeekInt16()
		{
			return base.Reader.Peek<short>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Read(out ushort value)
		{
			value = base.Reader.Read<ushort>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override ushort ReadUInt16()
		{
			return base.Reader.Read<ushort>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Peek(out ushort value)
		{
			value = base.Reader.Peek<ushort>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override ushort PeekUInt16()
		{
			return base.Reader.Peek<ushort>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Read(out int value)
		{
			value = base.Reader.Read<int>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override int ReadInt32()
		{
			return base.Reader.Read<int>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Peek(out int value)
		{
			value = base.Reader.Peek<int>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override int PeekInt32()
		{
			return base.Reader.Peek<int>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Read(out uint value)
		{
			value = base.Reader.Read<uint>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override uint ReadUInt32()
		{
			return base.Reader.Read<uint>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Peek(out uint value)
		{
			value = base.Reader.Peek<uint>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override uint PeekUInt32()
		{
			return base.Reader.Peek<uint>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Read(out long value)
		{
			value = base.Reader.Read<long>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override long ReadInt64()
		{
			return base.Reader.Read<long>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Peek(out long value)
		{
			value = base.Reader.Peek<long>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override long PeekInt64()
		{
			return base.Reader.Peek<long>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Read(out ulong value)
		{
			value = base.Reader.Read<ulong>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override ulong ReadUInt64()
		{
			return base.Reader.Read<ulong>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Peek(out ulong value)
		{
			value = base.Reader.Peek<ulong>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override ulong PeekUInt64()
		{
			return base.Reader.Peek<ulong>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Read(out float value)
		{
			value = base.Reader.Read<float>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override float ReadSingle()
		{
			return base.Reader.Read<float>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Peek(out float value)
		{
			value = base.Reader.Peek<float>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override float PeekSingle()
		{
			return base.Reader.Peek<float>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Read(out double value)
		{
			value = base.Reader.Read<double>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override double ReadDouble()
		{
			return base.Reader.Read<double>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override void Peek(out double value)
		{
			value = base.Reader.Peek<double>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public override double PeekDouble()
		{
			return base.Reader.Peek<double>();
		}
	}
}
namespace Reloaded.Memory.Sources
{
	public class ExternalMemory : IMemory
	{
		private static Memory _localMemory = new Memory();

		private readonly IntPtr _processHandle;

		public ExternalMemory(IntPtr processHandle)
		{
			_processHandle = processHandle;
		}

		public ExternalMemory(Process process)
			: this(process.Handle)
		{
		}

		public unsafe void Read<T>(nuint memoryAddress, out T value) where T : unmanaged
		{
			int size = Struct.GetSize<T>();
			fixed (byte* ptr = GC.AllocateUninitializedArray<byte>(size))
			{
				if (!Reloaded.Memory.Kernel32.Kernel32.ReadProcessMemory(_processHandle, memoryAddress, (UIntPtr)ptr, (UIntPtr)(ulong)size, out var _))
				{
					throw new MemoryException($"ReadProcessMemory failed to read {size} bytes of memory from {memoryAddress}");
				}
				_localMemory.Read<T>((nuint)ptr, out value);
			}
		}

		public unsafe void Read<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(nuint memoryAddress, out T value, bool marshal)
		{
			int size = Struct.GetSize<T>(marshal);
			fixed (byte* ptr = GC.AllocateUninitializedArray<byte>(size))
			{
				if (!Reloaded.Memory.Kernel32.Kernel32.ReadProcessMemory(_processHandle, memoryAddress, (UIntPtr)ptr, (UIntPtr)(ulong)size, out var _))
				{
					throw new MemoryException($"ReadProcessMemory failed to read {size} bytes of memory from {memoryAddress}");
				}
				_localMemory.Read<T>((nuint)ptr, out value, marshal);
			}
		}

		public unsafe void ReadRaw(nuint memoryAddress, out byte[] value, int length)
		{
			value = GC.AllocateUninitializedArray<byte>(length);
			fixed (byte* ptr = value)
			{
				if (!Reloaded.Memory.Kernel32.Kernel32.ReadProcessMemory(_processHandle, memoryAddress, (UIntPtr)ptr, (UIntPtr)(ulong)value.Length, out var _))
				{
					throw new MemoryException($"ReadProcessMemory failed to read {value.Length} bytes of memory from {memoryAddress}");
				}
			}
		}

		public unsafe void Write<T>(nuint memoryAddress, ref T item) where T : unmanaged
		{
			byte[] bytes = Struct.GetBytes(ref item);
			fixed (byte* ptr = bytes)
			{
				if (!Reloaded.Memory.Kernel32.Kernel32.WriteProcessMemory(_processHandle, memoryAddress, (UIntPtr)ptr, (UIntPtr)(ulong)bytes.Length, out var _))
				{
					throw new MemoryException($"WriteProcessMemory failed to write {bytes.Length} bytes of memory to {memoryAddress}");
				}
			}
		}

		public unsafe void Write<T>(nuint memoryAddress, ref T item, bool marshal)
		{
			byte[] bytes = Struct.GetBytes(ref item, marshal);
			fixed (byte* ptr = bytes)
			{
				if (!Reloaded.Memory.Kernel32.Kernel32.WriteProcessMemory(_processHandle, memoryAddress, (UIntPtr)ptr, (UIntPtr)(ulong)bytes.Length, out var _))
				{
					throw new MemoryException($"WriteProcessMemory failed to write {bytes.Length} bytes of memory to {memoryAddress}");
				}
			}
		}

		public unsafe void WriteRaw(nuint memoryAddress, byte[] data)
		{
			fixed (byte* ptr = data)
			{
				if (!Reloaded.Memory.Kernel32.Kernel32.WriteProcessMemory(_processHandle, memoryAddress, (UIntPtr)ptr, (UIntPtr)(ulong)data.Length, out var _))
				{
					throw new MemoryException($"WriteProcessMemory failed to write {data.Length} bytes of memory to {memoryAddress}");
				}
			}
		}

		public nuint Allocate(int length)
		{
			nuint num = Reloaded.Memory.Kernel32.Kernel32.VirtualAllocEx(_processHandle, UIntPtr.Zero, (UIntPtr)(ulong)length, Reloaded.Memory.Kernel32.Kernel32.MEM_ALLOCATION_TYPE.MEM_COMMIT | Reloaded.Memory.Kernel32.Kernel32.MEM_ALLOCATION_TYPE.MEM_RESERVE, Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION.PAGE_EXECUTE_READWRITE);
			if (num == 0)
			{
				throw new MemoryAllocationException($"Failed to allocate memory in external process: {length} bytes, {Marshal.GetLastWin32Error()} last error.");
			}
			return num;
		}

		public bool Free(nuint address)
		{
			return Reloaded.Memory.Kernel32.Kernel32.VirtualFreeEx(_processHandle, address, (UIntPtr)0uL, Reloaded.Memory.Kernel32.Kernel32.MEM_ALLOCATION_TYPE.MEM_RELEASE);
		}

		public Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION ChangePermission(nuint memoryAddress, int size, Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION newPermissions)
		{
			if (!Reloaded.Memory.Kernel32.Kernel32.VirtualProtectEx(_processHandle, memoryAddress, (UIntPtr)(ulong)size, newPermissions, out var lpflOldProtect))
			{
				throw new MemoryPermissionException($"Unable to change permissions for the following memory address {memoryAddress} of size {size} and permission {newPermissions.ToString()}");
			}
			return lpflOldProtect;
		}
	}
	public interface IMemory
	{
		void Read<T>(nuint memoryAddress, out T value) where T : unmanaged;

		void Read<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(nuint memoryAddress, out T value, bool marshal);

		void ReadRaw(nuint memoryAddress, out byte[] value, int length);

		void Write<T>(nuint memoryAddress, ref T item) where T : unmanaged;

		void Write<T>(nuint memoryAddress, ref T item, bool marshal);

		void WriteRaw(nuint memoryAddress, byte[] data);

		nuint Allocate(int length);

		bool Free(nuint address);

		Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION ChangePermission(nuint memoryAddress, int size, Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION newPermissions);
	}
	public class Memory : IMemory
	{
		public static Memory CurrentProcess => Instance;

		public static Memory Instance { get; } = new Memory();


		public unsafe void Read<T>(nuint memoryAddress, out T value) where T : unmanaged
		{
			value = Unsafe.Read<T>((void*)memoryAddress);
		}

		public unsafe void Read<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(nuint memoryAddress, out T value, bool marshal)
		{
			value = (T)(marshal ? ((object)Marshal.PtrToStructure<T>((nint)memoryAddress)) : ((object)Unsafe.Read<T>((void*)memoryAddress)));
		}

		public void ReadRaw(nuint memoryAddress, out byte[] value, int length)
		{
			value = GC.AllocateUninitializedArray<byte>(length);
			Marshal.Copy((nint)memoryAddress, value, 0, value.Length);
		}

		public unsafe void Write<T>(nuint memoryAddress, ref T item) where T : unmanaged
		{
			Unsafe.Write((void*)memoryAddress, item);
		}

		public unsafe void Write<T>(nuint memoryAddress, ref T item, bool marshal)
		{
			if (marshal)
			{
				Marshal.StructureToPtr(item, (nint)memoryAddress, fDeleteOld: false);
			}
			else
			{
				Unsafe.Write((void*)memoryAddress, item);
			}
		}

		public void WriteRaw(nuint memoryAddress, byte[] data)
		{
			Marshal.Copy(data, 0, (nint)memoryAddress, data.Length);
		}

		public nuint Allocate(int length)
		{
			nuint num = Reloaded.Memory.Kernel32.Kernel32.VirtualAlloc(UIntPtr.Zero, (UIntPtr)(ulong)length, Reloaded.Memory.Kernel32.Kernel32.MEM_ALLOCATION_TYPE.MEM_COMMIT | Reloaded.Memory.Kernel32.Kernel32.MEM_ALLOCATION_TYPE.MEM_RESERVE, Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION.PAGE_EXECUTE_READWRITE);
			if (num == 0)
			{
				throw new MemoryAllocationException($"Failed to allocate memory in current process: {length} bytes, {Marshal.GetLastWin32Error()} last error.");
			}
			return num;
		}

		public bool Free(nuint address)
		{
			Reloaded.Memory.Kernel32.Kernel32.VirtualFree(address, (UIntPtr)0uL, Reloaded.Memory.Kernel32.Kernel32.MEM_ALLOCATION_TYPE.MEM_RELEASE);
			return true;
		}

		public Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION ChangePermission(nuint memoryAddress, int size, Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION newPermissions)
		{
			if (!Reloaded.Memory.Kernel32.Kernel32.VirtualProtect(memoryAddress, (UIntPtr)(ulong)size, newPermissions, out var lpflOldProtect))
			{
				throw new MemoryPermissionException($"Unable to change permissions for the following memory address {memoryAddress} of size {size} and permission {newPermissions}");
			}
			return lpflOldProtect;
		}
	}
	public static class MemoryExtensions
	{
		public delegate void ReadFunction<T>(nuint memoryAddress, out T value, bool marshal);

		public delegate void WriteFunction<T>(nuint memoryAddress, ref T item, bool marshal);

		public static void Read<TMemory, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(this TMemory memory, nuint memoryAddress, out T[] value, int arrayLength, bool marshal = false) where TMemory : IMemory
		{
			IMemory source = Struct.Source;
			Struct.Source = memory;
			value = GC.AllocateUninitializedArray<T>(arrayLength);
			StructArray.FromPtr<T>(memoryAddress, out value, arrayLength, marshal);
			Struct.Source = source;
		}

		public static void SafeRead<TMemory, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(this TMemory memory, nuint memoryAddress, out T value, bool marshal) where TMemory : IMemory
		{
			int size = Struct.GetSize<T>(marshal);
			Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION newPermissions = memory.ChangePermission(memoryAddress, size, Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION.PAGE_EXECUTE_READWRITE);
			memory.Read<T>(memoryAddress, out value, marshal);
			memory.ChangePermission(memoryAddress, size, newPermissions);
		}

		public static void SafeRead<TMemory, T>(this TMemory memory, nuint memoryAddress, out T value) where TMemory : IMemory where T : unmanaged
		{
			int size = Struct.GetSize<T>();
			Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION newPermissions = memory.ChangePermission(memoryAddress, size, Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION.PAGE_EXECUTE_READWRITE);
			memory.Read<T>(memoryAddress, out value);
			memory.ChangePermission(memoryAddress, size, newPermissions);
		}

		public static void SafeReadRaw<TMemory>(this TMemory memory, nuint memoryAddress, out byte[] value, int length) where TMemory : IMemory
		{
			Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION newPermissions = memory.ChangePermission(memoryAddress, length, Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION.PAGE_EXECUTE_READWRITE);
			value = GC.AllocateUninitializedArray<byte>(length);
			memory.ReadRaw(memoryAddress, out value, length);
			memory.ChangePermission(memoryAddress, length, newPermissions);
		}

		public static void SafeRead<TMemory, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(this TMemory memory, nuint memoryAddress, out T[] value, int arrayLength, bool marshal = false) where TMemory : IMemory
		{
			int size = StructArray.GetSize<T>(arrayLength, marshal);
			Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION newPermissions = memory.ChangePermission(memoryAddress, size, Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION.PAGE_EXECUTE_READWRITE);
			memory.Read<TMemory, T>(memoryAddress, out value, arrayLength, marshal);
			memory.ChangePermission(memoryAddress, size, newPermissions);
		}

		public static void Write<TMemory, T>(this TMemory memory, nuint memoryAddress, T[] items, bool marshal) where TMemory : IMemory
		{
			IMemory source = Struct.Source;
			Struct.Source = memory;
			StructArray.ToPtr(memoryAddress, items, marshal);
			Struct.Source = source;
		}

		public static void Write<TMemory, T>(this TMemory memory, nuint memoryAddress, T[] items) where TMemory : IMemory
		{
			memory.Write(memoryAddress, items, marshal: false);
		}

		public static void SafeWrite<TMemory, T>(this TMemory memory, nuint memoryAddress, ref T item, bool marshal) where TMemory : IMemory
		{
			int size = Struct.GetSize<T>(marshal);
			Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION newPermissions = memory.ChangePermission(memoryAddress, size, Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION.PAGE_EXECUTE_READWRITE);
			memory.Write(memoryAddress, ref item, marshal);
			memory.ChangePermission(memoryAddress, size, newPermissions);
		}

		public static void SafeWrite<TMemory, T>(this TMemory memory, nuint memoryAddress, ref T item) where TMemory : IMemory where T : unmanaged
		{
			int size = Struct.GetSize<T>();
			Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION newPermissions = memory.ChangePermission(memoryAddress, size, Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION.PAGE_EXECUTE_READWRITE);
			memory.Write(memoryAddress, ref item);
			memory.ChangePermission(memoryAddress, size, newPermissions);
		}

		public static void SafeWriteRaw<TMemory>(this TMemory memory, nuint memoryAddress, byte[] data) where TMemory : IMemory
		{
			Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION newPermissions = memory.ChangePermission(memoryAddress, data.Length, Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION.PAGE_EXECUTE_READWRITE);
			memory.WriteRaw(memoryAddress, data);
			memory.ChangePermission(memoryAddress, data.Length, newPermissions);
		}

		public static void SafeWrite<TMemory, T>(this TMemory memory, nuint memoryAddress, T[] items, bool marshal = false) where TMemory : IMemory
		{
			int size = StructArray.GetSize<T>(items.Length, marshal);
			Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION newPermissions = memory.ChangePermission(memoryAddress, size, Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION.PAGE_EXECUTE_READWRITE);
			memory.Write(memoryAddress, items, marshal);
			memory.ChangePermission(memoryAddress, size, newPermissions);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public static T Read<TMemory, T>(this TMemory memory, int memoryAddress) where TMemory : IMemory where T : unmanaged
		{
			memory.Read<T>((nuint)memoryAddress, out var value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public static T Read<TMemory, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(this TMemory memory, int memoryAddress, bool marshal) where TMemory : IMemory
		{
			memory.Read<T>((nuint)memoryAddress, out var value, marshal);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public static T Read<TMemory, T>(this TMemory memory, long memoryAddress) where TMemory : IMemory where T : unmanaged
		{
			memory.Read<T>((nuint)memoryAddress, out var value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public static T Read<TMemory, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(this TMemory memory, long memoryAddress, bool marshal) where TMemory : IMemory
		{
			memory.Read<T>((nuint)memoryAddress, out var value, marshal);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public static T Read<TMemory, T>(this TMemory memory, nuint memoryAddress) where TMemory : IMemory where T : unmanaged
		{
			memory.Read<T>(memoryAddress, out var value);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public static T Read<TMemory, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(this TMemory memory, nuint memoryAddress, bool marshal) where TMemory : IMemory
		{
			memory.Read<T>(memoryAddress, out var value, marshal);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public static void Write<TMemory, T>(this TMemory memory, int memoryAddress, T item) where TMemory : IMemory where T : unmanaged
		{
			memory.Write((nuint)memoryAddress, ref item);
		}

		[ExcludeFromCodeCoverage]
		public static void Write<TMemory, T>(this TMemory memory, int memoryAddress, T item, bool marshal) where TMemory : IMemory
		{
			memory.Write((nuint)memoryAddress, ref item, marshal);
		}

		[ExcludeFromCodeCoverage]
		public static void SafeWrite<TMemory, T>(this TMemory memory, int memoryAddress, T item, bool marshal = false) where TMemory : IMemory
		{
			memory.SafeWrite((nuint)memoryAddress, ref item, marshal);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public static void Write<TMemory, T>(this TMemory memory, long memoryAddress, T item) where TMemory : IMemory where T : unmanaged
		{
			memory.Write((nuint)memoryAddress, ref item);
		}

		[ExcludeFromCodeCoverage]
		public static void Write<TMemory, T>(this TMemory memory, long memoryAddress, T item, bool marshal) where TMemory : IMemory
		{
			memory.Write((nuint)memoryAddress, ref item, marshal);
		}

		[ExcludeFromCodeCoverage]
		public static void SafeWrite<TMemory, T>(this TMemory memory, long memoryAddress, T item, bool marshal = false) where TMemory : IMemory
		{
			memory.SafeWrite((nuint)memoryAddress, ref item, marshal);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public static void Write<TMemory, T>(this TMemory memory, nuint memoryAddress, T item) where TMemory : IMemory where T : unmanaged
		{
			memory.Write(memoryAddress, ref item);
		}

		[ExcludeFromCodeCoverage]
		public static void Write<TMemory, T>(this TMemory memory, nuint memoryAddress, T item, bool marshal) where TMemory : IMemory
		{
			memory.Write(memoryAddress, ref item, marshal);
		}

		[ExcludeFromCodeCoverage]
		public static void SafeWrite<TMemory, T>(this TMemory memory, nuint memoryAddress, T item, bool marshal = false) where TMemory : IMemory
		{
			memory.SafeWrite(memoryAddress, ref item, marshal);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[ExcludeFromCodeCoverage]
		public static Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION ChangePermission<TMemory, T>(this TMemory memory, nuint memoryAddress, ref T baseElement, Reloaded.Memory.Kernel32.Kernel32.MEM_PROTECTION newPermissions, bool marshalElement = false) where TMemory : IMemory
		{
			return memory.ChangePermission(memoryAddress, Struct.GetSize<T>(marshalElement), newPermissions);
		}
	}
}
namespace Reloaded.Memory.Pointers
{
	public struct ArrayPtr<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] TStruct> : IArrayPtr<TStruct>
	{
		public unsafe void* Pointer { get; set; }

		public bool MarshalElements { get; set; }

		public IMemory Source { get; set; }

		public int ElementSize => Struct.GetSize<TStruct>(MarshalElements);

		public TStruct this[int index]
		{
			get
			{
				Get(out var value, index);
				return value;
			}
			set
			{
				Set(ref value, index);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void Get(out TStruct value, int index)
		{
			Source.Read<TStruct>((nuint)GetPointerToElement(index), out value, MarshalElements);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void Set(ref TStruct value, int index)
		{
			Source.Write((nuint)GetPointerToElement(index), ref value, MarshalElements);
		}

		public unsafe ArrayPtr(nuint address, bool marshalElements = false, IMemory source = null)
		{
			Pointer = (void*)address;
			MarshalElements = marshalElements;
			Source = source ?? Reloaded.Memory.Sources.Memory.CurrentProcess;
		}

		public unsafe void* GetPointerToElement(int index)
		{
			return (void*)((ulong)Pointer + (ulong)(index * ElementSize));
		}
	}
	public struct BlittablePointer<T> where T : unmanaged
	{
		public unsafe T* Pointer { get; set; }

		public unsafe BlittablePointer(T* pointer)
		{
			Pointer = pointer;
		}

		public RefPointer<T> AsRefPointer()
		{
			return this;
		}

		public unsafe ref T AsReference()
		{
			return ref Unsafe.AsRef<T>(Pointer);
		}

		public unsafe static implicit operator BlittablePointer<T>(T* operand)
		{
			return new BlittablePointer<T>(operand);
		}

		public unsafe static implicit operator T*(BlittablePointer<T> operand)
		{
			return operand.Pointer;
		}
	}
	public struct FixedArrayPtr<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] TStruct> : IEnumerable<TStruct>, IEnumerable, IArrayPtr<TStruct>
	{
		private class FixedArrayPtrEnumerator : IEnumerator<TStruct>, IEnumerator, IDisposable
		{
			private readonly FixedArrayPtr<TStruct> _arrayPtr;

			private int _currentIndex = -1;

			object IEnumerator.Current => Current;

			public TStruct Current
			{
				get
				{
					_arrayPtr.Get(out var value, _currentIndex);
					return value;
				}
			}

			public FixedArrayPtrEnumerator(FixedArrayPtr<TStruct> parentArrayPtr)
			{
				_arrayPtr = parentArrayPtr;
			}

			public bool MoveNext()
			{
				_currentIndex++;
				return _currentIndex < _arrayPtr.Count;
			}

			[ExcludeFromCodeCoverage]
			public void Reset()
			{
				_currentIndex = -1;
			}

			public void Dispose()
			{
			}
		}

		public unsafe void* Pointer { get; set; }

		public bool MarshalElements { get; set; }

		public IMemory Source { get; set; }

		public int ElementSize => Struct.GetSize<TStruct>(MarshalElements);

		public int Count { get; set; }

		public int ArraySize => Struct.GetSize<TStruct>(MarshalElements) * Count;

		public TStruct this[int index]
		{
			get
			{
				Get(out var value, index);
				return value;
			}
			set
			{
				Set(ref value, index);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void Get(out TStruct value, int index)
		{
			Source.Read<TStruct>((nuint)GetPointerToElement(index), out value, MarshalElements);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void Set(ref TStruct value, int index)
		{
			Source.Write((nuint)GetPointerToElement(index), ref value, MarshalElements);
		}

		public unsafe FixedArrayPtr(nuint address, int count, bool marshalElements = false, IMemory source = null)
		{
			Pointer = (void*)address;
			Count = count;
			MarshalElements = marshalElements;
			Source = source ?? Reloaded.Memory.Sources.Memory.CurrentProcess;
		}

		public bool Contains(TStruct item)
		{
			return Contains(ref item);
		}

		public bool Contains(ref TStruct item)
		{
			return IndexOf(ref item) != -1;
		}

		public int IndexOf(TStruct item)
		{
			return IndexOf(ref item);
		}

		public int IndexOf(ref TStruct item)
		{
			for (int i = 0; i < Count; i++)
			{
				Get(out var value, i);
				if (value.Equals(item))
				{
					return i;
				}
			}
			return -1;
		}

		public void CopyFrom(TStruct[] sourceArray, int length, int sourceIndex = 0, int destinationIndex = 0)
		{
			int num = Count - destinationIndex;
			if (length > num)
			{
				throw new ArgumentException($"There is insufficient space in the {"FixedArrayPtr"} to copy {length} elements. (Length: {length}, Available Elements: {num})");
			}
			int num2 = sourceArray.Length - sourceIndex;
			if (length > num2)
			{
				throw new ArgumentException($"There is insufficient space in the {"sourceArray"} to copy {length} elements. (Length: {length}, Available Elements: {num2})");
			}
			for (int i = 0; i < length; i++)
			{
				Set(ref sourceArray[sourceIndex + i], destinationIndex + i);
			}
		}

		public void CopyTo(TStruct[] destinationArray, int length, int sourceIndex = 0, int destinationIndex = 0)
		{
			int num = destinationArray.Length - destinationIndex;
			if (length > num)
			{
				throw new ArgumentException($"There is insufficient space in the {"destinationArray"} to copy {length} elements. (Length: {length}, Available Elements: {num})");
			}
			int num2 = Count - sourceIndex;
			if (length > num2)
			{
				throw new ArgumentException($"There are not enough elements in the current {"FixedArrayPtr"}. (Length: {length}, Available Elements: {num2})");
			}
			for (int i = 0; i < length; i++)
			{
				Get(out var value, sourceIndex + i);
				destinationArray[i + destinationIndex] = value;
			}
		}

		public unsafe void* GetPointerToElement(int index)
		{
			if (index >= Count)
			{
				return (void*)(-1);
			}
			return (void*)((ulong)Pointer + (ulong)(index * ElementSize));
		}

		public IEnumerator<TStruct> GetEnumerator()
		{
			return new FixedArrayPtrEnumerator(this);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
	public interface IArrayPtr<TStruct>
	{
		int ElementSize { get; }

		bool MarshalElements { get; set; }

		unsafe void* Pointer { get; set; }

		IMemory Source { get; set; }

		TStruct this[int index] { get; set; }

		unsafe void* GetPointerToElement(int index);

		void Get(out TStruct value, int index);

		void Set(ref TStruct value, int index);
	}
	public struct Pointer<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] TStruct>
	{
		public unsafe void* Address { get; set; }

		public bool MarshalElements { get; set; }

		public IMemory Source { get; set; }

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe TStruct GetValue()
		{
			Source.Read<TStruct>((nuint)Address, out var value, MarshalElements);
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void GetValue(out TStruct value)
		{
			Source.Read<TStruct>((nuint)Address, out value, MarshalElements);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void SetValue(TStruct value)
		{
			Source.Write((nuint)Address, ref value, MarshalElements);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void SetValue(ref TStruct value)
		{
			Source.Write((nuint)Address, ref value, MarshalElements);
		}

		public unsafe Pointer(nuint address, bool marshalElements = false, IMemory memorySource = null)
		{
			Address = (void*)address;
			MarshalElements = marshalElements;
			Source = memorySource ?? Reloaded.Memory.Sources.Memory.CurrentProcess;
		}
	}
	public struct RefArrayPtr<TStruct> where TStruct : unmanaged
	{
		public unsafe TStruct* Pointer { get; private set; }

		public unsafe ref TStruct this[int index] => ref RefPointer<TStruct>.Create(Pointer + index);

		public unsafe RefArrayPtr(nuint address)
		{
			Pointer = (TStruct*)address;
		}

		public unsafe RefArrayPtr(TStruct* structPtr)
		{
			Pointer = structPtr;
		}
	}
	public struct RefFixedArrayPtr

GDWeave/core/Reloaded.Memory.Sigscan.Definitions.dll

Decompiled 3 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using Reloaded.Memory.Sigscan.Definitions.Structs;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETCoreApp,Version=v5.0", FrameworkDisplayName = "")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCompany("Sewer56")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("LGPL V3")]
[assembly: AssemblyDescription("Interface definitions for Reloaded.Memory.Sigscan; used for sharing across AssemblyLoadContext(s)")]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: AssemblyInformationalVersion("1.1.1")]
[assembly: AssemblyProduct("Reloaded.Memory.Sigscan.Definitions")]
[assembly: AssemblyTitle("Reloaded.Memory.Sigscan.Definitions")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Reloaded-Project/Reloaded.Memory.SigScan")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.1.0")]
[module: UnverifiableCode]
[module: SkipLocalsInit]
namespace Reloaded.Memory.Sigscan.Definitions
{
	public interface IScanner : IDisposable
	{
		PatternScanResult FindPattern(string pattern);

		PatternScanResult FindPattern(string pattern, int offset);

		PatternScanResult[] FindPatterns(IReadOnlyList<string> patterns, bool loadBalance = false);

		PatternScanResult[] FindPatternsCached(IReadOnlyList<string> patterns, bool loadBalance = false);

		PatternScanResult FindPattern_Avx2(string pattern);

		PatternScanResult FindPattern_Sse2(string pattern);

		PatternScanResult FindPattern_Compiled(string pattern);

		PatternScanResult FindPattern_Simple(string pattern);
	}
	public interface IScannerFactory
	{
		IScanner CreateScanner(byte[] data);

		IScanner CreateScanner(Process process);

		IScanner CreateScanner(Process process, ProcessModule module);

		unsafe IScanner CreateScanner(byte* data, int length);
	}
}
namespace Reloaded.Memory.Sigscan.Definitions.Structs
{
	public struct PatternScanResult
	{
		public int Offset { get; internal set; }

		public bool Found => Offset != -1;

		public PatternScanResult(int offset)
		{
			Offset = offset;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public PatternScanResult AddOffset(int offset)
		{
			return (Offset != -1) ? new PatternScanResult(Offset + offset) : this;
		}

		public bool Equals(PatternScanResult other)
		{
			return Offset == other.Offset;
		}

		public override bool Equals(object obj)
		{
			return obj is PatternScanResult other && Equals(other);
		}

		public override int GetHashCode()
		{
			return Offset;
		}
	}
}

GDWeave/core/Reloaded.Memory.Sigscan.dll

Decompiled 3 days ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Reloaded.Memory.Sigscan.Definitions;
using Reloaded.Memory.Sigscan.Definitions.Structs;
using Reloaded.Memory.Sigscan.Structs;
using Reloaded.Memory.Sigscan.Utility;
using Reloaded.Memory.Sources;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCompany("Sewer56")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("LGPL V3")]
[assembly: AssemblyDescription("Simple high performance byte pattern/PE signature scanner, allowing upwards of 2000MB/s per core on modern hardware.")]
[assembly: AssemblyFileVersion("3.1.6.0")]
[assembly: AssemblyInformationalVersion("3.1.6")]
[assembly: AssemblyProduct("Reloaded.Memory.Sigscan")]
[assembly: AssemblyTitle("Reloaded.Memory.Sigscan")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Reloaded-Project/Reloaded.Memory.SigScan")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("3.1.6.0")]
[module: UnverifiableCode]
[module: SkipLocalsInit]
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.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;
		}
	}
}
namespace Reloaded.Memory.Sigscan
{
	public class Scanner : IScanner, IDisposable
	{
		private static int _currentProcessId = Process.GetCurrentProcess().Id;

		private bool _disposedValue;

		private GCHandle? _gcHandle;

		private unsafe byte* _dataPtr;

		private int _dataLength;

		private const int AvxRegisterLength = 32;

		private const int SseRegisterLength = 16;

		public unsafe Scanner(byte[] data)
		{
			_gcHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
			_dataPtr = (byte*)(void*)_gcHandle.Value.AddrOfPinnedObject();
			_dataLength = data.Length;
		}

		public Scanner(Process process)
			: this(process, process.MainModule)
		{
		}

		public unsafe Scanner(Process process, ProcessModule module)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			if (process.Id == _currentProcessId)
			{
				_dataPtr = (byte*)(void*)module.BaseAddress;
				_dataLength = module.ModuleMemorySize;
				return;
			}
			ExternalMemory val = new ExternalMemory(process);
			Unsafe.SkipInit(out byte[] array);
			val.ReadRaw((UIntPtr)(nuint)(nint)module.BaseAddress, ref array, module.ModuleMemorySize);
			_gcHandle = GCHandle.Alloc(array, GCHandleType.Pinned);
			_dataPtr = (byte*)(void*)_gcHandle.Value.AddrOfPinnedObject();
			_dataLength = array.Length;
		}

		public unsafe Scanner(byte* data, int length)
		{
			_dataPtr = data;
			_dataLength = length;
		}

		~Scanner()
		{
			Dispose(disposing: false);
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!_disposedValue)
			{
				_gcHandle?.Free();
				_disposedValue = true;
			}
		}

		public unsafe PatternScanResult FindPattern(string pattern)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			if (Avx2.IsSupported)
			{
				return FindPatternAvx2(_dataPtr, _dataLength, pattern);
			}
			if (Sse2.IsSupported)
			{
				return FindPatternSse2(_dataPtr, _dataLength, pattern);
			}
			return FindPatternCompiled(_dataPtr, _dataLength, pattern);
		}

		public unsafe PatternScanResult FindPattern(string pattern, int offset)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			PatternScanResult val;
			if (Avx2.IsSupported)
			{
				val = FindPatternAvx2(_dataPtr + offset, _dataLength - offset, pattern);
				return ((PatternScanResult)(ref val)).AddOffset(offset);
			}
			if (Sse2.IsSupported)
			{
				val = FindPatternSse2(_dataPtr + offset, _dataLength - offset, pattern);
				return ((PatternScanResult)(ref val)).AddOffset(offset);
			}
			val = FindPatternCompiled(_dataPtr + offset, _dataLength - offset, pattern);
			return ((PatternScanResult)(ref val)).AddOffset(offset);
		}

		public PatternScanResult[] FindPatterns(IReadOnlyList<string> patterns, bool loadBalance = false)
		{
			PatternScanResult[] results = (PatternScanResult[])(object)new PatternScanResult[patterns.Count];
			if (patterns.Count == 0)
			{
				return results;
			}
			if (loadBalance)
			{
				Parallel.ForEach(Partitioner.Create(patterns.ToArray(), loadBalance: true), delegate(string item, ParallelLoopState _, long index)
				{
					//IL_0010: Unknown result type (might be due to invalid IL or missing references)
					//IL_0015: Unknown result type (might be due to invalid IL or missing references)
					results[index] = FindPattern(item);
				});
			}
			else
			{
				Parallel.ForEach(Partitioner.Create(0, patterns.Count), delegate(Tuple<int, int> tuple)
				{
					//IL_0023: Unknown result type (might be due to invalid IL or missing references)
					//IL_0028: Unknown result type (might be due to invalid IL or missing references)
					for (int i = tuple.Item1; i < tuple.Item2; i++)
					{
						results[i] = FindPattern(patterns[i]);
					}
				});
			}
			return results;
		}

		public PatternScanResult[] FindPatternsCached(IReadOnlyList<string> patterns, bool loadBalance = false)
		{
			PatternScanResult[] results = (PatternScanResult[])(object)new PatternScanResult[patterns.Count];
			if (patterns.Count == 0)
			{
				return results;
			}
			ConcurrentDictionary<string, PatternScanResult> completedPatternCache = new ConcurrentDictionary<string, PatternScanResult>(StringComparer.OrdinalIgnoreCase);
			if (loadBalance)
			{
				Parallel.ForEach(Partitioner.Create(patterns.ToArray(), loadBalance: true), delegate(string item, ParallelLoopState _, long index)
				{
					//IL_001b: Unknown result type (might be due to invalid IL or missing references)
					//IL_001c: Unknown result type (might be due to invalid IL or missing references)
					if (completedPatternCache.TryGetValue(item, out var value2))
					{
						results[index] = value2;
					}
					else
					{
						AddResult(item, (int)index);
					}
				});
			}
			else
			{
				Parallel.ForEach(Partitioner.Create(0, patterns.Count), delegate(Tuple<int, int> tuple)
				{
					//IL_0031: Unknown result type (might be due to invalid IL or missing references)
					//IL_0032: Unknown result type (might be due to invalid IL or missing references)
					for (int i = tuple.Item1; i < tuple.Item2; i++)
					{
						string text = patterns[i];
						if (completedPatternCache.TryGetValue(text, out var value))
						{
							results[i] = value;
						}
						else
						{
							AddResult(text, i);
						}
					}
				});
			}
			return results;
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			void AddResult(string pattern, int index)
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				PatternScanResult val = FindPattern(pattern);
				results[index] = val;
				completedPatternCache[pattern] = val;
			}
		}

		public unsafe PatternScanResult FindPattern_Avx2(string pattern)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			return FindPatternAvx2(_dataPtr, _dataLength, pattern);
		}

		public unsafe PatternScanResult FindPattern_Sse2(string pattern)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			return FindPatternSse2(_dataPtr, _dataLength, pattern);
		}

		public unsafe PatternScanResult FindPattern_Compiled(string pattern)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return FindPatternCompiled(_dataPtr, _dataLength, pattern);
		}

		public unsafe PatternScanResult FindPattern_Simple(string pattern)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return FindPatternSimple(_dataPtr, _dataLength, pattern);
		}

		[SkipLocalsInit]
		public unsafe static PatternScanResult FindPatternAvx2(byte* data, int dataLength, string pattern)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			SimdPatternScanData scanPattern = new SimdPatternScanData(pattern);
			if (scanPattern.Bytes.Length == 1)
			{
				return FindPatternSimple(data, dataLength, pattern);
			}
			Span<ushort> span = BuildMatchIndexes(in scanPattern);
			Vector256<byte>[] array = PadPatternToVector256Avx(in scanPattern);
			int length = span.Length;
			Vector256<byte> left = Vector256.Create(scanPattern.Bytes[scanPattern.LeadingIgnoreCount]);
			int num = dataLength - Math.Max(scanPattern.Bytes.Length, 32);
			int leadingIgnoreCount = scanPattern.LeadingIgnoreCount;
			ref Vector256<byte> source = ref array[0];
			short* ptr = (short*)Unsafe.AsPointer(ref span.GetPinnableReference());
			int num2 = array.Length;
			int num3 = 31;
			byte* ptr2 = data;
			byte* ptr3 = ptr2 + num;
			while (ptr2 < ptr3)
			{
				Vector256<byte> right = Avx.LoadVector256(ptr2);
				Vector256<byte> value = Avx2.CompareEqual(left, right);
				int num4 = Avx2.MoveMask(value);
				if (num4 == 0)
				{
					ptr2 += num3;
				}
				else
				{
					ptr2 += BitOperations.TrailingZeroCount((uint)num4) - leadingIgnoreCount;
					int i = 0;
					int num5 = 0;
					while (true)
					{
						if (num5 < num2)
						{
							int num6 = num5 * 32;
							byte* address = ptr2 + num6 + 1;
							Vector256<byte> right2 = Avx.LoadVector256(address);
							Vector256<byte> left2 = Unsafe.Add(ref source, num5);
							int num7 = Avx2.MoveMask(Avx2.CompareEqual(left2, right2));
							for (; i < length; i++)
							{
								int num8 = ptr[i] - num6;
								if (num8 < 32)
								{
									if (((num7 >> num8) & 1) != 1)
									{
										goto end_IL_0189;
									}
									continue;
								}
								break;
							}
							num5++;
							continue;
						}
						return new PatternScanResult((int)(ptr2 - data));
						continue;
						end_IL_0189:
						break;
					}
				}
				ptr2++;
			}
			int num9 = (int)(ptr2 - data);
			PatternScanResult val = FindPatternSimple(data + num9, dataLength - num9, pattern);
			return ((PatternScanResult)(ref val)).AddOffset(num9);
		}

		private static Vector256<byte>[] PadPatternToVector256Avx(in SimdPatternScanData cbPattern)
		{
			int num = cbPattern.Mask.Length;
			int num2 = (int)Math.Ceiling((float)(num - 1) / 32f);
			Vector256<byte>[] array = new Vector256<byte>[num2];
			ref byte source = ref cbPattern.Bytes[1];
			num--;
			for (int i = 0; i < num2; i++)
			{
				if (i < num2 - 1)
				{
					array[i] = Unsafe.As<byte, Vector256<byte>>(ref Unsafe.Add(ref source, i * 32));
					continue;
				}
				int num3 = i * 32;
				array[i] = Vector256.Create(Unsafe.Add(ref source, num3), (byte)((num3 + 1 < num) ? Unsafe.Add(ref source, num3 + 1) : 0), (byte)((num3 + 2 < num) ? Unsafe.Add(ref source, num3 + 2) : 0), (byte)((num3 + 3 < num) ? Unsafe.Add(ref source, num3 + 3) : 0), (byte)((num3 + 4 < num) ? Unsafe.Add(ref source, num3 + 4) : 0), (byte)((num3 + 5 < num) ? Unsafe.Add(ref source, num3 + 5) : 0), (byte)((num3 + 6 < num) ? Unsafe.Add(ref source, num3 + 6) : 0), (byte)((num3 + 7 < num) ? Unsafe.Add(ref source, num3 + 7) : 0), (byte)((num3 + 8 < num) ? Unsafe.Add(ref source, num3 + 8) : 0), (byte)((num3 + 9 < num) ? Unsafe.Add(ref source, num3 + 9) : 0), (byte)((num3 + 10 < num) ? Unsafe.Add(ref source, num3 + 10) : 0), (byte)((num3 + 11 < num) ? Unsafe.Add(ref source, num3 + 11) : 0), (byte)((num3 + 12 < num) ? Unsafe.Add(ref source, num3 + 12) : 0), (byte)((num3 + 13 < num) ? Unsafe.Add(ref source, num3 + 13) : 0), (byte)((num3 + 14 < num) ? Unsafe.Add(ref source, num3 + 14) : 0), (byte)((num3 + 15 < num) ? Unsafe.Add(ref source, num3 + 15) : 0), (byte)((num3 + 16 < num) ? Unsafe.Add(ref source, num3 + 16) : 0), (byte)((num3 + 17 < num) ? Unsafe.Add(ref source, num3 + 17) : 0), (byte)((num3 + 18 < num) ? Unsafe.Add(ref source, num3 + 18) : 0), (byte)((num3 + 19 < num) ? Unsafe.Add(ref source, num3 + 19) : 0), (byte)((num3 + 20 < num) ? Unsafe.Add(ref source, num3 + 20) : 0), (byte)((num3 + 21 < num) ? Unsafe.Add(ref source, num3 + 21) : 0), (byte)((num3 + 22 < num) ? Unsafe.Add(ref source, num3 + 22) : 0), (byte)((num3 + 23 < num) ? Unsafe.Add(ref source, num3 + 23) : 0), (byte)((num3 + 24 < num) ? Unsafe.Add(ref source, num3 + 24) : 0), (byte)((num3 + 25 < num) ? Unsafe.Add(ref source, num3 + 25) : 0), (byte)((num3 + 26 < num) ? Unsafe.Add(ref source, num3 + 26) : 0), (byte)((num3 + 27 < num) ? Unsafe.Add(ref source, num3 + 27) : 0), (byte)((num3 + 28 < num) ? Unsafe.Add(ref source, num3 + 28) : 0), (byte)((num3 + 29 < num) ? Unsafe.Add(ref source, num3 + 29) : 0), (byte)((num3 + 30 < num) ? Unsafe.Add(ref source, num3 + 30) : 0), (byte)((num3 + 31 < num) ? Unsafe.Add(ref source, num3 + 31) : 0));
			}
			return array;
		}

		public unsafe static PatternScanResult FindPatternCompiled(byte* data, int dataLength, CompiledScanPattern pattern)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			int numberOfInstructions = pattern.NumberOfInstructions;
			int num = dataLength - Math.Max(pattern.Length, sizeof(IntPtr)) - 8;
			if (num < 0)
			{
				return FindPatternSimple(data, dataLength, new SimplePatternScanData(pattern.Pattern));
			}
			fixed (GenericInstruction* ptr = pattern.Instructions)
			{
				GenericInstruction genericInstruction = *ptr;
				byte* ptr2 = data;
				byte* ptr3 = data + num;
				while (ptr2 < ptr3)
				{
					if (((nuint)(nint)(*(IntPtr*)ptr2) & genericInstruction.Mask) != genericInstruction.LongValue)
					{
						if (((nuint)(nint)(*(IntPtr*)(ptr2 + 1)) & genericInstruction.Mask) != genericInstruction.LongValue)
						{
							if (((nuint)(nint)(*(IntPtr*)(ptr2 + 2)) & genericInstruction.Mask) != genericInstruction.LongValue)
							{
								if (((nuint)(nint)(*(IntPtr*)(ptr2 + 3)) & genericInstruction.Mask) != genericInstruction.LongValue)
								{
									if (((nuint)(nint)(*(IntPtr*)(ptr2 + 4)) & genericInstruction.Mask) != genericInstruction.LongValue)
									{
										if (((nuint)(nint)(*(IntPtr*)(ptr2 + 5)) & genericInstruction.Mask) != genericInstruction.LongValue)
										{
											if (((nuint)(nint)(*(IntPtr*)(ptr2 + 6)) & genericInstruction.Mask) != genericInstruction.LongValue)
											{
												if (((nuint)(nint)(*(IntPtr*)(ptr2 + 7)) & genericInstruction.Mask) != genericInstruction.LongValue)
												{
													ptr2 += 8;
													continue;
												}
												ptr2 += 7;
											}
											else
											{
												ptr2 += 6;
											}
										}
										else
										{
											ptr2 += 5;
										}
									}
									else
									{
										ptr2 += 4;
									}
								}
								else
								{
									ptr2 += 3;
								}
							}
							else
							{
								ptr2 += 2;
							}
						}
						else
						{
							ptr2++;
						}
					}
					if (numberOfInstructions <= 1 || TestRemainingMasks(numberOfInstructions, ptr2, ptr))
					{
						return new PatternScanResult((int)(ptr2 - data));
					}
					ptr2++;
				}
				PatternScanResult val = FindPatternSimple(data + num, dataLength - num, pattern.Pattern);
				return ((PatternScanResult)(ref val)).AddOffset(num);
			}
		}

		private unsafe static bool TestRemainingMasks(int numberOfInstructions, byte* currentDataPointer, GenericInstruction* instructions)
		{
			currentDataPointer += sizeof(UIntPtr);
			int num = 1;
			do
			{
				nuint num2 = *(nuint*)currentDataPointer & instructions[num].Mask;
				if (num2 != instructions[num].LongValue)
				{
					return false;
				}
				currentDataPointer += sizeof(UIntPtr);
				num++;
			}
			while (num < numberOfInstructions);
			return true;
		}

		public unsafe static PatternScanResult FindPatternSimple(byte* data, int dataLength, SimplePatternScanData pattern)
		{
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			byte[] bytes = pattern.Bytes;
			byte[] mask = pattern.Mask;
			int num = dataLength - mask.Length + 1;
			fixed (byte* ptr = bytes)
			{
				for (int i = 0; i < num; i++)
				{
					int num2 = 0;
					int num3 = i;
					int num4 = 0;
					while (true)
					{
						if (mask[num4] == 0)
						{
							num3++;
							num4++;
						}
						else
						{
							if (data[num3] != ptr[num2])
							{
								break;
							}
							num3++;
							num2++;
							num4++;
						}
						if (num4 >= mask.Length)
						{
							return new PatternScanResult(i);
						}
					}
				}
				return new PatternScanResult(-1);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveOptimization)]
		public unsafe static PatternScanResult FindPatternSse2(byte* data, int dataLength, string pattern)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			SimdPatternScanData scanPattern = new SimdPatternScanData(pattern);
			if (scanPattern.Bytes.Length == 1)
			{
				return FindPatternSimple(data, dataLength, pattern);
			}
			Span<ushort> span = BuildMatchIndexes(in scanPattern);
			Vector128<byte>[] array = PadPatternToVector128Sse(in scanPattern);
			int length = span.Length;
			Vector128<byte> left = Vector128.Create(scanPattern.Bytes[scanPattern.LeadingIgnoreCount]);
			int num = dataLength - Math.Max(scanPattern.Bytes.Length, 16);
			int leadingIgnoreCount = scanPattern.LeadingIgnoreCount;
			ref Vector128<byte> source = ref array[0];
			short* ptr = (short*)Unsafe.AsPointer(ref span.GetPinnableReference());
			int num2 = array.Length;
			int num3 = 15;
			byte* ptr2 = data;
			byte* ptr3 = ptr2 + num;
			while (ptr2 < ptr3)
			{
				Vector128<byte> right = Sse2.LoadVector128(ptr2);
				Vector128<byte> value = Sse2.CompareEqual(left, right);
				int num4 = Sse2.MoveMask(value);
				if (num4 == 0)
				{
					ptr2 += num3;
				}
				else
				{
					ptr2 += BitOperations.TrailingZeroCount((uint)num4) - leadingIgnoreCount;
					int i = 0;
					int num5 = 0;
					while (true)
					{
						if (num5 < num2)
						{
							int num6 = num5 * 16;
							byte* address = ptr2 + num6 + 1;
							Vector128<byte> right2 = Sse2.LoadVector128(address);
							Vector128<byte> left2 = Unsafe.Add(ref source, num5);
							int num7 = Sse2.MoveMask(Sse2.CompareEqual(left2, right2));
							for (; i < length; i++)
							{
								int num8 = ptr[i] - num6;
								if (num8 < 16)
								{
									if (((num7 >> num8) & 1) != 1)
									{
										goto end_IL_0189;
									}
									continue;
								}
								break;
							}
							num5++;
							continue;
						}
						return new PatternScanResult((int)(ptr2 - data));
						continue;
						end_IL_0189:
						break;
					}
				}
				ptr2++;
			}
			int num9 = (int)(ptr2 - data);
			PatternScanResult val = FindPatternSimple(data + num9, dataLength - num9, pattern);
			return ((PatternScanResult)(ref val)).AddOffset(num9);
		}

		[MethodImpl(MethodImplOptions.AggressiveOptimization)]
		private static Span<ushort> BuildMatchIndexes(in SimdPatternScanData scanPattern)
		{
			int num = scanPattern.Mask.Length;
			ushort[] array = new ushort[num];
			int num2 = 0;
			for (ushort num3 = 1; num3 < num; num3++)
			{
				if (scanPattern.Mask[num3] == 1)
				{
					array[num2] = (ushort)(num3 - 1);
					num2++;
				}
			}
			return new Span<ushort>(array).Slice(0, num2);
		}

		[MethodImpl(MethodImplOptions.AggressiveOptimization)]
		private static Vector128<byte>[] PadPatternToVector128Sse(in SimdPatternScanData cbPattern)
		{
			int num = cbPattern.Mask.Length;
			int num2 = (int)Math.Ceiling((float)(num - 1) / 16f);
			Vector128<byte>[] array = new Vector128<byte>[num2];
			ref byte source = ref cbPattern.Bytes[1];
			num--;
			for (int i = 0; i < num2; i++)
			{
				if (i < num2 - 1)
				{
					array[i] = Unsafe.As<byte, Vector128<byte>>(ref Unsafe.Add(ref source, i * 16));
					continue;
				}
				int num3 = i * 16;
				array[i] = Vector128.Create(Unsafe.Add(ref source, num3), (byte)((num3 + 1 < num) ? Unsafe.Add(ref source, num3 + 1) : 0), (byte)((num3 + 2 < num) ? Unsafe.Add(ref source, num3 + 2) : 0), (byte)((num3 + 3 < num) ? Unsafe.Add(ref source, num3 + 3) : 0), (byte)((num3 + 4 < num) ? Unsafe.Add(ref source, num3 + 4) : 0), (byte)((num3 + 5 < num) ? Unsafe.Add(ref source, num3 + 5) : 0), (byte)((num3 + 6 < num) ? Unsafe.Add(ref source, num3 + 6) : 0), (byte)((num3 + 7 < num) ? Unsafe.Add(ref source, num3 + 7) : 0), (byte)((num3 + 8 < num) ? Unsafe.Add(ref source, num3 + 8) : 0), (byte)((num3 + 9 < num) ? Unsafe.Add(ref source, num3 + 9) : 0), (byte)((num3 + 10 < num) ? Unsafe.Add(ref source, num3 + 10) : 0), (byte)((num3 + 11 < num) ? Unsafe.Add(ref source, num3 + 11) : 0), (byte)((num3 + 12 < num) ? Unsafe.Add(ref source, num3 + 12) : 0), (byte)((num3 + 13 < num) ? Unsafe.Add(ref source, num3 + 13) : 0), (byte)((num3 + 14 < num) ? Unsafe.Add(ref source, num3 + 14) : 0), (byte)((num3 + 15 < num) ? Unsafe.Add(ref source, num3 + 15) : 0));
			}
			return array;
		}
	}
	public class ScannerFactory : IScannerFactory
	{
		public IScanner CreateScanner(byte[] data)
		{
			return (IScanner)(object)new Scanner(data);
		}

		public IScanner CreateScanner(Process process)
		{
			return (IScanner)(object)new Scanner(process);
		}

		public IScanner CreateScanner(Process process, ProcessModule module)
		{
			return (IScanner)(object)new Scanner(process, module);
		}

		public unsafe IScanner CreateScanner(byte* data, int length)
		{
			return (IScanner)(object)new Scanner(data, length);
		}
	}
}
namespace Reloaded.Memory.Sigscan.Utility
{
	public ref struct SpanSplitEnumerator<TSpanType> where TSpanType : IEquatable<TSpanType>
	{
		private ReadOnlySpan<TSpanType> _original;

		private bool _reachedEnd;

		public TSpanType SplitItem { get; private set; }

		public ReadOnlySpan<TSpanType> Current { get; private set; }

		public bool MoveNext()
		{
			int num = _original.IndexOf(SplitItem);
			if (num == -1)
			{
				if (_reachedEnd)
				{
					return false;
				}
				Current = _original;
				_reachedEnd = true;
				return true;
			}
			Current = _original.Slice(0, num);
			_original = _original.Slice(num + 1);
			return true;
		}

		public SpanSplitEnumerator(ReadOnlySpan<TSpanType> item, TSpanType splitItem)
		{
			_original = item;
			Current = _original;
			SplitItem = splitItem;
			_reachedEnd = false;
		}
	}
}
namespace Reloaded.Memory.Sigscan.Structs
{
	public ref struct CompiledScanPattern
	{
		private const string MaskIgnore = "??";

		public readonly string Pattern;

		public readonly int Length;

		internal GenericInstruction[] Instructions;

		internal int NumberOfInstructions;

		public unsafe CompiledScanPattern(string stringPattern)
		{
			Pattern = stringPattern;
			string[] array = stringPattern.Split(' ');
			Length = array.Length;
			Instructions = new GenericInstruction[Length];
			NumberOfInstructions = 0;
			Span<string> span = new Span<string>(array, 0, array.Length);
			while (span.Length > 0)
			{
				int num = Math.Min(sizeof(IntPtr), span.Length);
				GenerateMaskAndValue(span.Slice(0, num), out var mask, out var value);
				AddInstruction(new GenericInstruction(value, mask));
				span = span.Slice(num);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void AddInstruction(GenericInstruction instruction)
		{
			Instructions[NumberOfInstructions] = instruction;
			NumberOfInstructions++;
		}

		private unsafe void GenerateMaskAndValue(Span<string> entries, out nuint mask, out nuint value)
		{
			mask = 0u;
			value = 0u;
			for (int i = 0; i < entries.Length; i++)
			{
				mask <<= 8;
				value <<= 8;
				if (entries[i] != "??")
				{
					mask |= 255u;
					value |= byte.Parse(entries[i], NumberStyles.HexNumber);
				}
			}
			if (BitConverter.IsLittleEndian)
			{
				Endian.Reverse<UIntPtr>(ref value);
				Endian.Reverse<UIntPtr>(ref mask);
				int num = sizeof(IntPtr) - entries.Length;
				for (int j = 0; j < num; j++)
				{
					mask >>= 8;
					value >>= 8;
				}
			}
		}

		public static implicit operator CompiledScanPattern(string pattern)
		{
			return new CompiledScanPattern(pattern);
		}
	}
	public struct GenericInstruction
	{
		public nuint LongValue;

		public nuint Mask;

		public GenericInstruction(nuint longValue, nuint mask)
		{
			LongValue = longValue;
			Mask = mask;
		}
	}
	public ref struct SimdPatternScanData
	{
		private static char[] _maskIgnore = new char[2] { '?', '?' };

		private static List<byte> _bytes = new List<byte>(1024);

		private static List<byte> _maskBuilder = new List<byte>(1024);

		private static object _buildLock = new object();

		public byte[] Bytes;

		public byte[] Mask;

		public int LeadingIgnoreCount;

		public SimdPatternScanData(string stringPattern)
		{
			LeadingIgnoreCount = 0;
			SpanSplitEnumerator<char> spanSplitEnumerator = new SpanSplitEnumerator<char>(stringPattern, ' ');
			ReadOnlySpan<char> other = new ReadOnlySpan<char>(_maskIgnore);
			bool flag = false;
			lock (_buildLock)
			{
				_maskBuilder.Clear();
				_bytes.Clear();
				while (spanSplitEnumerator.MoveNext())
				{
					if (MemoryExtensions.Equals(spanSplitEnumerator.Current, other, StringComparison.Ordinal))
					{
						_maskBuilder.Add(0);
						_bytes.Add(0);
						if (!flag)
						{
							LeadingIgnoreCount++;
						}
					}
					else
					{
						_bytes.Add(byte.Parse(spanSplitEnumerator.Current, NumberStyles.AllowHexSpecifier));
						_maskBuilder.Add(1);
						flag = true;
					}
				}
				Mask = _maskBuilder.ToArray();
				Bytes = _bytes.ToArray();
			}
		}
	}
	public ref struct SimplePatternScanData
	{
		private static char[] _maskIgnore = new char[2] { '?', '?' };

		private static List<byte> _bytes = new List<byte>(1024);

		private static List<byte> _maskBuilder = new List<byte>(1024);

		private static object _buildLock = new object();

		public byte[] Bytes;

		public byte[] Mask;

		public string Pattern;

		public SimplePatternScanData(string stringPattern)
		{
			Pattern = stringPattern;
			SpanSplitEnumerator<char> spanSplitEnumerator = new SpanSplitEnumerator<char>(stringPattern, ' ');
			ReadOnlySpan<char> other = new ReadOnlySpan<char>(_maskIgnore);
			lock (_buildLock)
			{
				_maskBuilder.Clear();
				_bytes.Clear();
				while (spanSplitEnumerator.MoveNext())
				{
					if (MemoryExtensions.Equals(spanSplitEnumerator.Current, other, StringComparison.Ordinal))
					{
						_maskBuilder.Add(0);
						continue;
					}
					_bytes.Add(byte.Parse(spanSplitEnumerator.Current, NumberStyles.AllowHexSpecifier));
					_maskBuilder.Add(1);
				}
				Mask = _maskBuilder.ToArray();
				Bytes = _bytes.ToArray();
			}
		}

		public static implicit operator SimplePatternScanData(string pattern)
		{
			return new SimplePatternScanData(pattern);
		}
	}
}

GDWeave/core/Serilog.dll

Decompiled 3 days ago
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Serilog.Capturing;
using Serilog.Configuration;
using Serilog.Context;
using Serilog.Core;
using Serilog.Core.Enrichers;
using Serilog.Core.Filters;
using Serilog.Core.Pipeline;
using Serilog.Core.Sinks;
using Serilog.Core.Sinks.Batching;
using Serilog.Data;
using Serilog.Debugging;
using Serilog.Events;
using Serilog.Formatting.Json;
using Serilog.Parsing;
using Serilog.Policies;
using Serilog.Rendering;
using Serilog.Settings.KeyValuePairs;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(/*Could not decode attribute arguments.*/)]
[assembly: CLSCompliant(true)]
[assembly: InternalsVisibleTo("Serilog.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100fb8d13fd344a1c6fe0fe83ef33c1080bf30690765bc6eb0df26ebfdf8f21670c64265b30db09f73a0dea5b3db4c9d18dbf6d5a25af5ce9016f281014d79dc3b4201ac646c451830fc7e61a2dfd633d34c39f87b81894191652df5ac63cc40c77f3542f702bda692e6e8a9158353df189007a49da0f3cfd55eb250066b19485ec")]
[assembly: InternalsVisibleTo("Serilog.PerformanceTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100fb8d13fd344a1c6fe0fe83ef33c1080bf30690765bc6eb0df26ebfdf8f21670c64265b30db09f73a0dea5b3db4c9d18dbf6d5a25af5ce9016f281014d79dc3b4201ac646c451830fc7e61a2dfd633d34c39f87b81894191652df5ac63cc40c77f3542f702bda692e6e8a9158353df189007a49da0f3cfd55eb250066b19485ec")]
[assembly: TargetFramework(".NETCoreApp,Version=v8.0", FrameworkDisplayName = ".NET 8.0")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCompany("Serilog Contributors")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © 2013-24 Serilog Contributors")]
[assembly: AssemblyDescription("Simple .NET logging with fully-structured events")]
[assembly: AssemblyFileVersion("4.0.0.0")]
[assembly: AssemblyInformationalVersion("4.0.0-main-573a6287+573a62874260d7a1708f620076b5469f69bc79b3")]
[assembly: AssemblyProduct("Serilog")]
[assembly: AssemblyTitle("Serilog")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/serilog/serilog.git")]
[assembly: AssemblyVersion("4.0.0.0")]
[assembly: TypeForwardedTo(typeof(IsExternalInit))]
[assembly: TypeForwardedTo(typeof(RequiresLocationAttribute))]
[module: RefSafetyRules(11)]
internal static class Guard
{
	public static T AgainstNull<T>([NoEnumeration][NotNull] T? argument, [CallerArgumentExpression("argument")] string? paramName = null) where T : class
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		if (argument == null)
		{
			throw new ArgumentNullException(paramName);
		}
		return argument;
	}
}
namespace JetBrains.Annotations
{
	[AttributeUsage(/*Could not decode attribute arguments.*/)]
	internal sealed class NoEnumerationAttribute : System.Attribute
	{
	}
}
namespace Serilog
{
	public interface ILogger
	{
		private static readonly object[] NoPropertyValues = System.Array.Empty<object>();

		private static readonly Logger DefaultLoggerImpl = new LoggerConfiguration().CreateLogger();

		[CustomDefaultMethodImplementation]
		ILogger ForContext(ILogEventEnricher enricher)
		{
			return new LoggerConfiguration().MinimumLevel.Is(LogEventLevel.Verbose).WriteTo.Logger(this).CreateLogger().ForContext(enricher);
		}

		ILogger ForContext(System.Collections.Generic.IEnumerable<ILogEventEnricher> enrichers)
		{
			if (enrichers == null)
			{
				return this;
			}
			return ForContext(new SafeAggregateEnricher(enrichers));
		}

		[CustomDefaultMethodImplementation]
		ILogger ForContext(string propertyName, object? value, bool destructureObjects = false)
		{
			return new LoggerConfiguration().MinimumLevel.Is(LogEventLevel.Verbose).WriteTo.Logger(this).CreateLogger().ForContext(propertyName, value, destructureObjects);
		}

		ILogger ForContext<TSource>()
		{
			return ForContext(typeof(TSource));
		}

		ILogger ForContext(System.Type source)
		{
			if (source == (System.Type)null)
			{
				return this;
			}
			return ForContext("SourceContext", source.FullName);
		}

		void Write(LogEvent logEvent);

		[MessageTemplateFormatMethod("messageTemplate")]
		void Write(LogEventLevel level, string messageTemplate)
		{
			if (IsEnabled(level))
			{
				Write(level, messageTemplate, NoPropertyValues);
			}
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Write<T>(LogEventLevel level, string messageTemplate, T propertyValue)
		{
			if (IsEnabled(level))
			{
				Write(level, messageTemplate, new object[1] { propertyValue });
			}
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Write<T0, T1>(LogEventLevel level, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			if (IsEnabled(level))
			{
				Write(level, messageTemplate, new object[2] { propertyValue0, propertyValue1 });
			}
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Write<T0, T1, T2>(LogEventLevel level, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			if (IsEnabled(level))
			{
				Write(level, messageTemplate, new object[3] { propertyValue0, propertyValue1, propertyValue2 });
			}
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Write(LogEventLevel level, string messageTemplate, params object?[]? propertyValues)
		{
			Write(level, (System.Exception?)null, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Write(LogEventLevel level, System.Exception? exception, string messageTemplate)
		{
			if (IsEnabled(level))
			{
				Write(level, exception, messageTemplate, NoPropertyValues);
			}
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Write<T>(LogEventLevel level, System.Exception? exception, string messageTemplate, T propertyValue)
		{
			if (IsEnabled(level))
			{
				Write(level, exception, messageTemplate, new object[1] { propertyValue });
			}
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Write<T0, T1>(LogEventLevel level, System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			if (IsEnabled(level))
			{
				Write(level, exception, messageTemplate, new object[2] { propertyValue0, propertyValue1 });
			}
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Write<T0, T1, T2>(LogEventLevel level, System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			if (IsEnabled(level))
			{
				Write(level, exception, messageTemplate, new object[3] { propertyValue0, propertyValue1, propertyValue2 });
			}
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		[CustomDefaultMethodImplementation]
		void Write(LogEventLevel level, System.Exception? exception, string messageTemplate, params object?[]? propertyValues)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			if (IsEnabled(level) && messageTemplate != null)
			{
				if (propertyValues != null && ((object)propertyValues).GetType() != typeof(object[]))
				{
					propertyValues = new object[1] { propertyValues };
				}
				DateTimeOffset now = DateTimeOffset.Now;
				if (BindMessageTemplate(messageTemplate, propertyValues, out MessageTemplate parsedTemplate, out System.Collections.Generic.IEnumerable<LogEventProperty> boundProperties))
				{
					Activity current = Activity.Current;
					LogEvent logEvent = new LogEvent(now, level, exception, parsedTemplate, boundProperties, (ActivityTraceId)((current != null) ? current.TraceId : default(ActivityTraceId)), (ActivitySpanId)((current != null) ? current.SpanId : default(ActivitySpanId)));
					Write(logEvent);
				}
			}
		}

		[CustomDefaultMethodImplementation]
		bool IsEnabled(LogEventLevel level)
		{
			return true;
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Verbose(string messageTemplate)
		{
			Write(LogEventLevel.Verbose, messageTemplate, NoPropertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Verbose<T>(string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Verbose, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Verbose<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Verbose, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Verbose<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Verbose, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Verbose(string messageTemplate, params object?[]? propertyValues)
		{
			Verbose((System.Exception?)null, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Verbose(System.Exception? exception, string messageTemplate)
		{
			Write(LogEventLevel.Verbose, exception, messageTemplate, NoPropertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Verbose<T>(System.Exception? exception, string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Verbose, exception, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Verbose<T0, T1>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Verbose, exception, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Verbose<T0, T1, T2>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Verbose, exception, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Verbose(System.Exception? exception, string messageTemplate, params object?[]? propertyValues)
		{
			Write(LogEventLevel.Verbose, exception, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Debug(string messageTemplate)
		{
			Write(LogEventLevel.Debug, messageTemplate, NoPropertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Debug<T>(string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Debug, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Debug<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Debug, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Debug<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Debug, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Debug(string messageTemplate, params object?[]? propertyValues)
		{
			Debug((System.Exception?)null, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Debug(System.Exception? exception, string messageTemplate)
		{
			Write(LogEventLevel.Debug, exception, messageTemplate, NoPropertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Debug<T>(System.Exception? exception, string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Debug, exception, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Debug<T0, T1>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Debug, exception, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Debug<T0, T1, T2>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Debug, exception, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Debug(System.Exception? exception, string messageTemplate, params object?[]? propertyValues)
		{
			Write(LogEventLevel.Debug, exception, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Information(string messageTemplate)
		{
			Write(LogEventLevel.Information, messageTemplate, NoPropertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Information<T>(string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Information, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Information<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Information, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Information<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Information, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Information(string messageTemplate, params object?[]? propertyValues)
		{
			Information((System.Exception?)null, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Information(System.Exception? exception, string messageTemplate)
		{
			Write(LogEventLevel.Information, exception, messageTemplate, NoPropertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Information<T>(System.Exception? exception, string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Information, exception, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Information<T0, T1>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Information, exception, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Information<T0, T1, T2>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Information, exception, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Information(System.Exception? exception, string messageTemplate, params object?[]? propertyValues)
		{
			Write(LogEventLevel.Information, exception, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Warning(string messageTemplate)
		{
			Write(LogEventLevel.Warning, messageTemplate, NoPropertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Warning<T>(string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Warning, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Warning<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Warning, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Warning<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Warning, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Warning(string messageTemplate, params object?[]? propertyValues)
		{
			Warning((System.Exception?)null, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Warning(System.Exception? exception, string messageTemplate)
		{
			Write(LogEventLevel.Warning, exception, messageTemplate, NoPropertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Warning<T>(System.Exception? exception, string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Warning, exception, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Warning<T0, T1>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Warning, exception, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Warning<T0, T1, T2>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Warning, exception, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Warning(System.Exception? exception, string messageTemplate, params object?[]? propertyValues)
		{
			Write(LogEventLevel.Warning, exception, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Error(string messageTemplate)
		{
			Write(LogEventLevel.Error, messageTemplate, NoPropertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Error<T>(string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Error, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Error<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Error, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Error<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Error, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Error(string messageTemplate, params object?[]? propertyValues)
		{
			Error((System.Exception?)null, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Error(System.Exception? exception, string messageTemplate)
		{
			Write(LogEventLevel.Error, exception, messageTemplate, NoPropertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Error<T>(System.Exception? exception, string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Error, exception, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Error<T0, T1>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Error, exception, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Error<T0, T1, T2>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Error, exception, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Error(System.Exception? exception, string messageTemplate, params object?[]? propertyValues)
		{
			Write(LogEventLevel.Error, exception, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Fatal(string messageTemplate)
		{
			Write(LogEventLevel.Fatal, messageTemplate, NoPropertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Fatal<T>(string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Fatal, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Fatal<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Fatal, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Fatal<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Fatal, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Fatal(string messageTemplate, params object?[]? propertyValues)
		{
			Fatal((System.Exception?)null, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Fatal(System.Exception? exception, string messageTemplate)
		{
			Write(LogEventLevel.Fatal, exception, messageTemplate, NoPropertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Fatal<T>(System.Exception? exception, string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Fatal, exception, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Fatal<T0, T1>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Fatal, exception, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Fatal<T0, T1, T2>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Fatal, exception, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		void Fatal(System.Exception? exception, string messageTemplate, params object?[]? propertyValues)
		{
			Write(LogEventLevel.Fatal, exception, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		[CustomDefaultMethodImplementation]
		bool BindMessageTemplate(string messageTemplate, object?[]? propertyValues, [NotNullWhen(true)] out MessageTemplate? parsedTemplate, [NotNullWhen(true)] out System.Collections.Generic.IEnumerable<LogEventProperty>? boundProperties)
		{
			return DefaultLoggerImpl.BindMessageTemplate(messageTemplate, propertyValues, out parsedTemplate, out boundProperties);
		}

		[CustomDefaultMethodImplementation]
		bool BindProperty(string? propertyName, object? value, bool destructureObjects, [NotNullWhen(true)] out LogEventProperty? property)
		{
			return DefaultLoggerImpl.BindProperty(propertyName, value, destructureObjects, out property);
		}
	}
	public static class Log
	{
		private static ILogger _logger = Serilog.Core.Logger.None;

		public static ILogger Logger
		{
			get
			{
				return _logger;
			}
			set
			{
				_logger = Guard.AgainstNull(value, "value");
			}
		}

		public static void CloseAndFlush()
		{
			(Interlocked.Exchange<ILogger>(ref _logger, Serilog.Core.Logger.None) as System.IDisposable)?.Dispose();
		}

		public static System.Threading.Tasks.ValueTask CloseAndFlushAsync()
		{
			return (Interlocked.Exchange<ILogger>(ref _logger, Serilog.Core.Logger.None) as System.IAsyncDisposable)?.DisposeAsync() ?? default(System.Threading.Tasks.ValueTask);
		}

		public static ILogger ForContext(ILogEventEnricher enricher)
		{
			return Logger.ForContext(enricher);
		}

		public static ILogger ForContext(ILogEventEnricher[] enrichers)
		{
			return Logger.ForContext(enrichers);
		}

		public static ILogger ForContext(string propertyName, object? value, bool destructureObjects = false)
		{
			return Logger.ForContext(propertyName, value, destructureObjects);
		}

		public static ILogger ForContext<TSource>()
		{
			return Logger.ForContext<TSource>();
		}

		public static ILogger ForContext(System.Type source)
		{
			return Logger.ForContext(source);
		}

		public static void Write(LogEvent logEvent)
		{
			Logger.Write(logEvent);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Write(LogEventLevel level, string messageTemplate)
		{
			Logger.Write(level, messageTemplate);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Write<T>(LogEventLevel level, string messageTemplate, T propertyValue)
		{
			Logger.Write(level, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Write<T0, T1>(LogEventLevel level, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Logger.Write(level, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Write<T0, T1, T2>(LogEventLevel level, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Logger.Write(level, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Write(LogEventLevel level, string messageTemplate, params object?[]? propertyValues)
		{
			Logger.Write(level, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Write(LogEventLevel level, System.Exception? exception, string messageTemplate)
		{
			Logger.Write(level, exception, messageTemplate);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Write<T>(LogEventLevel level, System.Exception? exception, string messageTemplate, T propertyValue)
		{
			Logger.Write(level, exception, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Write<T0, T1>(LogEventLevel level, System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Logger.Write(level, exception, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Write<T0, T1, T2>(LogEventLevel level, System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Logger.Write(level, exception, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Write(LogEventLevel level, System.Exception? exception, string messageTemplate, params object?[]? propertyValues)
		{
			Logger.Write(level, exception, messageTemplate, propertyValues);
		}

		public static bool IsEnabled(LogEventLevel level)
		{
			return Logger.IsEnabled(level);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Verbose(string messageTemplate)
		{
			Write(LogEventLevel.Verbose, messageTemplate);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Verbose<T>(string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Verbose, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Verbose<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Verbose, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Verbose<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Verbose, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Verbose(string messageTemplate, params object?[]? propertyValues)
		{
			Logger.Verbose(messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Verbose(System.Exception? exception, string messageTemplate)
		{
			Write(LogEventLevel.Verbose, exception, messageTemplate);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Verbose<T>(System.Exception? exception, string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Verbose, exception, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Verbose<T0, T1>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Verbose, exception, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Verbose<T0, T1, T2>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Verbose, exception, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Verbose(System.Exception? exception, string messageTemplate, params object?[]? propertyValues)
		{
			Logger.Verbose(exception, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Debug(string messageTemplate)
		{
			Write(LogEventLevel.Debug, messageTemplate);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Debug<T>(string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Debug, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Debug<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Debug, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Debug<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Debug, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Debug(string messageTemplate, params object?[]? propertyValues)
		{
			Logger.Debug(messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Debug(System.Exception? exception, string messageTemplate)
		{
			Write(LogEventLevel.Debug, exception, messageTemplate);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Debug<T>(System.Exception? exception, string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Debug, exception, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Debug<T0, T1>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Debug, exception, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Debug<T0, T1, T2>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Debug, exception, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Debug(System.Exception? exception, string messageTemplate, params object?[]? propertyValues)
		{
			Logger.Debug(exception, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Information(string messageTemplate)
		{
			Write(LogEventLevel.Information, messageTemplate);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Information<T>(string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Information, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Information<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Information, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Information<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Information, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Information(string messageTemplate, params object?[]? propertyValues)
		{
			Logger.Information(messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Information(System.Exception? exception, string messageTemplate)
		{
			Write(LogEventLevel.Information, exception, messageTemplate);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Information<T>(System.Exception? exception, string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Information, exception, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Information<T0, T1>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Information, exception, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Information<T0, T1, T2>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Information, exception, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Information(System.Exception? exception, string messageTemplate, params object?[]? propertyValues)
		{
			Logger.Information(exception, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Warning(string messageTemplate)
		{
			Write(LogEventLevel.Warning, messageTemplate);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Warning<T>(string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Warning, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Warning<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Warning, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Warning<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Warning, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Warning(string messageTemplate, params object?[]? propertyValues)
		{
			Logger.Warning(messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Warning(System.Exception? exception, string messageTemplate)
		{
			Write(LogEventLevel.Warning, exception, messageTemplate);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Warning<T>(System.Exception? exception, string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Warning, exception, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Warning<T0, T1>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Warning, exception, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Warning<T0, T1, T2>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Warning, exception, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Warning(System.Exception? exception, string messageTemplate, params object?[]? propertyValues)
		{
			Logger.Warning(exception, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Error(string messageTemplate)
		{
			Write(LogEventLevel.Error, messageTemplate);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Error<T>(string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Error, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Error<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Error, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Error<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Error, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Error(string messageTemplate, params object?[]? propertyValues)
		{
			Logger.Error(messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Error(System.Exception? exception, string messageTemplate)
		{
			Write(LogEventLevel.Error, exception, messageTemplate);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Error<T>(System.Exception? exception, string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Error, exception, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Error<T0, T1>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Error, exception, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Error<T0, T1, T2>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Error, exception, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Error(System.Exception? exception, string messageTemplate, params object?[]? propertyValues)
		{
			Logger.Error(exception, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Fatal(string messageTemplate)
		{
			Write(LogEventLevel.Fatal, messageTemplate);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Fatal<T>(string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Fatal, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Fatal<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Fatal, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Fatal<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Fatal, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Fatal(string messageTemplate, params object?[]? propertyValues)
		{
			Logger.Fatal(messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Fatal(System.Exception? exception, string messageTemplate)
		{
			Write(LogEventLevel.Fatal, exception, messageTemplate);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Fatal<T>(System.Exception? exception, string messageTemplate, T propertyValue)
		{
			Write(LogEventLevel.Fatal, exception, messageTemplate, propertyValue);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Fatal<T0, T1>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
		{
			Write(LogEventLevel.Fatal, exception, messageTemplate, propertyValue0, propertyValue1);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Fatal<T0, T1, T2>(System.Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
		{
			Write(LogEventLevel.Fatal, exception, messageTemplate, propertyValue0, propertyValue1, propertyValue2);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static void Fatal(System.Exception? exception, string messageTemplate, params object?[]? propertyValues)
		{
			Logger.Fatal(exception, messageTemplate, propertyValues);
		}

		[MessageTemplateFormatMethod("messageTemplate")]
		public static bool BindMessageTemplate(string messageTemplate, object?[] propertyValues, [NotNullWhen(true)] out MessageTemplate? parsedTemplate, [NotNullWhen(true)] out System.Collections.Generic.IEnumerable<LogEventProperty>? boundProperties)
		{
			return Logger.BindMessageTemplate(messageTemplate, propertyValues, out parsedTemplate, out boundProperties);
		}

		public static bool BindProperty(string propertyName, object? value, bool destructureObjects, [NotNullWhen(true)] out LogEventProperty? property)
		{
			return Logger.BindProperty(propertyName, value, destructureObjects, out property);
		}
	}
	public class LoggerConfiguration
	{
		[CompilerGenerated]
		private sealed class <>c__DisplayClass33_0
		{
			public ILogEventSink[] disposableSinks;
		}

		private readonly List<ILogEventSink> _logEventSinks = new List<ILogEventSink>();

		private readonly List<ILogEventSink> _auditSinks = new List<ILogEventSink>();

		private readonly List<ILogEventEnricher> _enrichers = new List<ILogEventEnricher>();

		private readonly List<ILogEventFilter> _filters = new List<ILogEventFilter>();

		private readonly List<System.Type> _additionalScalarTypes = new List<System.Type>();

		private readonly HashSet<System.Type> _additionalDictionaryTypes = new HashSet<System.Type>();

		private readonly List<IDestructuringPolicy> _additionalDestructuringPolicies = new List<IDestructuringPolicy>();

		private readonly Dictionary<string, LoggingLevelSwitch> _overrides = new Dictionary<string, LoggingLevelSwitch>();

		private LogEventLevel _minimumLevel = LogEventLevel.Information;

		private LoggingLevelSwitch? _levelSwitch;

		private int _maximumDestructuringDepth = 10;

		private int _maximumStringLength = 2147483647;

		private int _maximumCollectionCount = 2147483647;

		private bool _loggerCreated;

		[field: CompilerGenerated]
		public LoggerSinkConfiguration WriteTo
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			internal set;
		}

		public LoggerAuditSinkConfiguration AuditTo => new LoggerAuditSinkConfiguration(this, [CompilerGenerated] (ILogEventSink s) =>
		{
			_auditSinks.Add(s);
		});

		public LoggerMinimumLevelConfiguration MinimumLevel => new LoggerMinimumLevelConfiguration(this, [CompilerGenerated] (LogEventLevel l) =>
		{
			_minimumLevel = l;
			_levelSwitch = null;
		}, [CompilerGenerated] (LoggingLevelSwitch sw) =>
		{
			_levelSwitch = sw;
		}, [CompilerGenerated] (string s, LoggingLevelSwitch lls) =>
		{
			_overrides[s] = lls;
		});

		[field: CompilerGenerated]
		public LoggerEnrichmentConfiguration Enrich
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			internal set;
		}

		public LoggerFilterConfiguration Filter => new LoggerFilterConfiguration(this, [CompilerGenerated] (ILogEventFilter f) =>
		{
			_filters.Add(f);
		});

		public LoggerDestructuringConfiguration Destructure
		{
			get
			{
				List<System.Type> additionalScalarTypes = _additionalScalarTypes;
				Action<System.Type> addScalar = additionalScalarTypes.Add;
				Action<System.Type> addDictionaryType = [CompilerGenerated] (System.Type type) =>
				{
					_additionalDictionaryTypes.Add(type);
				};
				List<IDestructuringPolicy> additionalDestructuringPolicies = _additionalDestructuringPolicies;
				return new LoggerDestructuringConfiguration(this, addScalar, addDictionaryType, additionalDestructuringPolicies.Add, [CompilerGenerated] (int depth) =>
				{
					_maximumDestructuringDepth = depth;
				}, [CompilerGenerated] (int length) =>
				{
					_maximumStringLength = length;
				}, [CompilerGenerated] (int count) =>
				{
					_maximumCollectionCount = count;
				});
			}
		}

		public LoggerSettingsConfiguration ReadFrom => new LoggerSettingsConfiguration(this);

		public LoggerConfiguration()
		{
			WriteTo = new LoggerSinkConfiguration(this, [CompilerGenerated] (ILogEventSink s) =>
			{
				_logEventSinks.Add(s);
			});
			Enrich = new LoggerEnrichmentConfiguration(this, [CompilerGenerated] (ILogEventEnricher e) =>
			{
				_enrichers.Add(e);
			});
		}

		public Logger CreateLogger()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Expected O, but got Unknown
			<>c__DisplayClass33_0 CS$<>8__locals0 = new <>c__DisplayClass33_0();
			if (_loggerCreated)
			{
				throw new InvalidOperationException("CreateLogger() was previously called and can only be called once.");
			}
			_loggerCreated = true;
			ILogEventSink logEventSink = null;
			if (_logEventSinks.Count > 0)
			{
				logEventSink = new SafeAggregateSink((System.Collections.Generic.IEnumerable<ILogEventSink>)_logEventSinks);
			}
			bool flag = Enumerable.Any<ILogEventSink>((System.Collections.Generic.IEnumerable<ILogEventSink>)_auditSinks);
			if (flag)
			{
				System.Collections.Generic.IEnumerable<ILogEventSink> sinks;
				if (logEventSink != null)
				{
					sinks = Enumerable.Concat<ILogEventSink>((System.Collections.Generic.IEnumerable<ILogEventSink>)new ILogEventSink[1] { logEventSink }, (System.Collections.Generic.IEnumerable<ILogEventSink>)_auditSinks);
				}
				else
				{
					System.Collections.Generic.IEnumerable<ILogEventSink> auditSinks = (System.Collections.Generic.IEnumerable<ILogEventSink>)_auditSinks;
					sinks = auditSinks;
				}
				logEventSink = new AggregateSink(sinks);
			}
			if (logEventSink == null)
			{
				logEventSink = new SafeAggregateSink(System.Array.Empty<ILogEventSink>());
			}
			if (Enumerable.Any<ILogEventFilter>((System.Collections.Generic.IEnumerable<ILogEventFilter>)_filters))
			{
				logEventSink = new FilteringSink(logEventSink, (System.Collections.Generic.IEnumerable<ILogEventFilter>)_filters, flag);
			}
			MessageTemplateProcessor messageTemplateProcessor = new MessageTemplateProcessor(new PropertyValueConverter(_maximumDestructuringDepth, _maximumStringLength, _maximumCollectionCount, (System.Collections.Generic.IEnumerable<System.Type>)_additionalScalarTypes, (System.Collections.Generic.IEnumerable<System.Type>)_additionalDictionaryTypes, (System.Collections.Generic.IEnumerable<IDestructuringPolicy>)_additionalDestructuringPolicies, flag));
			ILogEventEnricher enricher = _enrichers.Count switch
			{
				0 => new EmptyEnricher(), 
				1 => _enrichers[0], 
				_ => new SafeAggregateEnricher((System.Collections.Generic.IEnumerable<ILogEventEnricher>)_enrichers), 
			};
			LevelOverrideMap overrideMap = null;
			if (_overrides.Count != 0)
			{
				overrideMap = new LevelOverrideMap((IDictionary<string, LoggingLevelSwitch>)(object)_overrides, _minimumLevel, _levelSwitch);
			}
			CS$<>8__locals0.disposableSinks = Enumerable.ToArray<ILogEventSink>(Enumerable.Where<ILogEventSink>(Enumerable.Concat<ILogEventSink>((System.Collections.Generic.IEnumerable<ILogEventSink>)_logEventSinks, (System.Collections.Generic.IEnumerable<ILogEventSink>)_auditSinks), (Func<ILogEventSink, bool>)((ILogEventSink s) => (s is System.IDisposable || s is System.IAsyncDisposable) ? true : false)));
			return new Logger(messageTemplateProcessor, (_levelSwitch == null) ? _minimumLevel : LogEventLevel.Verbose, _levelSwitch, logEventSink, enricher, new Action(Dispose), DisposeAsync, overrideMap);
			void Dispose()
			{
				ILogEventSink[] disposableSinks = CS$<>8__locals0.disposableSinks;
				for (int i = 0; i < disposableSinks.Length; i++)
				{
					(disposableSinks[i] as System.IDisposable)?.Dispose();
				}
			}
			[AsyncStateMachine(typeof(<>c__DisplayClass33_0.<<CreateLogger>g__DisposeAsync|2>d))]
			System.Threading.Tasks.ValueTask DisposeAsync()
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				<>c__DisplayClass33_0.<<CreateLogger>g__DisposeAsync|2>d <<CreateLogger>g__DisposeAsync|2>d = default(<>c__DisplayClass33_0.<<CreateLogger>g__DisposeAsync|2>d);
				<<CreateLogger>g__DisposeAsync|2>d.<>t__builder = AsyncValueTaskMethodBuilder.Create();
				<<CreateLogger>g__DisposeAsync|2>d.<>4__this = CS$<>8__locals0;
				<<CreateLogger>g__DisposeAsync|2>d.<>1__state = -1;
				((AsyncValueTaskMethodBuilder)(ref <<CreateLogger>g__DisposeAsync|2>d.<>t__builder)).Start<<>c__DisplayClass33_0.<<CreateLogger>g__DisposeAsync|2>d>(ref <<CreateLogger>g__DisposeAsync|2>d);
				return ((AsyncValueTaskMethodBuilder)(ref <<CreateLogger>g__DisposeAsync|2>d.<>t__builder)).Task;
			}
		}
	}
	public static class LoggerExtensions
	{
		public static ILogger ForContext<TValue>(this ILogger logger, LogEventLevel level, string propertyName, TValue value, bool destructureObjects = false)
		{
			Guard.AgainstNull(logger, "logger");
			if (!logger.IsEnabled(level))
			{
				return logger;
			}
			return logger.ForContext(propertyName, value, destructureObjects);
		}
	}
}
namespace Serilog.Settings.KeyValuePairs
{
	internal static class CallableConfigurationMethodFinder
	{
		[RequiresUnreferencedCode("Configuration methods are not trimming safe")]
		internal static System.Collections.Generic.IList<MethodInfo> FindConfigurationMethods(System.Collections.Generic.IEnumerable<Assembly> configurationAssemblies, System.Type configType)
		{
			System.Type configType2 = configType;
			List<MethodInfo> val = Enumerable.ToList<MethodInfo>(Enumerable.Where<MethodInfo>(Enumerable.SelectMany<System.Type, MethodInfo>(Enumerable.SelectMany<Assembly, System.Type>(configurationAssemblies, (Func<Assembly, System.Collections.Generic.IEnumerable<System.Type>>)([RequiresUnreferencedCode("Configuration methods are not trimming safe")] (Assembly a) => Enumerable.Where<System.Type>(a.ExportedTypes, (Func<System.Type, bool>)((System.Type t) => t.IsSealed && t.IsAbstract && !t.IsNested)))), (Func<System.Type, System.Collections.Generic.IEnumerable<MethodInfo>>)((System.Type t) => t.GetMethods((BindingFlags)24))), (Func<MethodInfo, bool>)((MethodInfo m) => ((MemberInfo)m).IsDefined(typeof(ExtensionAttribute), false) && ((MethodBase)m).GetParameters()[0].ParameterType == configType2)));
			if (configType2 == typeof(LoggerSinkConfiguration))
			{
				val.AddRange((System.Collections.Generic.IEnumerable<MethodInfo>)SurrogateConfigurationMethods.WriteTo);
			}
			if (configType2 == typeof(LoggerAuditSinkConfiguration))
			{
				val.AddRange((System.Collections.Generic.IEnumerable<MethodInfo>)SurrogateConfigurationMethods.AuditTo);
			}
			if (configType2 == typeof(LoggerEnrichmentConfiguration))
			{
				val.AddRange((System.Collections.Generic.IEnumerable<MethodInfo>)SurrogateConfigurationMethods.Enrich);
			}
			if (configType2 == typeof(LoggerDestructuringConfiguration))
			{
				val.AddRange((System.Collections.Generic.IEnumerable<MethodInfo>)SurrogateConfigurationMethods.Destructure);
			}
			if (configType2 == typeof(LoggerFilterConfiguration))
			{
				val.AddRange((System.Collections.Generic.IEnumerable<MethodInfo>)SurrogateConfigurationMethods.Filter);
			}
			return (System.Collections.Generic.IList<MethodInfo>)val;
		}
	}
	[RequiresUnreferencedCode("Scans assemblies at runtime")]
	[RequiresDynamicCode("Creates arrays of unknown element type")]
	internal class KeyValuePairSettings : ILoggerSettings
	{
		internal class ConfigurationMethodCall
		{
			[field: CompilerGenerated]
			public string MethodName
			{
				[CompilerGenerated]
				get;
			}

			[field: CompilerGenerated]
			public string ArgumentName
			{
				[CompilerGenerated]
				get;
			}

			[field: CompilerGenerated]
			public string Value
			{
				[CompilerGenerated]
				get;
			}

			public ConfigurationMethodCall(string methodName, string argumentName, string value)
			{
				MethodName = methodName;
				ArgumentName = argumentName;
				Value = value;
			}
		}

		private const string UsingDirective = "using";

		private const string LevelSwitchDirective = "level-switch";

		private const string AuditToDirective = "audit-to";

		private const string WriteToDirective = "write-to";

		private const string MinimumLevelDirective = "minimum-level";

		private const string MinimumLevelControlledByDirective = "minimum-level:controlled-by";

		private const string EnrichWithDirective = "enrich";

		private const string EnrichWithPropertyDirective = "enrich:with-property";

		private const string FilterDirective = "filter";

		private const string DestructureDirective = "destructure";

		private const string UsingDirectiveFullFormPrefix = "using:";

		private const string EnrichWithPropertyDirectivePrefix = "enrich:with-property:";

		private const string MinimumLevelOverrideDirectivePrefix = "minimum-level:override:";

		private const string CallableDirectiveRegex = "^(?<directive>audit-to|write-to|enrich|filter|destructure):(?<method>[A-Za-z0-9]*)(\\.(?<argument>[A-Za-z0-9]*)){0,1}$";

		private const string LevelSwitchDeclarationDirectiveRegex = "^level-switch:(?<switchName>.*)$";

		private const string LevelSwitchNameRegex = "^\\$[A-Za-z]+[A-Za-z0-9]*$";

		private static readonly string[] _supportedDirectives = new string[10] { "using", "level-switch", "audit-to", "write-to", "minimum-level", "minimum-level:controlled-by", "enrich:with-property", "enrich", "filter", "destructure" };

		private static readonly Dictionary<string, System.Type> CallableDirectiveReceiverTypes = new Dictionary<string, System.Type>
		{
			["audit-to"] = typeof(LoggerAuditSinkConfiguration),
			["write-to"] = typeof(LoggerSinkConfiguration),
			["enrich"] = typeof(LoggerEnrichmentConfiguration),
			["filter"] = typeof(LoggerFilterConfiguration),
			["destructure"] = typeof(LoggerDestructuringConfiguration)
		};

		private static readonly Dictionary<System.Type, Func<LoggerConfiguration, object>> CallableDirectiveReceivers = new Dictionary<System.Type, Func<LoggerConfiguration, object>>
		{
			[typeof(LoggerAuditSinkConfiguration)] = (LoggerConfiguration lc) => lc.AuditTo,
			[typeof(LoggerSinkConfiguration)] = (LoggerConfiguration lc) => lc.WriteTo,
			[typeof(LoggerEnrichmentConfiguration)] = (LoggerConfiguration lc) => lc.Enrich,
			[typeof(LoggerFilterConfiguration)] = (LoggerConfiguration lc) => lc.Filter,
			[typeof(LoggerDestructuringConfiguration)] = (LoggerConfiguration lc) => lc.Destructure
		};

		private readonly IReadOnlyDictionary<string, string> _settings;

		[RequiresUnreferencedCode("Finds accessors by name")]
		public KeyValuePairSettings(IReadOnlyDictionary<string, string> settings)
		{
			_settings = Guard.AgainstNull<IReadOnlyDictionary<string, string>>(settings, "settings");
		}

		public void Configure(LoggerConfiguration loggerConfiguration)
		{
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Expected O, but got Unknown
			Guard.AgainstNull(loggerConfiguration, "loggerConfiguration");
			Dictionary<string, string> val = Enumerable.ToDictionary<KeyValuePair<string, string>, string, string>(Enumerable.Where<KeyValuePair<string, string>>((System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>)_settings, (Func<KeyValuePair<string, string>, bool>)((KeyValuePair<string, string> kvp) => Enumerable.Any<string>((System.Collections.Generic.IEnumerable<string>)_supportedDirectives, (Func<string, bool>)kvp.Key.StartsWith))), (Func<KeyValuePair<string, string>, string>)((KeyValuePair<string, string> kvp) => kvp.Key), (Func<KeyValuePair<string, string>, string>)((KeyValuePair<string, string> kvp) => kvp.Value));
			IReadOnlyDictionary<string, LoggingLevelSwitch> val2 = ParseNamedLevelSwitchDeclarationDirectives((IReadOnlyDictionary<string, string>)(object)val);
			string text = default(string);
			LogEventLevel minimumLevel = default(LogEventLevel);
			if (val.TryGetValue("minimum-level", ref text) && System.Enum.TryParse<LogEventLevel>(text, ref minimumLevel))
			{
				loggerConfiguration.MinimumLevel.Is(minimumLevel);
			}
			System.Collections.Generic.IEnumerator<KeyValuePair<string, string>> enumerator = Enumerable.Where<KeyValuePair<string, string>>((System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>)val, (Func<KeyValuePair<string, string>, bool>)((KeyValuePair<string, string> dir) => dir.Key.StartsWith("enrich:with-property:") && dir.Key.Length > "enrich:with-property:".Length)).GetEnumerator();
			try
			{
				while (((System.Collections.IEnumerator)enumerator).MoveNext())
				{
					KeyValuePair<string, string> current = enumerator.Current;
					string name = current.Key.Substring("enrich:with-property:".Length);
					loggerConfiguration.Enrich.WithProperty(name, current.Value);
				}
			}
			finally
			{
				((System.IDisposable)enumerator)?.Dispose();
			}
			string switchName = default(string);
			if (val.TryGetValue("minimum-level:controlled-by", ref switchName))
			{
				LoggingLevelSwitch levelSwitch = LookUpSwitchByName(switchName, val2);
				loggerConfiguration.MinimumLevel.ControlledBy(levelSwitch);
			}
			enumerator = Enumerable.Where<KeyValuePair<string, string>>((System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>)val, (Func<KeyValuePair<string, string>, bool>)((KeyValuePair<string, string> dir) => dir.Key.StartsWith("minimum-level:override:") && dir.Key.Length > "minimum-level:override:".Length)).GetEnumerator();
			try
			{
				LogEventLevel minimumLevel2 = default(LogEventLevel);
				while (((System.Collections.IEnumerator)enumerator).MoveNext())
				{
					KeyValuePair<string, string> current2 = enumerator.Current;
					string source = current2.Key.Substring("minimum-level:override:".Length);
					if (System.Enum.TryParse<LogEventLevel>(current2.Value, ref minimumLevel2))
					{
						loggerConfiguration.MinimumLevel.Override(source, minimumLevel2);
						continue;
					}
					LoggingLevelSwitch levelSwitch2 = LookUpSwitchByName(current2.Value, val2);
					loggerConfiguration.MinimumLevel.Override(source, levelSwitch2);
				}
			}
			finally
			{
				((System.IDisposable)enumerator)?.Dispose();
			}
			Regex matchCallables = new Regex("^(?<directive>audit-to|write-to|enrich|filter|destructure):(?<method>[A-Za-z0-9]*)(\\.(?<argument>[A-Za-z0-9]*)){0,1}$");
			var val3 = Enumerable.ToList(Enumerable.Select(Enumerable.Select(Enumerable.Where<KeyValuePair<string, string>>((System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>)val, (Func<KeyValuePair<string, string>, bool>)delegate(KeyValuePair<string, string> wt)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				Regex obj2 = matchCallables;
				KeyValuePair<string, string> val5 = wt;
				return obj2.IsMatch(val5.Key);
			}), delegate(KeyValuePair<string, string> wt)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				Regex obj = matchCallables;
				KeyValuePair<string, string> val4 = wt;
				return new
				{
					wt = wt,
					match = obj.Match(val4.Key)
				};
			}), <>h__TransparentIdentifier0 => new
			{
				ReceiverType = CallableDirectiveReceiverTypes[((Capture)<>h__TransparentIdentifier0.match.Groups["directive"]).Value],
				Call = new ConfigurationMethodCall(((Capture)<>h__TransparentIdentifier0.match.Groups["method"]).Value, ((Capture)<>h__TransparentIdentifier0.match.Groups["argument"]).Value, <>h__TransparentIdentifier0.wt.Value)
			}));
			if (!Enumerable.Any((System.Collections.Generic.IEnumerable<<>f__AnonymousType1<System.Type, ConfigurationMethodCall>>)val3))
			{
				return;
			}
			List<Assembly> configurationAssemblies = Enumerable.ToList<Assembly>(LoadConfigurationAssemblies((IReadOnlyDictionary<string, string>)(object)val));
			var enumerator2 = Enumerable.GroupBy((System.Collections.Generic.IEnumerable<<>f__AnonymousType1<System.Type, ConfigurationMethodCall>>)val3, d => d.ReceiverType).GetEnumerator();
			try
			{
				while (((System.Collections.IEnumerator)enumerator2).MoveNext())
				{
					var current3 = enumerator2.Current;
					System.Collections.Generic.IList<MethodInfo> configurationMethods = CallableConfigurationMethodFinder.FindConfigurationMethods((System.Collections.Generic.IEnumerable<Assembly>)configurationAssemblies, current3.Key);
					ApplyDirectives(Enumerable.ToList<IGrouping<string, ConfigurationMethodCall>>(Enumerable.GroupBy<ConfigurationMethodCall, string>(Enumerable.Select((System.Collections.Generic.IEnumerable<<>f__AnonymousType1<System.Type, ConfigurationMethodCall>>)current3, d => d.Call), (Func<ConfigurationMethodCall, string>)((ConfigurationMethodCall call) => call.MethodName))), configurationMethods, CallableDirectiveReceivers[current3.Key].Invoke(loggerConfiguration), val2);
				}
			}
			finally
			{
				((System.IDisposable)enumerator2)?.Dispose();
			}
		}

		internal static bool IsValidSwitchName(string input)
		{
			return Regex.IsMatch(input, "^\\$[A-Za-z]+[A-Za-z0-9]*$");
		}

		[RequiresUnreferencedCode("Reflects against accessors using dynamic string")]
		private static IReadOnlyDictionary<string, LoggingLevelSwitch> ParseNamedLevelSwitchDeclarationDirectives(IReadOnlyDictionary<string, string> directives)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			Regex matchLevelSwitchDeclarations = new Regex("^level-switch:(?<switchName>.*)$");
			var obj = Enumerable.ToList(Enumerable.Select(Enumerable.Select(Enumerable.Where<KeyValuePair<string, string>>((System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>)directives, (Func<KeyValuePair<string, string>, bool>)delegate(KeyValuePair<string, string> wt)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				Regex obj3 = matchLevelSwitchDeclarations;
				KeyValuePair<string, string> val3 = wt;
				return obj3.IsMatch(val3.Key);
			}), delegate(KeyValuePair<string, string> wt)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				Regex obj2 = matchLevelSwitchDeclarations;
				KeyValuePair<string, string> val2 = wt;
				return new
				{
					wt = wt,
					match = obj2.Match(val2.Key)
				};
			}), <>h__TransparentIdentifier0 => new
			{
				SwitchName = ((Capture)<>h__TransparentIdentifier0.match.Groups["switchName"]).Value,
				InitialSwitchLevel = <>h__TransparentIdentifier0.wt.Value
			}));
			Dictionary<string, LoggingLevelSwitch> val = new Dictionary<string, LoggingLevelSwitch>();
			var enumerator = obj.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					var current = enumerator.Current;
					string switchName = current.SwitchName;
					string initialSwitchLevel = current.InitialSwitchLevel;
					if (!IsValidSwitchName(switchName))
					{
						throw new FormatException("\"" + switchName + "\" is not a valid name for a Level Switch declaration. Level switch must be declared with a '$' sign, like \"level-switch:$switchName\"");
					}
					LoggingLevelSwitch loggingLevelSwitch = ((!(initialSwitchLevel == string.Empty)) ? new LoggingLevelSwitch((LogEventLevel)System.Enum.Parse(typeof(LogEventLevel), initialSwitchLevel)) : new LoggingLevelSwitch());
					val.Add(switchName, loggingLevelSwitch);
				}
				return (IReadOnlyDictionary<string, LoggingLevelSwitch>)(object)val;
			}
			finally
			{
				((System.IDisposable)enumerator).Dispose();
			}
		}

		private static LoggingLevelSwitch LookUpSwitchByName(string switchName, IReadOnlyDictionary<string, LoggingLevelSwitch> declaredLevelSwitches)
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			LoggingLevelSwitch result = default(LoggingLevelSwitch);
			if (declaredLevelSwitches.TryGetValue(switchName, ref result))
			{
				return result;
			}
			throw new InvalidOperationException($"No LoggingLevelSwitch has been declared with name \"{switchName}\". You might be missing a key \"{"level-switch"}:{switchName}\"");
		}

		[RequiresUnreferencedCode("Finds accessors by name")]
		[RequiresDynamicCode("Creates arrays of unknown element type")]
		private static object ConvertOrLookupByName(string valueOrSwitchName, System.Type type, IReadOnlyDictionary<string, LoggingLevelSwitch> declaredSwitches)
		{
			if (type == typeof(LoggingLevelSwitch))
			{
				return LookUpSwitchByName(valueOrSwitchName, declaredSwitches);
			}
			return SettingValueConversions.ConvertToType(valueOrSwitchName, type);
		}

		[RequiresUnreferencedCode("Finds accessors by name")]
		[RequiresDynamicCode("Creates arrays of unknown element type")]
		private static void ApplyDirectives(List<IGrouping<string, ConfigurationMethodCall>> directives, System.Collections.Generic.IList<MethodInfo> configurationMethods, object loggerConfigMethod, IReadOnlyDictionary<string, LoggingLevelSwitch> declaredSwitches)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			IReadOnlyDictionary<string, LoggingLevelSwitch> declaredSwitches2 = declaredSwitches;
			Enumerator<IGrouping<string, ConfigurationMethodCall>> enumerator = directives.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					IGrouping<string, ConfigurationMethodCall> directiveInfo = enumerator.Current;
					MethodInfo val = SelectConfigurationMethod((System.Collections.Generic.IEnumerable<MethodInfo>)configurationMethods, directiveInfo.Key, (System.Collections.Generic.IEnumerable<ConfigurationMethodCall>)directiveInfo);
					if (val == (MethodInfo)null)
					{
						SelfLog.WriteLine("Setting \"{0}\" could not be matched to an implementation in any of the loaded assemblies. To use settings from additional assemblies, specify them with the \"serilog:using\" key.", directiveInfo.Key);
						continue;
					}
					List<object> val2 = Enumerable.ToList<object>(Enumerable.Select(Enumerable.Select(Enumerable.Skip<ParameterInfo>((System.Collections.Generic.IEnumerable<ParameterInfo>)((MethodBase)val).GetParameters(), 1), (ParameterInfo p) => new
					{
						p = p,
						directive = Enumerable.FirstOrDefault<ConfigurationMethodCall>((System.Collections.Generic.IEnumerable<ConfigurationMethodCall>)directiveInfo, (Func<ConfigurationMethodCall, bool>)((ConfigurationMethodCall s) => s.ArgumentName == p.Name))
					}), <>h__TransparentIdentifier0 => SuppressConvertCall(<>h__TransparentIdentifier0.directive, <>h__TransparentIdentifier0.p)));
					val2.Insert(0, loggerConfigMethod);
					((MethodBase)val).Invoke((object)null, val2.ToArray());
				}
			}
			finally
			{
				((System.IDisposable)enumerator).Dispose();
			}
			[UnconditionalSuppressMessage("Trimming", "IL2026")]
			[UnconditionalSuppressMessage("AOT", "IL3050")]
			object? SuppressConvertCall(ConfigurationMethodCall? directive, ParameterInfo p)
			{
				if (directive != null)
				{
					return ConvertOrLookupByName(directive.Value, p.ParameterType, declaredSwitches2);
				}
				return p.DefaultValue;
			}
		}

		internal static MethodInfo? SelectConfigurationMethod(System.Collections.Generic.IEnumerable<MethodInfo> candidateMethods, string name, System.Collections.Generic.IEnumerable<ConfigurationMethodCall> suppliedArgumentValues)
		{
			string name2 = name;
			System.Collections.Generic.IEnumerable<ConfigurationMethodCall> suppliedArgumentValues2 = suppliedArgumentValues;
			return Enumerable.FirstOrDefault<MethodInfo>((System.Collections.Generic.IEnumerable<MethodInfo>)Enumerable.OrderByDescending<MethodInfo, int>(Enumerable.Where<MethodInfo>(candidateMethods, (Func<MethodInfo, bool>)((MethodInfo m) => ((MemberInfo)m).Name == name2 && Enumerable.All<ParameterInfo>(Enumerable.Skip<ParameterInfo>((System.Collections.Generic.IEnumerable<ParameterInfo>)((MethodBase)m).GetParameters(), 1), (Func<ParameterInfo, bool>)((ParameterInfo p) => p.HasDefaultValue || Enumerable.Any<ConfigurationMethodCall>(suppliedArgumentValues2, (Func<ConfigurationMethodCall, bool>)((ConfigurationMethodCall s) => s.ArgumentName == p.Name)))))), (Func<MethodInfo, int>)((MethodInfo m) => Enumerable.Count<ParameterInfo>((System.Collections.Generic.IEnumerable<ParameterInfo>)((MethodBase)m).GetParameters(), (Func<ParameterInfo, bool>)((ParameterInfo p) => Enumerable.Any<ConfigurationMethodCall>(suppliedArgumentValues2, (Func<ConfigurationMethodCall, bool>)((ConfigurationMethodCall s) => s.ArgumentName == p.Name)))))));
		}

		internal static System.Collections.Generic.IEnumerable<Assembly> LoadConfigurationAssemblies(IReadOnlyDictionary<string, string> directives)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			List<Assembly> obj = new List<Assembly>();
			obj.Add(typeof(ILogger).Assembly);
			List<Assembly> val = obj;
			System.Collections.Generic.IEnumerator<KeyValuePair<string, string>> enumerator = Enumerable.Where<KeyValuePair<string, string>>((System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>)directives, (Func<KeyValuePair<string, string>, bool>)((KeyValuePair<string, string> d) => d.Key.Equals("using") || d.Key.StartsWith("using:"))).GetEnumerator();
			try
			{
				while (((System.Collections.IEnumerator)enumerator).MoveNext())
				{
					KeyValuePair<string, string> current = enumerator.Current;
					if (string.IsNullOrWhiteSpace(current.Value))
					{
						throw new InvalidOperationException("A zero-length or whitespace assembly name was supplied to a serilog:using configuration statement.");
					}
					AssemblyName val2 = new AssemblyName(current.Value);
					val.Add(Assembly.Load(val2));
				}
			}
			finally
			{
				((System.IDisposable)enumerator)?.Dispose();
			}
			return Enumerable.Distinct<Assembly>((System.Collections.Generic.IEnumerable<Assembly>)val);
		}
	}
	internal class SettingValueConversions
	{
		private static Regex StaticMemberAccessorRegex = new Regex("^(?<shortTypeName>[^:]+)::(?<memberName>[A-Za-z][A-Za-z0-9]*)(?<typeNameExtraQualifiers>[^:]*)$");

		private static Dictionary<System.Type, Func<string, object>> ExtendedTypeConversions;

		[RequiresUnreferencedCode("Finds accessors by name")]
		[RequiresDynamicCode("Creates arrays of unknown element type")]
		public static object? ConvertToType(string value, System.Type toType)
		{
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			System.Type toType2 = toType;
			if (toType2.IsGenericType && toType2.GetGenericTypeDefinition() == typeof(System.Nullable<>))
			{
				if (value == string.Empty)
				{
					return null;
				}
				toType2 = toType2.GenericTypeArguments[0];
			}
			if (toType2.IsEnum)
			{
				return System.Enum.Parse(toType2, value);
			}
			Func<string, object> val = Enumerable.FirstOrDefault<Func<string, object>>(Enumerable.Select<KeyValuePair<System.Type, Func<string, object>>, Func<string, object>>(Enumerable.Where<KeyValuePair<System.Type, Func<string, object>>>((System.Collections.Generic.IEnumerable<KeyValuePair<System.Type, Func<string, object>>>)ExtendedTypeConversions, (Func<KeyValuePair<System.Type, Func<string, object>>, bool>)((KeyValuePair<System.Type, Func<string, object>> t) => t.Key.IsAssignableFrom(toType2))), (Func<KeyValuePair<System.Type, Func<string, object>>, Func<string, object>>)((KeyValuePair<System.Type, Func<string, object>> t) => t.Value)));
			if (val != null)
			{
				return val.Invoke(value);
			}
			if ((toType2.IsInterface || toType2.IsAbstract) && !string.IsNullOrWhiteSpace(value))
			{
				if (TryParseStaticMemberAccessor(value, out string accessorTypeName, out string memberName))
				{
					System.Type type = System.Type.GetType(accessorTypeName, true);
					PropertyInfo val2 = Enumerable.FirstOrDefault<PropertyInfo>((System.Collections.Generic.IEnumerable<PropertyInfo>)type.GetProperties((BindingFlags)24), (Func<PropertyInfo, bool>)((PropertyInfo x) => ((MemberInfo)x).Name == memberName && x.GetMethod != (MethodInfo)null));
					if (val2 != (PropertyInfo)null)
					{
						return val2.GetValue((object)null);
					}
					FieldInfo val3 = Enumerable.FirstOrDefault<FieldInfo>((System.Collections.Generic.IEnumerable<FieldInfo>)type.GetFields((BindingFlags)24), (Func<FieldInfo, bool>)((FieldInfo x) => ((MemberInfo)x).Name == memberName));
					if (val3 != (FieldInfo)null)
					{
						return val3.GetValue((object)null);
					}
					throw new InvalidOperationException($"Could not find a public static property or field with name `{memberName}` on type `{accessorTypeName}`");
				}
				System.Type type2 = System.Type.GetType(value.Trim(), false);
				if (type2 != (System.Type)null)
				{
					ConstructorInfo obj = Enumerable.FirstOrDefault<ConstructorInfo>((System.Collections.Generic.IEnumerable<ConstructorInfo>)type2.GetConstructors((BindingFlags)20), (Func<ConstructorInfo, bool>)delegate(ConstructorInfo ci)
					{
						ParameterInfo[] parameters = ((MethodBase)ci).GetParameters();
						return parameters.Length == 0 || Enumerable.All<ParameterInfo>((System.Collections.Generic.IEnumerable<ParameterInfo>)parameters, (Func<ParameterInfo, bool>)((ParameterInfo pi) => pi.HasDefaultValue));
					});
					if (obj == (ConstructorInfo)null)
					{
						throw new InvalidOperationException("A default constructor was not found on " + type2.FullName + ".");
					}
					object[] array = Enumerable.ToArray<object>(Enumerable.Select<ParameterInfo, object>((System.Collections.Generic.IEnumerable<ParameterInfo>)((MethodBase)obj).GetParameters(), (Func<ParameterInfo, object>)((ParameterInfo pi) => pi.DefaultValue)));
					return obj.Invoke(array);
				}
			}
			if (toType2.IsArray && toType2.GetArrayRank() == 1)
			{
				System.Type elementType = toType2.GetElementType();
				if (string.IsNullOrEmpty(value))
				{
					return System.Array.CreateInstance(elementType, 0);
				}
				string[] array2 = value.Split(',', (StringSplitOptions)0);
				int num = array2.Length;
				System.Array array3 = System.Array.CreateInstance(elementType, array2.Length);
				for (int i = 0; i < num; i++)
				{
					object obj2 = ConvertToType(array2[i], elementType);
					array3.SetValue(obj2, i);
				}
				return array3;
			}
			return Convert.ChangeType((object)value, toType2);
		}

		internal static bool TryParseStaticMemberAccessor(string input, [NotNullWhen(true)] out string? accessorTypeName, [NotNullWhen(true)] out string? memberName)
		{
			if (StaticMemberAccessorRegex.IsMatch(input))
			{
				Match obj = StaticMemberAccessorRegex.Match(input);
				string value = ((Capture)obj.Groups["shortTypeName"]).Value;
				string value2 = ((Capture)obj.Groups["memberName"]).Value;
				string value3 = ((Capture)obj.Groups["typeNameExtraQualifiers"]).Value;
				memberName = value2.Trim();
				accessorTypeName = value.Trim() + value3.TrimEnd();
				return true;
			}
			accessorTypeName = null;
			memberName = null;
			return false;
		}

		static SettingValueConversions()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			Dictionary<System.Type, Func<string, object>> obj = new Dictionary<System.Type, Func<string, object>>();
			obj.Add(typeof(Uri), (Func<string, object>)((string s) => (object)new Uri(s)));
			obj.Add(typeof(TimeSpan), (Func<string, object>)((string s) => TimeSpan.Parse(s)));
			obj.Add(typeof(System.Type), (Func<string, object>)([UnconditionalSuppressMessage("Trimming", "IL2057")] (string s) => System.Type.GetType(s, true)));
			ExtendedTypeConversions = obj;
		}
	}
	internal static class SurrogateConfigurationMethods
	{
		private static readonly Dictionary<System.Type, MethodInfo[]> SurrogateMethodCandidates = Enumerable.ToDictionary<IGrouping<System.Type, MethodInfo>, System.Type, MethodInfo[]>(Enumerable.GroupBy<MethodInfo, System.Type>(IntrospectionExtensions.GetTypeInfo(typeof(SurrogateConfigurationMethods)).DeclaredMethods, (Func<MethodInfo, System.Type>)((MethodInfo m) => Enumerable.First<ParameterInfo>((System.Collections.Generic.IEnumerable<ParameterInfo>)((MethodBase)m).GetParameters()).ParameterType)), (Func<IGrouping<System.Type, MethodInfo>, System.Type>)((IGrouping<System.Type, MethodInfo> g) => g.Key), (Func<IGrouping<System.Type, MethodInfo>, MethodInfo[]>)((IGrouping<System.Type, MethodInfo> g) => Enumerable.ToArray<MethodInfo>((System.Collections.Generic.IEnumerable<MethodInfo>)g)));

		internal static readonly MethodInfo[] WriteTo = SurrogateMethodCandidates[typeof(LoggerSinkConfiguration)];

		internal static readonly MethodInfo[] AuditTo = SurrogateMethodCandidates[typeof(LoggerAuditSinkConfiguration)];

		internal static readonly MethodInfo[] Enrich = SurrogateMethodCandidates[typeof(LoggerEnrichmentConfiguration)];

		internal static readonly MethodInfo[] Destructure = SurrogateMethodCandidates[typeof(LoggerDestructuringConfiguration)];

		internal static readonly MethodInfo[] Filter = SurrogateMethodCandidates[typeof(LoggerFilterConfiguration)];

		internal static LoggerConfiguration Sink(LoggerSinkConfiguration loggerSinkConfiguration, ILogEventSink sink, LogEventLevel restrictedToMinimumLevel = LogEventLevel.Verbose, LoggingLevelSwitch? levelSwitch = null)
		{
			return loggerSinkConfiguration.Sink(sink, restrictedToMinimumLevel, levelSwitch);
		}

		internal static LoggerConfiguration Sink(LoggerAuditSinkConfiguration auditSinkConfiguration, ILogEventSink sink, LogEventLevel restrictedToMinimumLevel = LogEventLevel.Verbose, LoggingLevelSwitch? levelSwitch = null)
		{
			return auditSinkConfiguration.Sink(sink, restrictedToMinimumLevel, levelSwitch);
		}

		internal static LoggerConfiguration With(LoggerEnrichmentConfiguration loggerEnrichmentConfiguration, ILogEventEnricher enricher)
		{
			return loggerEnrichmentConfiguration.With(enricher);
		}

		internal static LoggerConfiguration FromLogContext(LoggerEnrichmentConfiguration loggerEnrichmentConfiguration)
		{
			return loggerEnrichmentConfiguration.FromLogContext();
		}

		internal static LoggerConfiguration With(LoggerDestructuringConfiguration loggerDestructuringConfiguration, IDestructuringPolicy policy)
		{
			return loggerDestructuringConfiguration.With(policy);
		}

		internal static LoggerConfiguration AsScalar(LoggerDestructuringConfiguration loggerDestructuringConfiguration, System.Type scalarType)
		{
			return loggerDestructuringConfiguration.AsScalar(scalarType);
		}

		internal static LoggerConfiguration ToMaximumCollectionCount(LoggerDestructuringConfiguration loggerDestructuringConfiguration, int maximumCollectionCount)
		{
			return loggerDestructuringConfiguration.ToMaximumCollectionCount(maximumCollectionCount);
		}

		internal static LoggerConfiguration ToMaximumDepth(LoggerDestructuringConfiguration loggerDestructuringConfiguration, int maximumDestructuringDepth)
		{
			return loggerDestructuringConfiguration.ToMaximumDepth(maximumDestructuringDepth);
		}

		internal static LoggerConfiguration ToMaximumStringLength(LoggerDestructuringConfiguration loggerDestructuringConfiguration, int maximumStringLength)
		{
			return loggerDestructuringConfiguration.ToMaximumStringLength(maximumStringLength);
		}

		internal static LoggerConfiguration With(LoggerFilterConfiguration loggerFilterConfiguration, ILogEventFilter filter)
		{
			return loggerFilterConfiguration.With(filter);
		}
	}
}
namespace Serilog.Rendering
{
	internal static class Casing
	{
		public static string Format(string value, string? format = null)
		{
			if (!(format == "u"))
			{
				if (format == "w")
				{
					return value.ToLowerInvariant();
				}
				return value;
			}
			return value.ToUpperInvariant();
		}
	}
	internal static class MessageTemplateRenderer
	{
		private static readonly JsonValueFormatter JsonValueFormatter = new JsonValueFormatter("$type");

		[MethodImpl(256)]
		public static void Render(MessageTemplate messageTemplate, IReadOnlyDictionary<string, LogEventPropertyValue> properties, TextWriter output, string? format = null, IFormatProvider? formatProvider = null)
		{
			bool isLiteral = false;
			bool isJson = false;
			if (format != null)
			{
				for (int i = 0; i < format.Length; i++)
				{
					if (format[i] == 'l')
					{
						isLiteral = true;
					}
					else if (format[i] == 'j')
					{
						isJson = true;
					}
				}
			}
			for (int j = 0; j < messageTemplate.TokenArray.Length; j++)
			{
				MessageTemplateToken messageTemplateToken = messageTemplate.TokenArray[j];
				if (messageTemplateToken is TextToken tt)
				{
					RenderTextToken(tt, output);
				}
				else
				{
					RenderPropertyToken((PropertyToken)messageTemplateToken, properties, output, formatProvider, isLiteral, isJson);
				}
			}
		}

		public static void RenderTextToken(TextToken tt, TextWriter output)
		{
			output.Write(tt.Text);
		}

		public static void RenderPropertyToken(PropertyToken pt, IReadOnlyDictionary<string, LogEventPropertyValue> properties, TextWriter output, IFormatProvider? formatProvider, bool isLiteral, bool isJson)
		{
			LogEventPropertyValue propertyValue = default(LogEventPropertyValue);
			if (!properties.TryGetValue(pt.PropertyName, ref propertyValue))
			{
				output.Write(pt.RawText);
				return;
			}
			if (!pt.Alignment.HasValue)
			{
				RenderValue(propertyValue, isLiteral, isJson, output, pt.Format, formatProvider);
				return;
			}
			StringWriter orCreate = ReusableStringWriter.GetOrCreate();
			try
			{
				RenderValue(propertyValue, isLiteral, isJson, (TextWriter)(object)orCreate, pt.Format, formatProvider);
				StringBuilder stringBuilder = orCreate.GetStringBuilder();
				if (stringBuilder.Length >= pt.Alignment.Value.Width)
				{
					output.Write(stringBuilder);
					return;
				}
				Alignment? alignment = pt.Alignment.Value;
				Padding.Apply(output, stringBuilder, in alignment);
			}
			finally
			{
				((System.IDisposable)orCreate)?.Dispose();
			}
		}

		private static void RenderValue(LogEventPropertyValue propertyValue, bool literal, bool json, TextWriter output, string? format, IFormatProvider? formatProvider)
		{
			if (literal && propertyValue is ScalarValue scalarValue && scalarValue.Value is string text)
			{
				output.Write(text);
			}
			else if (json && format == null)
			{
				JsonValueFormatter.Format(propertyValue, output);
			}
			else
			{
				propertyValue.Render(output, format, formatProvider);
			}
		}
	}
	internal static class Padding
	{
		private static readonly char[] PaddingChars = Enumerable.ToArray<char>(Enumerable.Repeat<char>(' ', 80));

		public static void Apply(TextWriter output, string value, in Alignment? alignment)
		{
			if (!alignment.HasValue || value.Length >= alignment.Value.Width)
			{
				output.Write(value);
				return;
			}
			int num = alignment.Value.Width - value.Length;
			if (alignment.Value.Direction == AlignmentDirection.Left)
			{
				output.Write(value);
			}
			if (num <= PaddingChars.Length)
			{
				output.Write(PaddingChars, 0, num);
			}
			else
			{
				output.Write(new string(' ', num));
			}
			if (alignment.Value.Direction == AlignmentDirection.Right)
			{
				output.Write(value);
			}
		}

		public static void Apply(TextWriter output, StringBuilder value, in Alignment? alignment)
		{
			if (!alignment.HasValue || value.Length >= alignment.Value.Width)
			{
				output.Write(value);
				return;
			}
			int num = alignment.Value.Width - value.Length;
			if (alignment.Value.Direction == AlignmentDirection.Left)
			{
				output.Write(value);
			}
			if (num <= PaddingChars.Length)
			{
				output.Write(PaddingChars, 0, num);
			}
			else
			{
				output.Write(new string(' ', num));
			}
			if (alignment.Value.Direction == AlignmentDirection.Right)
			{
				output.Write(value);
			}
		}
	}
	internal class ReusableStringWriter : StringWriter
	{
		[ThreadStatic]
		private static ReusableStringWriter? _pooledWriter;

		internal const int StringBuilderCapacityThreshold = 32768;

		public static StringWriter GetOrCreate(IFormatProvider? formatProvider = null)
		{
			IFormatProvider val = (IFormatProvider)(((object)formatProvider) ?? ((object)CultureInfo.CurrentCulture));
			ReusableStringWriter reusableStringWriter = _pooledWriter;
			_pooledWriter = null;
			if (reusableStringWriter == null || !object.Equals((object)((TextWriter)reusableStringWriter).FormatProvider, (object)val))
			{
				reusableStringWriter = new ReusableStringWriter(formatProvider);
			}
			return (StringWriter)(object)reusableStringWriter;
		}

		private ReusableStringWriter(IFormatProvider? formatProvider)
			: base((IFormatProvider)(((object)formatProvider) ?? ((object)CultureInfo.CurrentCulture)))
		{
		}

		protected override void Dispose(bool disposing)
		{
			if (!disposing)
			{
				((StringWriter)this).Dispose(disposing);
				return;
			}
			StringBuilder stringBuilder = ((StringWriter)this).GetStringBuilder();
			if (stringBuilder.Capacity > 32768)
			{
				((StringWriter)this).Dispose(disposing);
				return;
			}
			stringBuilder.Clear();
			_pooledWriter = this;
		}
	}
}
namespace Serilog.Policies
{
	internal class ByteArrayScalarConversionPolicy : IScalarConversionPolicy
	{
		private const int MaximumByteArrayLength = 1024;

		public bool TryConvertToScalar(object value, [NotNullWhen(true)] out ScalarValue? result)
		{
			if (!(value is byte[] array))
			{
				result = null;
				return false;
			}
			if (array.Length > 1024)
			{
				string value2 = Convert.ToHexString(array, 0, 16) + "... (" + array.Length + " bytes)";
				result = new ScalarValue(value2);
			}
			else
			{
				result = new ScalarValue(Convert.ToHexString(array));
			}
			return true;
		}
	}
	internal sealed class ByteMemoryScalarConversionPolicy : IScalarConversionPolicy
	{
		private const int MaximumByteArrayLength = 1024;

		private const int MaxTake = 16;

		public bool TryConvertToScalar(object value, [NotNullWhen(true)] out ScalarValue? result)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			if (value is ReadOnlyMemory<byte> bytes)
			{
				result = new ScalarValue(ConvertToHexString(bytes));
				return true;
			}
			if (value is System.Memory<byte> memory)
			{
				result = new ScalarValue(ConvertToHexString(System.Memory<byte>.op_Implicit(memory)));
				return true;
			}
			result = null;
			return false;
		}

		private static string ConvertToHexString(ReadOnlyMemory<byte> bytes)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			if (bytes.Length > 1024)
			{
				return ConvertToHexString(bytes.Slice(0, 16), $"... ({bytes.Length} bytes)");
			}
			return ConvertToHexString(bytes, "");
		}

		private unsafe static string ConvertToHexString(ReadOnlyMemory<byte> src, string tail)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return string.Create<ValueTuple<ReadOnlyMemory<byte>, string>>(src.Length * 2 + tail.Length, new ValueTuple<ReadOnlyMemory<byte>, string>(src, tail), (SpanAction<char, ValueTuple<ReadOnlyMemory<byte>, string>>)delegate(System.Span<char> dest, ValueTuple<ReadOnlyMemory<byte>, string> state)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				ValueTuple<ReadOnlyMemory<byte>, string> val = state;
				ReadOnlyMemory<byte> item = val.Item1;
				string item2 = val.Item2;
				System.ReadOnlySpan<byte> span = item.Span;
				int num = default(int);
				for (int i = 0; i < span.Length; i++)
				{
					byte b = *(byte*)span[i];
					if (b.TryFormat(dest, ref num, string.op_Implicit("X2"), (IFormatProvider)null))
					{
						int num2 = num;
						dest = dest.Slice(num2, dest.Length - num2);
					}
				}
				for (int j = 0; j < item2.Length; j++)
				{
					dest[j] = item2[j];
				}
			});
		}
	}
	internal class DelegateDestructuringPolicy : IDestructuringPolicy
	{
		public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, [NotNullWhen(true)] out LogEventPropertyValue? result)
		{
			if (value is System.Delegate @delegate)
			{
				result = new ScalarValue(((object)@delegate).ToString());
				return true;
			}
			result = null;
			return false;
		}
	}
	internal class EnumScalarConversionPolicy : IScalarConversionPolicy
	{
		public bool TryConvertToScalar(object value, [NotNullWhen(true)] out ScalarValue? result)
		{
			if (value is System.Enum)
			{
				result = new ScalarValue(value);
				return true;
			}
			result = null;
			return false;
		}
	}
	internal class PrimitiveScalarConversionPolicy : IScalarConversionPolicy
	{
		public bool TryConvertToScalar(object value, [NotNullWhen(true)] out ScalarValue? result)
		{
			if (value.GetType().IsPrimitive)
			{
				result = new ScalarValue(value);
				return true;
			}
			result = null;
			return false;
		}
	}
	internal class ProjectedDestructuringPolicy : IDestructuringPolicy
	{
		private readonly Func<System.Type, bool> _canApply;

		private readonly Func<object, object> _projection;

		public ProjectedDestructuringPolicy(Func<System.Type, bool> canApply, Func<object, object> projection)
		{
			_canApply = Guard.AgainstNull<Func<System.Type, bool>>(canApply, "canApply");
			_projection = Guard.AgainstNull<Func<object, object>>(projection, "projection");
		}

		public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, [NotNullWhen(true)] out LogEventPropertyValue? result)
		{
			Guard.AgainstNull(value, "value");
			if (!_canApply.Invoke(value.GetType()))
			{
				result = null;
				return false;
			}
			object value2 = _projection.Invoke(value);
			result = propertyValueFactory.CreatePropertyValue(value2, destructureObjects: true);
			return true;
		}
	}
	internal class ReflectionTypesScalarDestructuringPolicy : IDestructuringPolicy
	{
		public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, [NotNullWhen(true)] out LogEventPropertyValue? result)
		{
			if ((value is System.Type || value is MemberInfo) ? true : false)
			{
				result = new ScalarValue(value);
				return true;
			}
			result = null;
			return false;
		}
	}
	internal class SimpleScalarConversionPolicy : IScalarConversionPolicy
	{
		private readonly HashSet<System.Type> _scalarTypes;

		public SimpleScalarConversionPolicy(System.Collections.Generic.IEnumerable<System.Type> scalarTypes)
		{
			HashSet<System.Type> val = new HashSet<System.Type>();
			System.Collections.Generic.IEnumerator<System.Type> enumerator = scalarTypes.GetEnumerator();
			try
			{
				while (((System.Collections.IEnumerator)enumerator).MoveNext())
				{
					System.Type current = enumerator.Current;
					val.Add(current);
				}
			}
			finally
			{
				((System.IDisposable)enumerator)?.Dispose();
			}
			_scalarTypes = val;
		}

		public bool TryConvertToScalar(object value, [NotNullWhen(true)] out ScalarValue? result)
		{
			if (_scalarTypes.Contains(value.GetType()))
			{
				result = new ScalarValue(value);
				return true;
			}
			result = null;
			return false;
		}
	}
}
namespace Serilog.Parsing
{
	public readonly struct Alignment
	{
		[field: CompilerGenerated]
		public AlignmentDirection Direction
		{
			[CompilerGenerated]
			get;
		}

		[field: CompilerGenerated]
		public int Width
		{
			[CompilerGenerated]
			get;
		}

		public Alignment(AlignmentDirection direction, int width)
		{
			Direction = direction;
			Width = width;
		}
	}
	public enum AlignmentDirection
	{
		Left,
		Right
	}
	public enum Destructuring
	{
		Default,
		Stringify,
		Destructure
	}
	public class MessageTemplateParser : IMessageTemplateParser
	{
		[CompilerGenerated]
		private sealed class <Tokenize>d__6 : System.Collections.Generic.IEnumerable<MessageTemplateToken>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<MessageTemplateToken>, System.Collections.IEnumerator, System.IDisposable
		{
			private int <>1__state;

			private MessageTemplateToken <>2__current;

			private int <>l__initialThreadId;

			private string messageTemplate;

			public string <>3__messageTemplate;

			public MessageTemplateParser <>4__this;

			private int <nextIndex>5__2;

			MessageTemplateToken System.Collections.Generic.IEnumerator<MessageTemplateToken>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object System.Collections.IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <Tokenize>d__6(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void System.IDisposable.Dispose()
			{
			}

			private bool MoveNext()
			{
				int num = <>1__state;
				MessageTemplateParser messageTemplateParser = <>4__this;
				int num2;
				MessageTemplateToken messageTemplateToken;
				int num3;
				TextToken textToken;
				switch (num)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					if (messageTemplate.Length == 0)
					{
						<>2__current = EmptyTextToken;
						<>1__state = 1;
						return true;
					}
					<nextIndex>5__2 = 0;
					goto IL_005e;
				case 1:
					<>1__state = -1;
					return false;
				case 2:
					<>1__state = -1;
					goto IL_009d;
				case 3:
					{
						<>1__state = -1;
						goto IL_00f2;
					}
					IL_009d:
					if (<nextIndex>5__2 == messageTemplate.Length)
					{
						return false;
					}
					num2 = <nextIndex>5__2;
					messageTemplateToken = messageTemplateParser.ParsePropertyToken(<nextIndex>5__2, messageTemplate, out <nextIndex>5__2);
					if (num2 < <nextIndex>5__2)
					{
						<>2__current = messageTemplateToken;
						<>1__state = 3;
						return true;
					}
					goto IL_00f2;
					IL_005e:
					num3 = <nextIndex>5__2;
					textToken = ParseTextToken(<nextIndex>5__2, messageTemplate, out <nextIndex>5__2);
					if (<nextIndex>5__2 > num3)
					{
						<>2__current = textToken;
						<>1__state = 2;
						return true;
					}
					goto IL_009d;
					IL_00f2:
					if (<nextIndex>5__2 == messageTemplate.Length)
					{
						return false;
					}
					goto IL_005e;
				}
			}

			bool System.Collections.IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void System.Collections.IEnumerator.Reset()
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			System.Collections.Generic.IEnumerator<MessageTemplateToken> System.Collections.Generic.IEnumerable<MessageTemplateToken>.GetEnumerator()
			{
				<Tokenize>d__6 <Tokenize>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					<Tokenize>d__ = this;
				}
				else
				{
					<Tokenize>d__ = new <Tokenize>d__6(0)
					{
						<>4__this = <>4__this
					};
				}
				<Tokenize>d__.messageTemplate = <>3__messageTemplate;
				return <Tokenize>d__;
			}

			[DebuggerHidden]
			System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
			{
				return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<MessageTemplateToken>)this).GetEnumerator();
			}
		}

		private static readonly bool DefaultAcceptDottedPropertyNames;

		private static readonly TextToken EmptyTextToken;

		private readonly bool _acceptDottedPropertyNames;

		public MessageTemplateParser()
			: this(DefaultAcceptDottedPropertyNames)
		{
		}

		internal MessageTemplateParser(bool acceptDottedPropertyNames)
		{
			_acceptDottedPropertyNames = acceptDottedPropertyNames;
		}

		public MessageTemplate Parse(string messageTemplate)
		{
			Guard.AgainstNull(messageTemplate, "messageTemplate");
			return new MessageTemplate(messageTemplate, Tokenize(messageTemplate));
		}

		[IteratorStateMachine(typeof(<Tokenize>d__6))]
		private System.Collections.Generic.IEnumerable<MessageTemplateToken> Tokenize(string messageTemplate)
		{
			if (messageTemplate.Length == 0)
			{
				yield return EmptyTextToken;
				yield break;
			}
			int nextIndex = 0;
			do
			{
				int num = nextIndex;
				TextToken textToken = ParseTextToken(nextIndex, messageTemplate, out nextIndex);
				if (nextIndex > num)
				{
					yield return textToken;
				}
				if (nextIndex == messageTemplate.Length)
				{
					break;
				}
				int num2 = nextIndex;
				MessageTemplateToken messageTemplateToken = ParsePropertyToken(nextIndex, messageTemplate, out nextIndex);
				if (num2 < nextIndex)
				{
					yield return messageTemplateToken;
				}
			}
			while (nextIndex != messageTemplate.Length);
		}

		private MessageTemplateToken ParsePropertyToken(int startAt, string messageTemplate, out int next)
		{
			int num = startAt;
			startAt++;
			startAt = messageTemplate.IndexOf('}', startAt);
			if (startAt == -1)
			{
				next = messageTemplate.Length;
				return new TextToken(messageTemplate.Substring(num));
			}
			next = startAt + 1;
			string text = messageTemplate.Substring(num, next - num);
			string text2 = text.Substring(1, next - (num + 2));
			if (text2.Length == 0)
			{
				return new TextToken(text);
			}
			if (!TrySplitTagContent(text2, out string propertyNameAndDestructuring, out string format, out string alignment))
			{
				return new TextToken(text);
			}
			string text3 = propertyNameAndDestructuring;
			Destructuring destructuring = Destructuring.Default;
			if (text3.Length != 0 && TryGetDestructuringHint(text3[0], out destructuring))
			{
				text3 = text3.Substring(1);
			}
			if (text3.Length == 0)
			{
				return new TextToken(text);
			}
			foreach (char c in text3)
			{
				if (!IsValidInPropertyName(c))
				{
					return new TextToken(text);
				}
			}
			if (format != null)
			{
				for (int j = 0; j < format.Length; j++)
				{
					if (!IsValidInFormat(format[j]))
					{
						return new TextToken(text);
					}
				}
			}
			Alignment? alignment2 = null;
			if (alignment != null)
			{
				if (alignment[0] == '+')
				{
					return new TextToken(text);
				}
				int num2 = default(int);
				if (!int.TryParse(alignment, (NumberStyles)4, (IFormatProvider)(object)CultureInfo.InvariantCulture, ref num2))
				{
					return new TextToken(text);
				}
				AlignmentDirection direction = ((alignment[0] != '-') ? AlignmentDirection.Right : AlignmentDirection.Left);
				alignment2 = new Alignment(direction, Math.Abs(num2));
			}
			return new PropertyToken(text3, text, format, in alignment2, destructuring);
		}

		private static bool TrySplitTagContent(string tagContent, [NotNullWhen(true)] out string? propertyNameAndDestructuring, out string? format, out string? alignment)
		{
			int num = tagContent.IndexOf(':');
			int num2 = tagContent.IndexOf(',');
			if (num == -1 && num2 == -1)
			{
				propertyNameAndDestructuring = tagContent;
				format = null;
				alignment = null;
				return true;
			}
			if (num2

GDWeave/core/Serilog.Sinks.Console.dll

Decompiled 3 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using Serilog.Configuration;
using Serilog.Core;
using Serilog.Data;
using Serilog.Events;
using Serilog.Formatting;
using Serilog.Formatting.Json;
using Serilog.Parsing;
using Serilog.Sinks.SystemConsole;
using Serilog.Sinks.SystemConsole.Formatting;
using Serilog.Sinks.SystemConsole.Output;
using Serilog.Sinks.SystemConsole.Platform;
using Serilog.Sinks.SystemConsole.Rendering;
using Serilog.Sinks.SystemConsole.Themes;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(/*Could not decode attribute arguments.*/)]
[assembly: CLSCompliant(true)]
[assembly: InternalsVisibleTo("Serilog.Sinks.Console.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100fb8d13fd344a1c6fe0fe83ef33c1080bf30690765bc6eb0df26ebfdf8f21670c64265b30db09f73a0dea5b3db4c9d18dbf6d5a25af5ce9016f281014d79dc3b4201ac646c451830fc7e61a2dfd633d34c39f87b81894191652df5ac63cc40c77f3542f702bda692e6e8a9158353df189007a49da0f3cfd55eb250066b19485ec")]
[assembly: TargetFramework(".NETCoreApp,Version=v8.0", FrameworkDisplayName = ".NET 8.0")]
[assembly: AssemblyCompany("Serilog Contributors")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("A Serilog sink that writes log events to the console/terminal.")]
[assembly: AssemblyFileVersion("6.0.0.0")]
[assembly: AssemblyInformationalVersion("6.0.0-main-4c9a7b6+4c9a7b6946dfd2d7f07a792c40bb3d46af835ee9")]
[assembly: AssemblyProduct("Serilog.Sinks.Console")]
[assembly: AssemblyTitle("Serilog.Sinks.Console")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/serilog/serilog-sinks-console")]
[assembly: AssemblyVersion("6.0.0.0")]
[module: RefSafetyRules(11)]
namespace Serilog
{
	public static class ConsoleAuditLoggerConfigurationExtensions
	{
		public static LoggerConfiguration Console(this LoggerAuditSinkConfiguration sinkConfiguration, LogEventLevel restrictedToMinimumLevel = 0, string outputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", IFormatProvider? formatProvider = null, LoggingLevelSwitch? levelSwitch = null, LogEventLevel? standardErrorFromLevel = null, ConsoleTheme? theme = null, bool applyThemeToRedirectedOutput = false, object? syncRoot = null)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			if (sinkConfiguration == null)
			{
				throw new ArgumentNullException("sinkConfiguration");
			}
			if (outputTemplate == null)
			{
				throw new ArgumentNullException("outputTemplate");
			}
			ConsoleTheme theme2 = (((!applyThemeToRedirectedOutput && (Console.IsOutputRedirected || Console.IsErrorRedirected)) || !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("NO_COLOR"))) ? ConsoleTheme.None : (theme ?? SystemConsoleThemes.Literate));
			if (syncRoot == null)
			{
				syncRoot = ConsoleLoggerConfigurationExtensions.DefaultSyncRoot;
			}
			OutputTemplateRenderer formatter = new OutputTemplateRenderer(theme2, outputTemplate, formatProvider);
			return sinkConfiguration.Sink((ILogEventSink)(object)new ConsoleSink(theme2, (ITextFormatter)(object)formatter, standardErrorFromLevel, syncRoot), restrictedToMinimumLevel, levelSwitch);
		}

		public static LoggerConfiguration Console(this LoggerAuditSinkConfiguration sinkConfiguration, ITextFormatter formatter, LogEventLevel restrictedToMinimumLevel = 0, LoggingLevelSwitch? levelSwitch = null, LogEventLevel? standardErrorFromLevel = null, object? syncRoot = null)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			if (sinkConfiguration == null)
			{
				throw new ArgumentNullException("sinkConfiguration");
			}
			if (formatter == null)
			{
				throw new ArgumentNullException("formatter");
			}
			if (syncRoot == null)
			{
				syncRoot = ConsoleLoggerConfigurationExtensions.DefaultSyncRoot;
			}
			return sinkConfiguration.Sink((ILogEventSink)(object)new ConsoleSink(ConsoleTheme.None, formatter, standardErrorFromLevel, syncRoot), restrictedToMinimumLevel, levelSwitch);
		}
	}
	public static class ConsoleLoggerConfigurationExtensions
	{
		internal static readonly object DefaultSyncRoot = new object();

		internal const string DefaultConsoleOutputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}";

		public static LoggerConfiguration Console(this LoggerSinkConfiguration sinkConfiguration, LogEventLevel restrictedToMinimumLevel = 0, string outputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", IFormatProvider? formatProvider = null, LoggingLevelSwitch? levelSwitch = null, LogEventLevel? standardErrorFromLevel = null, ConsoleTheme? theme = null, bool applyThemeToRedirectedOutput = false, object? syncRoot = null)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			if (sinkConfiguration == null)
			{
				throw new ArgumentNullException("sinkConfiguration");
			}
			if (outputTemplate == null)
			{
				throw new ArgumentNullException("outputTemplate");
			}
			ConsoleTheme theme2 = (((!applyThemeToRedirectedOutput && (Console.IsOutputRedirected || Console.IsErrorRedirected)) || !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("NO_COLOR"))) ? ConsoleTheme.None : (theme ?? SystemConsoleThemes.Literate));
			if (syncRoot == null)
			{
				syncRoot = DefaultSyncRoot;
			}
			OutputTemplateRenderer formatter = new OutputTemplateRenderer(theme2, outputTemplate, formatProvider);
			return sinkConfiguration.Sink((ILogEventSink)(object)new ConsoleSink(theme2, (ITextFormatter)(object)formatter, standardErrorFromLevel, syncRoot), restrictedToMinimumLevel, levelSwitch);
		}

		public static LoggerConfiguration Console(this LoggerSinkConfiguration sinkConfiguration, ITextFormatter formatter, LogEventLevel restrictedToMinimumLevel = 0, LoggingLevelSwitch? levelSwitch = null, LogEventLevel? standardErrorFromLevel = null, object? syncRoot = null)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			if (sinkConfiguration == null)
			{
				throw new ArgumentNullException("sinkConfiguration");
			}
			if (formatter == null)
			{
				throw new ArgumentNullException("formatter");
			}
			if (syncRoot == null)
			{
				syncRoot = DefaultSyncRoot;
			}
			return sinkConfiguration.Sink((ILogEventSink)(object)new ConsoleSink(ConsoleTheme.None, formatter, standardErrorFromLevel, syncRoot), restrictedToMinimumLevel, levelSwitch);
		}
	}
}
namespace Serilog.Sinks.SystemConsole
{
	internal class ConsoleSink : ILogEventSink
	{
		private readonly LogEventLevel? _standardErrorFromLevel;

		private readonly ConsoleTheme _theme;

		private readonly ITextFormatter _formatter;

		private readonly object _syncRoot;

		private const int DefaultWriteBufferCapacity = 256;

		static ConsoleSink()
		{
			WindowsConsole.EnableVirtualTerminalProcessing();
		}

		public ConsoleSink(ConsoleTheme theme, ITextFormatter formatter, LogEventLevel? standardErrorFromLevel, object syncRoot)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			_standardErrorFromLevel = standardErrorFromLevel;
			_theme = theme ?? throw new ArgumentNullException("theme");
			_formatter = formatter;
			_syncRoot = syncRoot ?? throw new ArgumentNullException("syncRoot");
		}

		public void Emit(LogEvent logEvent)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			TextWriter val = SelectOutputStream(logEvent.Level);
			if (_theme.CanBuffer)
			{
				StringWriter val2 = new StringWriter(new StringBuilder(256));
				_formatter.Format(logEvent, (TextWriter)(object)val2);
				string text = ((object)val2).ToString();
				lock (_syncRoot)
				{
					val.Write(text);
					val.Flush();
					return;
				}
			}
			lock (_syncRoot)
			{
				_formatter.Format(logEvent, val);
				val.Flush();
			}
		}

		private TextWriter SelectOutputStream(LogEventLevel logEventLevel)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			if (!_standardErrorFromLevel.HasValue)
			{
				return Console.Out;
			}
			if (!(logEventLevel < _standardErrorFromLevel))
			{
				return Console.Error;
			}
			return Console.Out;
		}
	}
}
namespace Serilog.Sinks.SystemConsole.Themes
{
	public class AnsiConsoleTheme : ConsoleTheme
	{
		private readonly IReadOnlyDictionary<ConsoleThemeStyle, string> _styles;

		private const string AnsiStyleReset = "\u001b[0m";

		[field: CompilerGenerated]
		public static AnsiConsoleTheme Code
		{
			[CompilerGenerated]
			get;
		} = AnsiConsoleThemes.Code;


		[field: CompilerGenerated]
		public static AnsiConsoleTheme Grayscale
		{
			[CompilerGenerated]
			get;
		} = AnsiConsoleThemes.Grayscale;


		[field: CompilerGenerated]
		public static AnsiConsoleTheme Literate
		{
			[CompilerGenerated]
			get;
		} = AnsiConsoleThemes.Literate;


		[field: CompilerGenerated]
		public static AnsiConsoleTheme Sixteen
		{
			[CompilerGenerated]
			get;
		} = AnsiConsoleThemes.Sixteen;


		public override bool CanBuffer => true;

		[field: CompilerGenerated]
		protected override int ResetCharCount
		{
			[CompilerGenerated]
			get;
		} = "\u001b[0m".Length;


		public AnsiConsoleTheme(IReadOnlyDictionary<ConsoleThemeStyle, string> styles)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (styles == null)
			{
				throw new ArgumentNullException("styles");
			}
			_styles = (IReadOnlyDictionary<ConsoleThemeStyle, string>)(object)Enumerable.ToDictionary<KeyValuePair<ConsoleThemeStyle, string>, ConsoleThemeStyle, string>((global::System.Collections.Generic.IEnumerable<KeyValuePair<ConsoleThemeStyle, string>>)styles, (Func<KeyValuePair<ConsoleThemeStyle, string>, ConsoleThemeStyle>)((KeyValuePair<ConsoleThemeStyle, string> kv) => kv.Key), (Func<KeyValuePair<ConsoleThemeStyle, string>, string>)((KeyValuePair<ConsoleThemeStyle, string> kv) => kv.Value));
		}

		public override int Set(TextWriter output, ConsoleThemeStyle style)
		{
			string text = default(string);
			if (_styles.TryGetValue(style, ref text))
			{
				output.Write(text);
				return text.Length;
			}
			return 0;
		}

		public override void Reset(TextWriter output)
		{
			output.Write("\u001b[0m");
		}
	}
	internal static class AnsiConsoleThemes
	{
		[field: CompilerGenerated]
		public static AnsiConsoleTheme Literate
		{
			[CompilerGenerated]
			get;
		} = new AnsiConsoleTheme((IReadOnlyDictionary<ConsoleThemeStyle, string>)(object)new Dictionary<ConsoleThemeStyle, string>
		{
			[ConsoleThemeStyle.Text] = "\u001b[38;5;0015m",
			[ConsoleThemeStyle.SecondaryText] = "\u001b[38;5;0007m",
			[ConsoleThemeStyle.TertiaryText] = "\u001b[38;5;0008m",
			[ConsoleThemeStyle.Invalid] = "\u001b[38;5;0011m",
			[ConsoleThemeStyle.Null] = "\u001b[38;5;0027m",
			[ConsoleThemeStyle.Name] = "\u001b[38;5;0007m",
			[ConsoleThemeStyle.String] = "\u001b[38;5;0045m",
			[ConsoleThemeStyle.Number] = "\u001b[38;5;0200m",
			[ConsoleThemeStyle.Boolean] = "\u001b[38;5;0027m",
			[ConsoleThemeStyle.Scalar] = "\u001b[38;5;0085m",
			[ConsoleThemeStyle.LevelVerbose] = "\u001b[38;5;0007m",
			[ConsoleThemeStyle.LevelDebug] = "\u001b[38;5;0007m",
			[ConsoleThemeStyle.LevelInformation] = "\u001b[38;5;0015m",
			[ConsoleThemeStyle.LevelWarning] = "\u001b[38;5;0011m",
			[ConsoleThemeStyle.LevelError] = "\u001b[38;5;0015m\u001b[48;5;0196m",
			[ConsoleThemeStyle.LevelFatal] = "\u001b[38;5;0015m\u001b[48;5;0196m"
		});


		[field: CompilerGenerated]
		public static AnsiConsoleTheme Grayscale
		{
			[CompilerGenerated]
			get;
		} = new AnsiConsoleTheme((IReadOnlyDictionary<ConsoleThemeStyle, string>)(object)new Dictionary<ConsoleThemeStyle, string>
		{
			[ConsoleThemeStyle.Text] = "\u001b[37;1m",
			[ConsoleThemeStyle.SecondaryText] = "\u001b[37m",
			[ConsoleThemeStyle.TertiaryText] = "\u001b[30;1m",
			[ConsoleThemeStyle.Invalid] = "\u001b[37;1m\u001b[47m",
			[ConsoleThemeStyle.Null] = "\u001b[1m\u001b[37;1m",
			[ConsoleThemeStyle.Name] = "\u001b[37m",
			[ConsoleThemeStyle.String] = "\u001b[1m\u001b[37;1m",
			[ConsoleThemeStyle.Number] = "\u001b[1m\u001b[37;1m",
			[ConsoleThemeStyle.Boolean] = "\u001b[1m\u001b[37;1m",
			[ConsoleThemeStyle.Scalar] = "\u001b[1m\u001b[37;1m",
			[ConsoleThemeStyle.LevelVerbose] = "\u001b[30;1m",
			[ConsoleThemeStyle.LevelDebug] = "\u001b[30;1m",
			[ConsoleThemeStyle.LevelInformation] = "\u001b[37;1m",
			[ConsoleThemeStyle.LevelWarning] = "\u001b[37;1m\u001b[47m",
			[ConsoleThemeStyle.LevelError] = "\u001b[30m\u001b[47m",
			[ConsoleThemeStyle.LevelFatal] = "\u001b[30m\u001b[47m"
		});


		[field: CompilerGenerated]
		public static AnsiConsoleTheme Code
		{
			[CompilerGenerated]
			get;
		} = new AnsiConsoleTheme((IReadOnlyDictionary<ConsoleThemeStyle, string>)(object)new Dictionary<ConsoleThemeStyle, string>
		{
			[ConsoleThemeStyle.Text] = "\u001b[38;5;0253m",
			[ConsoleThemeStyle.SecondaryText] = "\u001b[38;5;0246m",
			[ConsoleThemeStyle.TertiaryText] = "\u001b[38;5;0242m",
			[ConsoleThemeStyle.Invalid] = "\u001b[33;1m",
			[ConsoleThemeStyle.Null] = "\u001b[38;5;0038m",
			[ConsoleThemeStyle.Name] = "\u001b[38;5;0081m",
			[ConsoleThemeStyle.String] = "\u001b[38;5;0216m",
			[ConsoleThemeStyle.Number] = "\u001b[38;5;151m",
			[ConsoleThemeStyle.Boolean] = "\u001b[38;5;0038m",
			[ConsoleThemeStyle.Scalar] = "\u001b[38;5;0079m",
			[ConsoleThemeStyle.LevelVerbose] = "\u001b[37m",
			[ConsoleThemeStyle.LevelDebug] = "\u001b[37m",
			[ConsoleThemeStyle.LevelInformation] = "\u001b[37;1m",
			[ConsoleThemeStyle.LevelWarning] = "\u001b[38;5;0229m",
			[ConsoleThemeStyle.LevelError] = "\u001b[38;5;0197m\u001b[48;5;0238m",
			[ConsoleThemeStyle.LevelFatal] = "\u001b[38;5;0197m\u001b[48;5;0238m"
		});


		[field: CompilerGenerated]
		public static AnsiConsoleTheme Sixteen
		{
			[CompilerGenerated]
			get;
		} = new AnsiConsoleTheme((IReadOnlyDictionary<ConsoleThemeStyle, string>)(object)new Dictionary<ConsoleThemeStyle, string>
		{
			[ConsoleThemeStyle.Text] = "",
			[ConsoleThemeStyle.SecondaryText] = "",
			[ConsoleThemeStyle.TertiaryText] = "",
			[ConsoleThemeStyle.Invalid] = "\u001b[33m",
			[ConsoleThemeStyle.Null] = "\u001b[34m",
			[ConsoleThemeStyle.Name] = "",
			[ConsoleThemeStyle.String] = "\u001b[36m",
			[ConsoleThemeStyle.Number] = "\u001b[35m",
			[ConsoleThemeStyle.Boolean] = "\u001b[34m",
			[ConsoleThemeStyle.Scalar] = "\u001b[32m",
			[ConsoleThemeStyle.LevelVerbose] = "",
			[ConsoleThemeStyle.LevelDebug] = "\u001b[1m",
			[ConsoleThemeStyle.LevelInformation] = "\u001b[36;1m",
			[ConsoleThemeStyle.LevelWarning] = "\u001b[33;1m",
			[ConsoleThemeStyle.LevelError] = "\u001b[31;1m",
			[ConsoleThemeStyle.LevelFatal] = "\u001b[31;1m"
		});

	}
	internal static class AnsiEscapeSequence
	{
		public const string Unthemed = "";

		public const string Reset = "\u001b[0m";

		public const string Bold = "\u001b[1m";

		public const string Black = "\u001b[30m";

		public const string Red = "\u001b[31m";

		public const string Green = "\u001b[32m";

		public const string Yellow = "\u001b[33m";

		public const string Blue = "\u001b[34m";

		public const string Magenta = "\u001b[35m";

		public const string Cyan = "\u001b[36m";

		public const string White = "\u001b[37m";

		public const string BrightBlack = "\u001b[30;1m";

		public const string BrightRed = "\u001b[31;1m";

		public const string BrightGreen = "\u001b[32;1m";

		public const string BrightYellow = "\u001b[33;1m";

		public const string BrightBlue = "\u001b[34;1m";

		public const string BrightMagenta = "\u001b[35;1m";

		public const string BrightCyan = "\u001b[36;1m";

		public const string BrightWhite = "\u001b[37;1m";
	}
	public abstract class ConsoleTheme
	{
		[field: CompilerGenerated]
		public static ConsoleTheme None
		{
			[CompilerGenerated]
			get;
		} = new EmptyConsoleTheme();


		public abstract bool CanBuffer { get; }

		protected abstract int ResetCharCount { get; }

		public abstract int Set(TextWriter output, ConsoleThemeStyle style);

		public abstract void Reset(TextWriter output);

		internal StyleReset Apply(TextWriter output, ConsoleThemeStyle style, ref int invisibleCharacterCount)
		{
			invisibleCharacterCount += Set(output, style);
			invisibleCharacterCount += ResetCharCount;
			return new StyleReset(this, output);
		}
	}
	public enum ConsoleThemeStyle
	{
		Text = 0,
		SecondaryText = 1,
		TertiaryText = 2,
		Invalid = 3,
		Null = 4,
		Name = 5,
		String = 6,
		Number = 7,
		Boolean = 8,
		Scalar = 9,
		[Obsolete("Use ConsoleThemeStyle.Scalar instead")]
		[EditorBrowsable(/*Could not decode attribute arguments.*/)]
		Object = 9,
		LevelVerbose = 10,
		LevelDebug = 11,
		LevelInformation = 12,
		LevelWarning = 13,
		LevelError = 14,
		LevelFatal = 15
	}
	internal class EmptyConsoleTheme : ConsoleTheme
	{
		public override bool CanBuffer => true;

		[field: CompilerGenerated]
		protected override int ResetCharCount
		{
			[CompilerGenerated]
			get;
		}

		public override int Set(TextWriter output, ConsoleThemeStyle style)
		{
			return 0;
		}

		public override void Reset(TextWriter output)
		{
		}
	}
	internal struct StyleReset : global::System.IDisposable
	{
		private readonly ConsoleTheme _theme;

		private readonly TextWriter _output;

		public StyleReset(ConsoleTheme theme, TextWriter output)
		{
			_theme = theme;
			_output = output;
		}

		public void Dispose()
		{
			_theme.Reset(_output);
		}
	}
	public class SystemConsoleTheme : ConsoleTheme
	{
		[field: CompilerGenerated]
		public static SystemConsoleTheme Grayscale
		{
			[CompilerGenerated]
			get;
		} = SystemConsoleThemes.Grayscale;


		[field: CompilerGenerated]
		public static SystemConsoleTheme Literate
		{
			[CompilerGenerated]
			get;
		} = SystemConsoleThemes.Literate;


		[field: CompilerGenerated]
		public static SystemConsoleTheme Colored
		{
			[CompilerGenerated]
			get;
		} = SystemConsoleThemes.Colored;


		[field: CompilerGenerated]
		public IReadOnlyDictionary<ConsoleThemeStyle, SystemConsoleThemeStyle> Styles
		{
			[CompilerGenerated]
			get;
		}

		public override bool CanBuffer => false;

		[field: CompilerGenerated]
		protected override int ResetCharCount
		{
			[CompilerGenerated]
			get;
		}

		public SystemConsoleTheme(IReadOnlyDictionary<ConsoleThemeStyle, SystemConsoleThemeStyle> styles)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (styles == null)
			{
				throw new ArgumentNullException("styles");
			}
			Styles = (IReadOnlyDictionary<ConsoleThemeStyle, SystemConsoleThemeStyle>)(object)Enumerable.ToDictionary<KeyValuePair<ConsoleThemeStyle, SystemConsoleThemeStyle>, ConsoleThemeStyle, SystemConsoleThemeStyle>((global::System.Collections.Generic.IEnumerable<KeyValuePair<ConsoleThemeStyle, SystemConsoleThemeStyle>>)styles, (Func<KeyValuePair<ConsoleThemeStyle, SystemConsoleThemeStyle>, ConsoleThemeStyle>)((KeyValuePair<ConsoleThemeStyle, SystemConsoleThemeStyle> kv) => kv.Key), (Func<KeyValuePair<ConsoleThemeStyle, SystemConsoleThemeStyle>, SystemConsoleThemeStyle>)((KeyValuePair<ConsoleThemeStyle, SystemConsoleThemeStyle> kv) => kv.Value));
		}

		public override int Set(TextWriter output, ConsoleThemeStyle style)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			SystemConsoleThemeStyle systemConsoleThemeStyle = default(SystemConsoleThemeStyle);
			if (Styles.TryGetValue(style, ref systemConsoleThemeStyle))
			{
				if (systemConsoleThemeStyle.Foreground.HasValue)
				{
					Console.ForegroundColor = systemConsoleThemeStyle.Foreground.Value;
				}
				if (systemConsoleThemeStyle.Background.HasValue)
				{
					Console.BackgroundColor = systemConsoleThemeStyle.Background.Value;
				}
			}
			return 0;
		}

		public override void Reset(TextWriter output)
		{
			Console.ResetColor();
		}
	}
	internal static class SystemConsoleThemes
	{
		[field: CompilerGenerated]
		public static SystemConsoleTheme Literate
		{
			[CompilerGenerated]
			get;
		} = new SystemConsoleTheme((IReadOnlyDictionary<ConsoleThemeStyle, SystemConsoleThemeStyle>)(object)new Dictionary<ConsoleThemeStyle, SystemConsoleThemeStyle>
		{
			[ConsoleThemeStyle.Text] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15
			},
			[ConsoleThemeStyle.SecondaryText] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)7
			},
			[ConsoleThemeStyle.TertiaryText] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)8
			},
			[ConsoleThemeStyle.Invalid] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)14
			},
			[ConsoleThemeStyle.Null] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)9
			},
			[ConsoleThemeStyle.Name] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)7
			},
			[ConsoleThemeStyle.String] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)11
			},
			[ConsoleThemeStyle.Number] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)13
			},
			[ConsoleThemeStyle.Boolean] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)9
			},
			[ConsoleThemeStyle.Scalar] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)10
			},
			[ConsoleThemeStyle.LevelVerbose] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)7
			},
			[ConsoleThemeStyle.LevelDebug] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)7
			},
			[ConsoleThemeStyle.LevelInformation] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15
			},
			[ConsoleThemeStyle.LevelWarning] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)14
			},
			[ConsoleThemeStyle.LevelError] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15,
				Background = (ConsoleColor)12
			},
			[ConsoleThemeStyle.LevelFatal] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15,
				Background = (ConsoleColor)12
			}
		});


		[field: CompilerGenerated]
		public static SystemConsoleTheme Grayscale
		{
			[CompilerGenerated]
			get;
		} = new SystemConsoleTheme((IReadOnlyDictionary<ConsoleThemeStyle, SystemConsoleThemeStyle>)(object)new Dictionary<ConsoleThemeStyle, SystemConsoleThemeStyle>
		{
			[ConsoleThemeStyle.Text] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15
			},
			[ConsoleThemeStyle.SecondaryText] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)7
			},
			[ConsoleThemeStyle.TertiaryText] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)8
			},
			[ConsoleThemeStyle.Invalid] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15,
				Background = (ConsoleColor)8
			},
			[ConsoleThemeStyle.Null] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15
			},
			[ConsoleThemeStyle.Name] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)7
			},
			[ConsoleThemeStyle.String] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15
			},
			[ConsoleThemeStyle.Number] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15
			},
			[ConsoleThemeStyle.Boolean] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15
			},
			[ConsoleThemeStyle.Scalar] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15
			},
			[ConsoleThemeStyle.LevelVerbose] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)8
			},
			[ConsoleThemeStyle.LevelDebug] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)8
			},
			[ConsoleThemeStyle.LevelInformation] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15
			},
			[ConsoleThemeStyle.LevelWarning] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15,
				Background = (ConsoleColor)8
			},
			[ConsoleThemeStyle.LevelError] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)0,
				Background = (ConsoleColor)15
			},
			[ConsoleThemeStyle.LevelFatal] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)0,
				Background = (ConsoleColor)15
			}
		});


		[field: CompilerGenerated]
		public static SystemConsoleTheme Colored
		{
			[CompilerGenerated]
			get;
		} = new SystemConsoleTheme((IReadOnlyDictionary<ConsoleThemeStyle, SystemConsoleThemeStyle>)(object)new Dictionary<ConsoleThemeStyle, SystemConsoleThemeStyle>
		{
			[ConsoleThemeStyle.Text] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)7
			},
			[ConsoleThemeStyle.SecondaryText] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)8
			},
			[ConsoleThemeStyle.TertiaryText] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)8
			},
			[ConsoleThemeStyle.Invalid] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)14
			},
			[ConsoleThemeStyle.Null] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15
			},
			[ConsoleThemeStyle.Name] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15
			},
			[ConsoleThemeStyle.String] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15
			},
			[ConsoleThemeStyle.Number] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15
			},
			[ConsoleThemeStyle.Boolean] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15
			},
			[ConsoleThemeStyle.Scalar] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15
			},
			[ConsoleThemeStyle.LevelVerbose] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)7,
				Background = (ConsoleColor)8
			},
			[ConsoleThemeStyle.LevelDebug] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15,
				Background = (ConsoleColor)8
			},
			[ConsoleThemeStyle.LevelInformation] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15,
				Background = (ConsoleColor)9
			},
			[ConsoleThemeStyle.LevelWarning] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)8,
				Background = (ConsoleColor)14
			},
			[ConsoleThemeStyle.LevelError] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15,
				Background = (ConsoleColor)12
			},
			[ConsoleThemeStyle.LevelFatal] = new SystemConsoleThemeStyle
			{
				Foreground = (ConsoleColor)15,
				Background = (ConsoleColor)12
			}
		});

	}
	public struct SystemConsoleThemeStyle
	{
		public ConsoleColor? Foreground;

		public ConsoleColor? Background;
	}
}
namespace Serilog.Sinks.SystemConsole.Rendering
{
	internal static class AlignmentExtensions
	{
		public static Alignment Widen(this Alignment alignment, int amount)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			return new Alignment(((Alignment)(ref alignment)).Direction, ((Alignment)(ref alignment)).Width + amount);
		}
	}
	internal static class Casing
	{
		public static string Format(string value, string? format = null)
		{
			if (!(format == "u"))
			{
				if (format == "w")
				{
					return value.ToLowerInvariant();
				}
				return value;
			}
			return value.ToUpperInvariant();
		}
	}
	internal static class Padding
	{
		private static readonly char[] PaddingChars = new string(' ', 80).ToCharArray();

		public static void Apply(TextWriter output, string value, Alignment? alignment)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Invalid comparison between Unknown and I4
			if (alignment.HasValue)
			{
				int length = value.Length;
				Alignment value2 = alignment.Value;
				if (length < ((Alignment)(ref value2)).Width)
				{
					value2 = alignment.Value;
					int num = ((Alignment)(ref value2)).Width - value.Length;
					value2 = alignment.Value;
					if ((int)((Alignment)(ref value2)).Direction == 0)
					{
						output.Write(value);
					}
					if (num <= PaddingChars.Length)
					{
						output.Write(PaddingChars, 0, num);
					}
					else
					{
						output.Write(new string(' ', num));
					}
					value2 = alignment.Value;
					if ((int)((Alignment)(ref value2)).Direction == 1)
					{
						output.Write(value);
					}
					return;
				}
			}
			output.Write(value);
		}
	}
	internal class ThemedMessageTemplateRenderer
	{
		private readonly ConsoleTheme _theme;

		private readonly ThemedValueFormatter _valueFormatter;

		private readonly bool _isLiteral;

		private static readonly ConsoleTheme NoTheme = new EmptyConsoleTheme();

		private readonly ThemedValueFormatter _unthemedValueFormatter;

		public ThemedMessageTemplateRenderer(ConsoleTheme theme, ThemedValueFormatter valueFormatter, bool isLiteral)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			_theme = theme ?? throw new ArgumentNullException("theme");
			_valueFormatter = valueFormatter;
			_isLiteral = isLiteral;
			_unthemedValueFormatter = valueFormatter.SwitchTheme(NoTheme);
		}

		public int Render(MessageTemplate template, IReadOnlyDictionary<string, LogEventPropertyValue> properties, TextWriter output)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			int num = 0;
			global::System.Collections.Generic.IEnumerator<MessageTemplateToken> enumerator = template.Tokens.GetEnumerator();
			try
			{
				while (((global::System.Collections.IEnumerator)enumerator).MoveNext())
				{
					MessageTemplateToken current = enumerator.Current;
					TextToken val = (TextToken)(object)((current is TextToken) ? current : null);
					if (val != null)
					{
						num += RenderTextToken(val, output);
						continue;
					}
					PropertyToken pt = (PropertyToken)current;
					num += RenderPropertyToken(pt, properties, output);
				}
				return num;
			}
			finally
			{
				((global::System.IDisposable)enumerator)?.Dispose();
			}
		}

		private int RenderTextToken(TextToken tt, TextWriter output)
		{
			int invisibleCharacterCount = 0;
			using (_theme.Apply(output, ConsoleThemeStyle.Text, ref invisibleCharacterCount))
			{
				output.Write(tt.Text);
				return invisibleCharacterCount;
			}
		}

		private int RenderPropertyToken(PropertyToken pt, IReadOnlyDictionary<string, LogEventPropertyValue> properties, TextWriter output)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			LogEventPropertyValue propertyValue = default(LogEventPropertyValue);
			if (!properties.TryGetValue(pt.PropertyName, ref propertyValue))
			{
				int invisibleCharacterCount = 0;
				using (_theme.Apply(output, ConsoleThemeStyle.Invalid, ref invisibleCharacterCount))
				{
					output.Write(((object)pt).ToString());
					return invisibleCharacterCount;
				}
			}
			if (!pt.Alignment.HasValue)
			{
				return RenderValue(_theme, _valueFormatter, propertyValue, output, pt.Format);
			}
			StringWriter val = new StringWriter();
			if (!_theme.CanBuffer)
			{
				return RenderAlignedPropertyTokenUnbuffered(pt, output, propertyValue);
			}
			int num = RenderValue(_theme, _valueFormatter, propertyValue, (TextWriter)(object)val, pt.Format);
			string text = ((object)val).ToString();
			int num2 = text.Length - num;
			Alignment value = pt.Alignment.Value;
			if (num2 >= ((Alignment)(ref value)).Width)
			{
				output.Write(text);
			}
			else
			{
				Padding.Apply(output, text, pt.Alignment.Value.Widen(num));
			}
			return num;
		}

		private int RenderAlignedPropertyTokenUnbuffered(PropertyToken pt, TextWriter output, LogEventPropertyValue propertyValue)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			if (!pt.Alignment.HasValue)
			{
				throw new ArgumentException("The PropertyToken should have a non-null Alignment.", "pt");
			}
			StringWriter val = new StringWriter();
			RenderValue(NoTheme, _unthemedValueFormatter, propertyValue, (TextWriter)(object)val, pt.Format);
			int length = ((object)val).ToString().Length;
			Alignment value = pt.Alignment.Value;
			if (length >= ((Alignment)(ref value)).Width)
			{
				return RenderValue(_theme, _valueFormatter, propertyValue, output, pt.Format);
			}
			value = pt.Alignment.Value;
			if ((int)((Alignment)(ref value)).Direction == 0)
			{
				int result = RenderValue(_theme, _valueFormatter, propertyValue, output, pt.Format);
				Padding.Apply(output, string.Empty, pt.Alignment.Value.Widen(-length));
				return result;
			}
			Padding.Apply(output, string.Empty, pt.Alignment.Value.Widen(-length));
			return RenderValue(_theme, _valueFormatter, propertyValue, output, pt.Format);
		}

		private int RenderValue(ConsoleTheme theme, ThemedValueFormatter valueFormatter, LogEventPropertyValue propertyValue, TextWriter output, string? format)
		{
			if (_isLiteral)
			{
				ScalarValue val = (ScalarValue)(object)((propertyValue is ScalarValue) ? propertyValue : null);
				if (val != null && val.Value is string)
				{
					int invisibleCharacterCount = 0;
					using (theme.Apply(output, ConsoleThemeStyle.String, ref invisibleCharacterCount))
					{
						output.Write(val.Value);
						return invisibleCharacterCount;
					}
				}
			}
			return valueFormatter.Format(propertyValue, output, format, _isLiteral);
		}
	}
}
namespace Serilog.Sinks.SystemConsole.Platform
{
	internal static class WindowsConsole
	{
		private const int StandardOutputHandleId = -11;

		private const uint EnableVirtualTerminalProcessingMode = 4u;

		private const long InvalidHandleValue = -1L;

		public static void EnableVirtualTerminalProcessing()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
			{
				nint stdHandle = GetStdHandle(-11);
				if (stdHandle != -1 && GetConsoleMode(stdHandle, out var mode))
				{
					SetConsoleMode(stdHandle, mode | 4u);
				}
			}
		}

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern nint GetStdHandle(int handleId);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool GetConsoleMode(nint handle, out uint mode);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool SetConsoleMode(nint handle, uint mode);
	}
}
namespace Serilog.Sinks.SystemConsole.Output
{
	internal class EventPropertyTokenRenderer : OutputTemplateTokenRenderer
	{
		private readonly ConsoleTheme _theme;

		private readonly PropertyToken _token;

		private readonly IFormatProvider? _formatProvider;

		public EventPropertyTokenRenderer(ConsoleTheme theme, PropertyToken token, IFormatProvider? formatProvider)
		{
			_theme = theme;
			_token = token;
			_formatProvider = formatProvider;
		}

		public override void Render(LogEvent logEvent, TextWriter output)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			LogEventPropertyValue val = default(LogEventPropertyValue);
			if (!logEvent.Properties.TryGetValue(_token.PropertyName, ref val))
			{
				Padding.Apply(output, string.Empty, _token.Alignment);
				return;
			}
			int invisibleCharacterCount = 0;
			using (_theme.Apply(output, ConsoleThemeStyle.SecondaryText, ref invisibleCharacterCount))
			{
				TextWriter val2 = (TextWriter)((!_token.Alignment.HasValue) ? ((object)output) : ((object)new StringWriter()));
				ScalarValue val3 = (ScalarValue)(object)((val is ScalarValue) ? val : null);
				if (val3 != null && val3.Value is string value)
				{
					string text = Casing.Format(value, _token.Format);
					val2.Write(text);
				}
				else
				{
					val.Render(val2, _token.Format, _formatProvider);
				}
				if (_token.Alignment.HasValue)
				{
					string value2 = ((object)val2).ToString();
					Padding.Apply(output, value2, _token.Alignment);
				}
			}
		}
	}
	internal class ExceptionTokenRenderer : OutputTemplateTokenRenderer
	{
		private const string StackFrameLinePrefix = "   ";

		private readonly ConsoleTheme _theme;

		public ExceptionTokenRenderer(ConsoleTheme theme, PropertyToken pt)
		{
			_theme = theme;
		}

		public override void Render(LogEvent logEvent, TextWriter output)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			if (logEvent.Exception == null)
			{
				return;
			}
			StringReader val = new StringReader(((object)logEvent.Exception).ToString());
			string text;
			while ((text = ((TextReader)val).ReadLine()) != null)
			{
				ConsoleThemeStyle style = (text.StartsWith("   ") ? ConsoleThemeStyle.SecondaryText : ConsoleThemeStyle.Text);
				int invisibleCharacterCount = 0;
				using (_theme.Apply(output, style, ref invisibleCharacterCount))
				{
					output.Write(text);
				}
				output.WriteLine();
			}
		}
	}
	internal static class LevelOutputFormat
	{
		private static readonly string[][] TitleCaseLevelMap = new string[6][]
		{
			new string[7] { "V", "Vb", "Vrb", "Verb", "Verbo", "Verbos", "Verbose" },
			new string[5] { "D", "De", "Dbg", "Dbug", "Debug" },
			new string[11]
			{
				"I", "In", "Inf", "Info", "Infor", "Inform", "Informa", "Informat", "Informati", "Informatio",
				"Information"
			},
			new string[7] { "W", "Wn", "Wrn", "Warn", "Warni", "Warnin", "Warning" },
			new string[5] { "E", "Er", "Err", "Eror", "Error" },
			new string[5] { "F", "Fa", "Ftl", "Fatl", "Fatal" }
		};

		private static readonly string[][] LowerCaseLevelMap = new string[6][]
		{
			new string[7] { "v", "vb", "vrb", "verb", "verbo", "verbos", "verbose" },
			new string[5] { "d", "de", "dbg", "dbug", "debug" },
			new string[11]
			{
				"i", "in", "inf", "info", "infor", "inform", "informa", "informat", "informati", "informatio",
				"information"
			},
			new string[7] { "w", "wn", "wrn", "warn", "warni", "warnin", "warning" },
			new string[5] { "e", "er", "err", "eror", "error" },
			new string[5] { "f", "fa", "ftl", "fatl", "fatal" }
		};

		private static readonly string[][] UpperCaseLevelMap = new string[6][]
		{
			new string[7] { "V", "VB", "VRB", "VERB", "VERBO", "VERBOS", "VERBOSE" },
			new string[5] { "D", "DE", "DBG", "DBUG", "DEBUG" },
			new string[11]
			{
				"I", "IN", "INF", "INFO", "INFOR", "INFORM", "INFORMA", "INFORMAT", "INFORMATI", "INFORMATIO",
				"INFORMATION"
			},
			new string[7] { "W", "WN", "WRN", "WARN", "WARNI", "WARNIN", "WARNING" },
			new string[5] { "E", "ER", "ERR", "EROR", "ERROR" },
			new string[5] { "F", "FA", "FTL", "FATL", "FATAL" }
		};

		public static string GetLevelMoniker(LogEventLevel value, string? format = null)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Expected I4, but got Unknown
			int num = (int)value;
			if ((num < 0 || num > 5) ? true : false)
			{
				return Casing.Format(((object)(LogEventLevel)(ref value)).ToString(), format);
			}
			if (format == null || (format.Length != 2 && format.Length != 3))
			{
				return Casing.Format(GetLevelMoniker(TitleCaseLevelMap, num), format);
			}
			int num2 = format[1] - 48;
			if (format.Length == 3)
			{
				num2 *= 10;
				num2 += format[2] - 48;
			}
			if (num2 < 1)
			{
				return string.Empty;
			}
			return format[0] switch
			{
				'w' => GetLevelMoniker(LowerCaseLevelMap, num, num2), 
				'u' => GetLevelMoniker(UpperCaseLevelMap, num, num2), 
				't' => GetLevelMoniker(TitleCaseLevelMap, num, num2), 
				_ => Casing.Format(GetLevelMoniker(TitleCaseLevelMap, num), format), 
			};
		}

		private static string GetLevelMoniker(string[][] caseLevelMap, int index, int width)
		{
			string[] array = caseLevelMap[index];
			return array[Math.Min(width, array.Length) - 1];
		}

		private static string GetLevelMoniker(string[][] caseLevelMap, int index)
		{
			string[] obj = caseLevelMap[index];
			return obj[obj.Length - 1];
		}
	}
	internal class LevelTokenRenderer : OutputTemplateTokenRenderer
	{
		private readonly ConsoleTheme _theme;

		private readonly PropertyToken _levelToken;

		private static readonly Dictionary<LogEventLevel, ConsoleThemeStyle> Levels;

		public LevelTokenRenderer(ConsoleTheme theme, PropertyToken levelToken)
		{
			_theme = theme;
			_levelToken = levelToken;
		}

		public override void Render(LogEvent logEvent, TextWriter output)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			string levelMoniker = LevelOutputFormat.GetLevelMoniker(logEvent.Level, _levelToken.Format);
			ConsoleThemeStyle style = default(ConsoleThemeStyle);
			if (!Levels.TryGetValue(logEvent.Level, ref style))
			{
				style = ConsoleThemeStyle.Invalid;
			}
			int invisibleCharacterCount = 0;
			using (_theme.Apply(output, style, ref invisibleCharacterCount))
			{
				Padding.Apply(output, levelMoniker, _levelToken.Alignment);
			}
		}

		static LevelTokenRenderer()
		{
			Dictionary<LogEventLevel, ConsoleThemeStyle> obj = new Dictionary<LogEventLevel, ConsoleThemeStyle>();
			obj.Add((LogEventLevel)0, ConsoleThemeStyle.LevelVerbose);
			obj.Add((LogEventLevel)1, ConsoleThemeStyle.LevelDebug);
			obj.Add((LogEventLevel)2, ConsoleThemeStyle.LevelInformation);
			obj.Add((LogEventLevel)3, ConsoleThemeStyle.LevelWarning);
			obj.Add((LogEventLevel)4, ConsoleThemeStyle.LevelError);
			obj.Add((LogEventLevel)5, ConsoleThemeStyle.LevelFatal);
			Levels = obj;
		}
	}
	internal class MessageTemplateOutputTokenRenderer : OutputTemplateTokenRenderer
	{
		private readonly ConsoleTheme _theme;

		private readonly PropertyToken _token;

		private readonly ThemedMessageTemplateRenderer _renderer;

		public MessageTemplateOutputTokenRenderer(ConsoleTheme theme, PropertyToken token, IFormatProvider? formatProvider)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			_theme = theme ?? throw new ArgumentNullException("theme");
			_token = token ?? throw new ArgumentNullException("token");
			bool isLiteral = false;
			bool flag = false;
			if (token.Format != null)
			{
				for (int i = 0; i < token.Format.Length; i++)
				{
					if (token.Format[i] == 'l')
					{
						isLiteral = true;
					}
					else if (token.Format[i] == 'j')
					{
						flag = true;
					}
				}
			}
			_renderer = new ThemedMessageTemplateRenderer(theme, flag ? ((ThemedValueFormatter)new ThemedJsonValueFormatter(theme, formatProvider)) : ((ThemedValueFormatter)new ThemedDisplayValueFormatter(theme, formatProvider)), isLiteral);
		}

		public override void Render(LogEvent logEvent, TextWriter output)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			if (!_token.Alignment.HasValue || !_theme.CanBuffer)
			{
				_renderer.Render(logEvent.MessageTemplate, logEvent.Properties, output);
				return;
			}
			StringWriter val = new StringWriter();
			int amount = _renderer.Render(logEvent.MessageTemplate, logEvent.Properties, (TextWriter)(object)val);
			string value = ((object)val).ToString();
			Padding.Apply(output, value, _token.Alignment.Value.Widen(amount));
		}
	}
	internal class NewLineTokenRenderer : OutputTemplateTokenRenderer
	{
		private readonly Alignment? _alignment;

		public NewLineTokenRenderer(Alignment? alignment)
		{
			_alignment = alignment;
		}

		public override void Render(LogEvent logEvent, TextWriter output)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			if (_alignment.HasValue)
			{
				Padding.Apply(output, Environment.NewLine, _alignment.Value.Widen(Environment.NewLine.Length));
			}
			else
			{
				output.WriteLine();
			}
		}
	}
	internal class OutputTemplateRenderer : ITextFormatter
	{
		private readonly OutputTemplateTokenRenderer[] _renderers;

		public OutputTemplateRenderer(ConsoleTheme theme, string outputTemplate, IFormatProvider? formatProvider)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			if (outputTemplate == null)
			{
				throw new ArgumentNullException("outputTemplate");
			}
			MessageTemplate val = new MessageTemplateParser().Parse(outputTemplate);
			List<OutputTemplateTokenRenderer> val2 = new List<OutputTemplateTokenRenderer>();
			global::System.Collections.Generic.IEnumerator<MessageTemplateToken> enumerator = val.Tokens.GetEnumerator();
			try
			{
				while (((global::System.Collections.IEnumerator)enumerator).MoveNext())
				{
					MessageTemplateToken current = enumerator.Current;
					TextToken val3 = (TextToken)(object)((current is TextToken) ? current : null);
					if (val3 != null)
					{
						val2.Add((OutputTemplateTokenRenderer)new TextTokenRenderer(theme, val3.Text));
						continue;
					}
					PropertyToken val4 = (PropertyToken)current;
					if (val4.PropertyName == "Level")
					{
						val2.Add((OutputTemplateTokenRenderer)new LevelTokenRenderer(theme, val4));
					}
					else if (val4.PropertyName == "NewLine")
					{
						val2.Add((OutputTemplateTokenRenderer)new NewLineTokenRenderer(val4.Alignment));
					}
					else if (val4.PropertyName == "TraceId")
					{
						val2.Add((OutputTemplateTokenRenderer)new TraceIdTokenRenderer(theme, val4));
					}
					else if (val4.PropertyName == "SpanId")
					{
						val2.Add((OutputTemplateTokenRenderer)new SpanIdTokenRenderer(theme, val4));
					}
					else if (val4.PropertyName == "Exception")
					{
						val2.Add((OutputTemplateTokenRenderer)new ExceptionTokenRenderer(theme, val4));
					}
					else if (val4.PropertyName == "Message")
					{
						val2.Add((OutputTemplateTokenRenderer)new MessageTemplateOutputTokenRenderer(theme, val4, formatProvider));
					}
					else if (val4.PropertyName == "Timestamp")
					{
						val2.Add((OutputTemplateTokenRenderer)new TimestampTokenRenderer(theme, val4, formatProvider));
					}
					else if (val4.PropertyName == "Properties")
					{
						val2.Add((OutputTemplateTokenRenderer)new PropertiesTokenRenderer(theme, val4, val, formatProvider));
					}
					else
					{
						val2.Add((OutputTemplateTokenRenderer)new EventPropertyTokenRenderer(theme, val4, formatProvider));
					}
				}
			}
			finally
			{
				((global::System.IDisposable)enumerator)?.Dispose();
			}
			_renderers = val2.ToArray();
		}

		public void Format(LogEvent logEvent, TextWriter output)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			if (logEvent == null)
			{
				throw new ArgumentNullException("logEvent");
			}
			if (output == null)
			{
				throw new ArgumentNullException("output");
			}
			OutputTemplateTokenRenderer[] renderers = _renderers;
			for (int i = 0; i < renderers.Length; i++)
			{
				renderers[i].Render(logEvent, output);
			}
		}
	}
	internal abstract class OutputTemplateTokenRenderer
	{
		public abstract void Render(LogEvent logEvent, TextWriter output);
	}
	internal class PropertiesTokenRenderer : OutputTemplateTokenRenderer
	{
		private readonly MessageTemplate _outputTemplate;

		private readonly ConsoleTheme _theme;

		private readonly PropertyToken _token;

		private readonly ThemedValueFormatter _valueFormatter;

		public PropertiesTokenRenderer(ConsoleTheme theme, PropertyToken token, MessageTemplate outputTemplate, IFormatProvider? formatProvider)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			_outputTemplate = outputTemplate;
			_theme = theme ?? throw new ArgumentNullException("theme");
			_token = token ?? throw new ArgumentNullException("token");
			bool flag = false;
			if (token.Format != null)
			{
				for (int i = 0; i < token.Format.Length; i++)
				{
					if (token.Format[i] == 'j')
					{
						flag = true;
					}
				}
			}
			_valueFormatter = (flag ? ((ThemedValueFormatter)new ThemedJsonValueFormatter(theme, formatProvider)) : ((ThemedValueFormatter)new ThemedDisplayValueFormatter(theme, formatProvider)));
		}

		public override void Render(LogEvent logEvent, TextWriter output)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Expected O, but got Unknown
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			LogEvent logEvent2 = logEvent;
			StructureValue val = new StructureValue(Enumerable.Select<KeyValuePair<string, LogEventPropertyValue>, LogEventProperty>(Enumerable.Where<KeyValuePair<string, LogEventPropertyValue>>((global::System.Collections.Generic.IEnumerable<KeyValuePair<string, LogEventPropertyValue>>)logEvent2.Properties, (Func<KeyValuePair<string, LogEventPropertyValue>, bool>)((KeyValuePair<string, LogEventPropertyValue> p) => !TemplateContainsPropertyName(logEvent2.MessageTemplate, p.Key) && !TemplateContainsPropertyName(_outputTemplate, p.Key))), (Func<KeyValuePair<string, LogEventPropertyValue>, LogEventProperty>)((KeyValuePair<string, LogEventPropertyValue> p) => new LogEventProperty(p.Key, p.Value))), (string)null);
			if (!_token.Alignment.HasValue || !_theme.CanBuffer)
			{
				_valueFormatter.Format((LogEventPropertyValue)(object)val, output, null);
				return;
			}
			StringWriter val2 = new StringWriter(new StringBuilder(((global::System.Collections.Generic.IReadOnlyCollection<LogEventProperty>)val.Properties).Count * 16));
			int amount = _valueFormatter.Format((LogEventPropertyValue)(object)val, (TextWriter)(object)val2, null);
			string value = ((object)val2).ToString();
			Padding.Apply(output, value, _token.Alignment.Value.Widen(amount));
		}

		private static bool TemplateContainsPropertyName(MessageTemplate template, string propertyName)
		{
			global::System.Collections.Generic.IEnumerator<MessageTemplateToken> enumerator = template.Tokens.GetEnumerator();
			try
			{
				while (((global::System.Collections.IEnumerator)enumerator).MoveNext())
				{
					MessageTemplateToken current = enumerator.Current;
					PropertyToken val = (PropertyToken)(object)((current is PropertyToken) ? current : null);
					if (val != null && val.PropertyName == propertyName)
					{
						return true;
					}
				}
			}
			finally
			{
				((global::System.IDisposable)enumerator)?.Dispose();
			}
			return false;
		}
	}
	internal class SpanIdTokenRenderer : OutputTemplateTokenRenderer
	{
		private readonly ConsoleTheme _theme;

		private readonly Alignment? _alignment;

		public SpanIdTokenRenderer(ConsoleTheme theme, PropertyToken spanIdToken)
		{
			_theme = theme;
			_alignment = spanIdToken.Alignment;
		}

		public override void Render(LogEvent logEvent, TextWriter output)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			ActivitySpanId? spanId = logEvent.SpanId;
			if (!spanId.HasValue)
			{
				return;
			}
			ActivitySpanId valueOrDefault = spanId.GetValueOrDefault();
			int invisibleCharacterCount = 0;
			using (_theme.Apply(output, ConsoleThemeStyle.Text, ref invisibleCharacterCount))
			{
				Alignment? alignment = _alignment;
				if (alignment.HasValue)
				{
					Alignment valueOrDefault2 = alignment.GetValueOrDefault();
					Padding.Apply(output, ((object)(ActivitySpanId)(ref valueOrDefault)).ToString(), valueOrDefault2);
				}
				else
				{
					output.Write((object)valueOrDefault);
				}
			}
		}
	}
	internal class TextTokenRenderer : OutputTemplateTokenRenderer
	{
		private readonly ConsoleTheme _theme;

		private readonly string _text;

		public TextTokenRenderer(ConsoleTheme theme, string text)
		{
			_theme = theme;
			_text = text;
		}

		public override void Render(LogEvent logEvent, TextWriter output)
		{
			int invisibleCharacterCount = 0;
			using (_theme.Apply(output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
			{
				output.Write(_text);
			}
		}
	}
	internal class TimestampTokenRenderer : OutputTemplateTokenRenderer
	{
		private readonly struct DateTimeOffsetValue
		{
			[field: CompilerGenerated]
			public DateTimeOffset Value
			{
				[CompilerGenerated]
				get;
			}

			public DateTimeOffsetValue(DateTimeOffset value)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				Value = value;
			}

			public void Render(TextWriter output, string? format = null, IFormatProvider? formatProvider = null)
			{
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Expected O, but got Unknown
				//IL_0047: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0080: Unknown result type (might be due to invalid IL or missing references)
				//IL_0085: Unknown result type (might be due to invalid IL or missing references)
				ICustomFormatter val = (ICustomFormatter)((formatProvider != null) ? formatProvider.GetFormat(typeof(ICustomFormatter)) : null);
				if (val != null)
				{
					output.Write(val.Format(format, (object)Value, formatProvider));
					return;
				}
				global::System.Span<char> span = stackalloc char[32];
				DateTimeOffset value = Value;
				int num = default(int);
				if (((DateTimeOffset)(ref value)).TryFormat(span, ref num, string.op_Implicit(format), (IFormatProvider)(((object)formatProvider) ?? ((object)CultureInfo.InvariantCulture))))
				{
					output.Write(global::System.Span<char>.op_Implicit(span.Slice(0, num)));
					return;
				}
				value = Value;
				output.Write(((DateTimeOffset)(ref value)).ToString(format, (IFormatProvider)(((object)formatProvider) ?? ((object)CultureInfo.InvariantCulture))));
			}
		}

		private readonly ConsoleTheme _theme;

		private readonly PropertyToken _token;

		private readonly IFormatProvider? _formatProvider;

		public TimestampTokenRenderer(ConsoleTheme theme, PropertyToken token, IFormatProvider? formatProvider)
		{
			_theme = theme;
			_token = token;
			_formatProvider = formatProvider;
		}

		public override void Render(LogEvent logEvent, TextWriter output)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			DateTimeOffsetValue dateTimeOffsetValue = new DateTimeOffsetValue(logEvent.Timestamp);
			int invisibleCharacterCount = 0;
			using (_theme.Apply(output, ConsoleThemeStyle.SecondaryText, ref invisibleCharacterCount))
			{
				if (!_token.Alignment.HasValue)
				{
					dateTimeOffsetValue.Render(output, _token.Format, _formatProvider);
					return;
				}
				StringWriter val = new StringWriter();
				dateTimeOffsetValue.Render((TextWriter)(object)val, _token.Format, _formatProvider);
				string value = ((object)val).ToString();
				Padding.Apply(output, value, _token.Alignment);
			}
		}
	}
	internal class TraceIdTokenRenderer : OutputTemplateTokenRenderer
	{
		private readonly ConsoleTheme _theme;

		private readonly Alignment? _alignment;

		public TraceIdTokenRenderer(ConsoleTheme theme, PropertyToken traceIdToken)
		{
			_theme = theme;
			_alignment = traceIdToken.Alignment;
		}

		public override void Render(LogEvent logEvent, TextWriter output)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			ActivityTraceId? traceId = logEvent.TraceId;
			if (!traceId.HasValue)
			{
				return;
			}
			ActivityTraceId valueOrDefault = traceId.GetValueOrDefault();
			int invisibleCharacterCount = 0;
			using (_theme.Apply(output, ConsoleThemeStyle.Text, ref invisibleCharacterCount))
			{
				Alignment? alignment = _alignment;
				if (alignment.HasValue)
				{
					Alignment valueOrDefault2 = alignment.GetValueOrDefault();
					Padding.Apply(output, ((object)(ActivityTraceId)(ref valueOrDefault)).ToString(), valueOrDefault2);
				}
				else
				{
					output.Write((object)valueOrDefault);
				}
			}
		}
	}
}
namespace Serilog.Sinks.SystemConsole.Formatting
{
	internal class ThemedDisplayValueFormatter : ThemedValueFormatter
	{
		private readonly IFormatProvider? _formatProvider;

		public ThemedDisplayValueFormatter(ConsoleTheme theme, IFormatProvider? formatProvider)
			: base(theme)
		{
			_formatProvider = formatProvider;
		}

		public override ThemedValueFormatter SwitchTheme(ConsoleTheme theme)
		{
			return new ThemedDisplayValueFormatter(theme, _formatProvider);
		}

		protected override int VisitScalarValue(ThemedValueFormatterState state, ScalarValue scalar)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (scalar == null)
			{
				throw new ArgumentNullException("scalar");
			}
			return FormatLiteralValue(scalar, state.Output, state.Format);
		}

		protected override int VisitSequenceValue(ThemedValueFormatterState state, SequenceValue sequence)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (sequence == null)
			{
				throw new ArgumentNullException("sequence");
			}
			int invisibleCharacterCount = 0;
			using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
			{
				state.Output.Write('[');
			}
			string text = string.Empty;
			for (int i = 0; i < ((global::System.Collections.Generic.IReadOnlyCollection<LogEventPropertyValue>)sequence.Elements).Count; i++)
			{
				if (text.Length != 0)
				{
					using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
					{
						state.Output.Write(text);
					}
				}
				text = ", ";
				((LogEventPropertyValueVisitor<ThemedValueFormatterState, int>)this).Visit(state, sequence.Elements[i]);
			}
			using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
			{
				state.Output.Write(']');
				return invisibleCharacterCount;
			}
		}

		protected override int VisitStructureValue(ThemedValueFormatterState state, StructureValue structure)
		{
			int invisibleCharacterCount = 0;
			if (structure.TypeTag != null)
			{
				using (ApplyStyle(state.Output, ConsoleThemeStyle.Name, ref invisibleCharacterCount))
				{
					state.Output.Write(structure.TypeTag);
				}
				state.Output.Write(' ');
			}
			using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
			{
				state.Output.Write('{');
			}
			string text = string.Empty;
			for (int i = 0; i < ((global::System.Collections.Generic.IReadOnlyCollection<LogEventProperty>)structure.Properties).Count; i++)
			{
				if (text.Length != 0)
				{
					using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
					{
						state.Output.Write(text);
					}
				}
				text = ", ";
				LogEventProperty val = structure.Properties[i];
				using (ApplyStyle(state.Output, ConsoleThemeStyle.Name, ref invisibleCharacterCount))
				{
					state.Output.Write(val.Name);
				}
				using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
				{
					state.Output.Write('=');
				}
				invisibleCharacterCount += ((LogEventPropertyValueVisitor<ThemedValueFormatterState, int>)this).Visit(state.Nest(), val.Value);
			}
			using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
			{
				state.Output.Write('}');
				return invisibleCharacterCount;
			}
		}

		protected override int VisitDictionaryValue(ThemedValueFormatterState state, DictionaryValue dictionary)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			int invisibleCharacterCount = 0;
			using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
			{
				state.Output.Write('{');
			}
			string text = string.Empty;
			global::System.Collections.Generic.IEnumerator<KeyValuePair<ScalarValue, LogEventPropertyValue>> enumerator = ((global::System.Collections.Generic.IEnumerable<KeyValuePair<ScalarValue, LogEventPropertyValue>>)dictionary.Elements).GetEnumerator();
			try
			{
				while (((global::System.Collections.IEnumerator)enumerator).MoveNext())
				{
					KeyValuePair<ScalarValue, LogEventPropertyValue> current = enumerator.Current;
					if (text.Length != 0)
					{
						using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
						{
							state.Output.Write(text);
						}
					}
					text = ", ";
					using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
					{
						state.Output.Write('[');
					}
					using (ApplyStyle(state.Output, ConsoleThemeStyle.String, ref invisibleCharacterCount))
					{
						invisibleCharacterCount += ((LogEventPropertyValueVisitor<ThemedValueFormatterState, int>)this).Visit(state.Nest(), (LogEventPropertyValue)(object)current.Key);
					}
					using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
					{
						state.Output.Write("]=");
					}
					invisibleCharacterCount += ((LogEventPropertyValueVisitor<ThemedValueFormatterState, int>)this).Visit(state.Nest(), current.Value);
				}
			}
			finally
			{
				((global::System.IDisposable)enumerator)?.Dispose();
			}
			using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
			{
				state.Output.Write('}');
				return invisibleCharacterCount;
			}
		}

		public int FormatLiteralValue(ScalarValue scalar, TextWriter output, string? format)
		{
			object value = scalar.Value;
			int invisibleCharacterCount = 0;
			if (value == null)
			{
				using (ApplyStyle(output, ConsoleThemeStyle.Null, ref invisibleCharacterCount))
				{
					output.Write("null");
					return invisibleCharacterCount;
				}
			}
			if (value is string text)
			{
				using (ApplyStyle(output, ConsoleThemeStyle.String, ref invisibleCharacterCount))
				{
					if (format != "l")
					{
						JsonValueFormatter.WriteQuotedJsonString(text, output);
					}
					else
					{
						output.Write(text);
					}
				}
				return invisibleCharacterCount;
			}
			if (value is global::System.ValueType)
			{
				if (value is int || value is uint || value is long || value is ulong || value is decimal || value is byte || value is sbyte || value is short || value is ushort || value is float || value is double)
				{
					using (ApplyStyle(output, ConsoleThemeStyle.Number, ref invisibleCharacterCount))
					{
						((LogEventPropertyValue)scalar).Render(output, format, _formatProvider);
						return invisibleCharacterCount;
					}
				}
				if (value is bool flag)
				{
					using (ApplyStyle(output, ConsoleThemeStyle.Boolean, ref invisibleCharacterCount))
					{
						output.Write(flag);
						return invisibleCharacterCount;
					}
				}
				if (value is char c)
				{
					using (ApplyStyle(output, ConsoleThemeStyle.Scalar, ref invisibleCharacterCount))
					{
						output.Write('\'');
						output.Write(c);
						output.Write('\'');
						return invisibleCharacterCount;
					}
				}
			}
			using (ApplyStyle(output, ConsoleThemeStyle.Scalar, ref invisibleCharacterCount))
			{
				((LogEventPropertyValue)scalar).Render(output, format, _formatProvider);
				return invisibleCharacterCount;
			}
		}
	}
	internal class ThemedJsonValueFormatter : ThemedValueFormatter
	{
		private readonly ThemedDisplayValueFormatter _displayFormatter;

		private readonly IFormatProvider? _formatProvider;

		public ThemedJsonValueFormatter(ConsoleTheme theme, IFormatProvider? formatProvider)
			: base(theme)
		{
			_displayFormatter = new ThemedDisplayValueFormatter(theme, formatProvider);
			_formatProvider = formatProvider;
		}

		public override ThemedValueFormatter SwitchTheme(ConsoleTheme theme)
		{
			return new ThemedJsonValueFormatter(theme, _formatProvider);
		}

		protected override int VisitScalarValue(ThemedValueFormatterState state, ScalarValue scalar)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (scalar == null)
			{
				throw new ArgumentNullException("scalar");
			}
			if (state.IsTopLevel)
			{
				return _displayFormatter.FormatLiteralValue(scalar, state.Output, state.Format);
			}
			return FormatLiteralValue(scalar, state.Output);
		}

		protected override int VisitSequenceValue(ThemedValueFormatterState state, SequenceValue sequence)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (sequence == null)
			{
				throw new ArgumentNullException("sequence");
			}
			int invisibleCharacterCount = 0;
			using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
			{
				state.Output.Write('[');
			}
			string text = string.Empty;
			for (int i = 0; i < ((global::System.Collections.Generic.IReadOnlyCollection<LogEventPropertyValue>)sequence.Elements).Count; i++)
			{
				if (text.Length != 0)
				{
					using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
					{
						state.Output.Write(text);
					}
				}
				text = ", ";
				((LogEventPropertyValueVisitor<ThemedValueFormatterState, int>)this).Visit(state.Nest(), sequence.Elements[i]);
			}
			using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
			{
				state.Output.Write(']');
				return invisibleCharacterCount;
			}
		}

		protected override int VisitStructureValue(ThemedValueFormatterState state, StructureValue structure)
		{
			int invisibleCharacterCount = 0;
			using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
			{
				state.Output.Write('{');
			}
			string text = string.Empty;
			for (int i = 0; i < ((global::System.Collections.Generic.IReadOnlyCollection<LogEventProperty>)structure.Properties).Count; i++)
			{
				if (text.Length != 0)
				{
					using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
					{
						state.Output.Write(text);
					}
				}
				text = ", ";
				LogEventProperty val = structure.Properties[i];
				using (ApplyStyle(state.Output, ConsoleThemeStyle.Name, ref invisibleCharacterCount))
				{
					JsonValueFormatter.WriteQuotedJsonString(val.Name, state.Output);
				}
				using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
				{
					state.Output.Write(": ");
				}
				invisibleCharacterCount += ((LogEventPropertyValueVisitor<ThemedValueFormatterState, int>)this).Visit(state.Nest(), val.Value);
			}
			if (structure.TypeTag != null)
			{
				using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
				{
					state.Output.Write(text);
				}
				using (ApplyStyle(state.Output, ConsoleThemeStyle.Name, ref invisibleCharacterCount))
				{
					JsonValueFormatter.WriteQuotedJsonString("$type", state.Output);
				}
				using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
				{
					state.Output.Write(": ");
				}
				using (ApplyStyle(state.Output, ConsoleThemeStyle.String, ref invisibleCharacterCount))
				{
					JsonValueFormatter.WriteQuotedJsonString(structure.TypeTag, state.Output);
				}
			}
			using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
			{
				state.Output.Write('}');
				return invisibleCharacterCount;
			}
		}

		protected override int VisitDictionaryValue(ThemedValueFormatterState state, DictionaryValue dictionary)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			int invisibleCharacterCount = 0;
			using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
			{
				state.Output.Write('{');
			}
			string text = string.Empty;
			global::System.Collections.Generic.IEnumerator<KeyValuePair<ScalarValue, LogEventPropertyValue>> enumerator = ((global::System.Collections.Generic.IEnumerable<KeyValuePair<ScalarValue, LogEventPropertyValue>>)dictionary.Elements).GetEnumerator();
			try
			{
				while (((global::System.Collections.IEnumerator)enumerator).MoveNext())
				{
					KeyValuePair<ScalarValue, LogEventPropertyValue> current = enumerator.Current;
					if (text.Length != 0)
					{
						using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
						{
							state.Output.Write(text);
						}
					}
					text = ", ";
					ConsoleThemeStyle style = ((current.Key.Value == null) ? ConsoleThemeStyle.Null : ((current.Key.Value is string) ? ConsoleThemeStyle.String : ConsoleThemeStyle.Scalar));
					using (ApplyStyle(state.Output, style, ref invisibleCharacterCount))
					{
						JsonValueFormatter.WriteQuotedJsonString((current.Key.Value ?? "null").ToString() ?? "", state.Output);
					}
					using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
					{
						state.Output.Write(": ");
					}
					invisibleCharacterCount += ((LogEventPropertyValueVisitor<ThemedValueFormatterState, int>)this).Visit(state.Nest(), current.Value);
				}
			}
			finally
			{
				((global::System.IDisposable)enumerator)?.Dispose();
			}
			using (ApplyStyle(state.Output, ConsoleThemeStyle.TertiaryText, ref invisibleCharacterCount))
			{
				state.Output.Write('}');
				return invisibleCharacterCount;
			}
		}

		private int FormatLiteralValue(ScalarValue scalar, TextWriter output)
		{
			object value = scalar.Value;
			int invisibleCharacterCount = 0;
			if (value == null)
			{
				using (ApplyStyle(output, ConsoleThemeStyle.Null, ref invisibleCharacterCount))
				{
					output.Write("null");
					return invisibleCharacterCount;
				}
			}
			if (value is string text)
			{
				using (ApplyStyle(output, ConsoleThemeStyle.String, ref invisibleCharacterCount))
				{
					JsonValueFormatter.WriteQuotedJsonString(text, output);
					return invisibleCharacterCount;
				}
			}
			if (value is global::System.ValueType)
			{
				if (value is int || value is uint || value is long || value is ulong || value is decimal || value is byte || value is sbyte || value is short || value is ushort)
				{
					using (ApplyStyle(output, ConsoleThemeStyle.Number, ref invisibleCharacterCount))
					{
						output.Write(((global::System.IFormattable)value).ToString((string)null, (IFormatProvider)(object)CultureInfo.InvariantCulture));
						return invisibleCharacterCount;
					}
				}
				if (value is double num)
				{
					using (ApplyStyle(output, ConsoleThemeStyle.Number, ref invisibleCharacterCount))
					{
						if (double.IsNaN(num) || double.IsInfinity(num))
						{
							JsonValueFormatter.WriteQuotedJsonString(num.ToString((IFormatProvider)(object)CultureInfo.InvariantCulture), output);
						}
						else
						{
							output.Write(num.ToString("R", (IFormatProvider)(object)CultureInfo.InvariantCulture));
						}
					}
					return invisibleCharacterCount;
				}
				if (value is float num2)
				{
					using (ApplyStyle(output, ConsoleThemeStyle.Number, ref invisibleCharacterCount))
					{
						if (double.IsNaN((double)num2) || double.IsInfinity((double)num2))
						{
							JsonValueFormatter.WriteQuotedJsonString(num2.ToString((IFormatProvider)(object)CultureInfo.InvariantCulture), output);
						}
						else
						{
							output.Write(num2.ToString("R", (IFormatProvider)(object)CultureInfo.InvariantCulture));
						}
					}
					return invisibleCharacterCount;
				}
				if (value is bool flag)
				{
					using (ApplyStyle(output, ConsoleThemeStyle.Boolean, ref invisibleCharacterCount))
					{
						output.Write(flag ? "true" : "false");
						return invisibleCharacterCount;
					}
				}
				if (value is char c)
				{
					using (ApplyStyle(output, ConsoleThemeStyle.Scalar, ref invisibleCharacterCount))
					{
						JsonValueFormatter.WriteQuotedJsonString(c.ToString(), output);
						return invisibleCharacterCount;
					}
				}
				if (value is global::System.DateTime || value is DateTimeOffset)
				{
					using (ApplyStyle(output, ConsoleThemeStyle.Scalar, ref invisibleCharacterCount))
					{
						output.Write('"');
						output.Write(((global::System.IFormattable)value).ToString("O", (IFormatProvider)(object)CultureInfo.InvariantCulture));
						output.Write('"');
						return invisibleCharacterCount;
					}
				}
			}
			using (ApplyStyle(output, ConsoleThemeStyle.Scalar, ref invisibleCharacterCount))
			{
				JsonValueFormatter.WriteQuotedJsonString(value.ToString() ?? "", output);
				return invisibleCharacterCount;
			}
		}
	}
	internal abstract class ThemedValueFormatter : LogEventPropertyValueVisitor<ThemedValueFormatterState, int>
	{
		private readonly ConsoleTheme _theme;

		protected ThemedValueFormatter(ConsoleTheme theme)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			_theme = theme ?? throw new ArgumentNullException("theme");
		}

		protected StyleReset ApplyStyle(TextWriter output, ConsoleThemeStyle style, ref int invisibleCharacterCount)
		{
			return _theme.Apply(output, style, ref invisibleCharacterCount);
		}

		public int Format(LogEventPropertyValue value, TextWriter output, string? format, bool literalTopLevel = false)
		{
			return ((LogEventPropertyValueVisitor<ThemedValueFormatterState, int>)this).Visit(new ThemedValueFormatterState
			{
				Output = output,
				Format = format,
				IsTopLevel = literalTopLevel
			}, value);
		}

		public abstract ThemedValueFormatter SwitchTheme(ConsoleTheme theme);
	}
	internal struct ThemedValueFormatterState
	{
		public TextWriter Output;

		public string? Format;

		public bool IsTopLevel;

		public ThemedValueFormatterState Nest()
		{
			ThemedValueFormatterState result = default(ThemedValueFormatterState);
			result.Output = Output;
			return result;
		}
	}
}

GDWeave/core/Serilog.Sinks.File.dll

Decompiled 3 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Serilog.Configuration;
using Serilog.Core;
using Serilog.Debugging;
using Serilog.Events;
using Serilog.Formatting;
using Serilog.Formatting.Display;
using Serilog.Sinks.File;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(/*Could not decode attribute arguments.*/)]
[assembly: CLSCompliant(true)]
[assembly: InternalsVisibleTo("Serilog.Sinks.File.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100fb8d13fd344a1c6fe0fe83ef33c1080bf30690765bc6eb0df26ebfdf8f21670c64265b30db09f73a0dea5b3db4c9d18dbf6d5a25af5ce9016f281014d79dc3b4201ac646c451830fc7e61a2dfd633d34c39f87b81894191652df5ac63cc40c77f3542f702bda692e6e8a9158353df189007a49da0f3cfd55eb250066b19485ec")]
[assembly: TargetFramework(".NETCoreApp,Version=v8.0", FrameworkDisplayName = ".NET 8.0")]
[assembly: AssemblyCompany("Serilog Contributors")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Write Serilog events to text files in plain or JSON format.")]
[assembly: AssemblyFileVersion("6.0.0.0")]
[assembly: AssemblyInformationalVersion("6.0.0+c7b9bc3d87f9bb98572a52286135efda1e608ad6")]
[assembly: AssemblyProduct("Serilog.Sinks.File")]
[assembly: AssemblyTitle("Serilog.Sinks.File")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/serilog/serilog-sinks-file")]
[assembly: AssemblyVersion("6.0.0.0")]
[module: RefSafetyRules(11)]
namespace Serilog
{
	public static class FileLoggerConfigurationExtensions
	{
		private const int DefaultRetainedFileCountLimit = 31;

		private const long DefaultFileSizeLimitBytes = 1073741824L;

		private const string DefaultOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}";

		[Obsolete("New code should not be compiled against this obsolete overload")]
		[EditorBrowsable(/*Could not decode attribute arguments.*/)]
		public static LoggerConfiguration File(this LoggerSinkConfiguration sinkConfiguration, string path, LogEventLevel restrictedToMinimumLevel, string outputTemplate, IFormatProvider formatProvider, long? fileSizeLimitBytes, LoggingLevelSwitch levelSwitch, bool buffered, bool shared, TimeSpan? flushToDiskInterval)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return sinkConfiguration.File(path, restrictedToMinimumLevel, outputTemplate, formatProvider, fileSizeLimitBytes, levelSwitch, buffered, shared, flushToDiskInterval, RollingInterval.Infinite, rollOnFileSizeLimit: false, null);
		}

		[Obsolete("New code should not be compiled against this obsolete overload")]
		[EditorBrowsable(/*Could not decode attribute arguments.*/)]
		public static LoggerConfiguration File(this LoggerSinkConfiguration sinkConfiguration, ITextFormatter formatter, string path, LogEventLevel restrictedToMinimumLevel, long? fileSizeLimitBytes, LoggingLevelSwitch levelSwitch, bool buffered, bool shared, TimeSpan? flushToDiskInterval)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return sinkConfiguration.File(formatter, path, restrictedToMinimumLevel, fileSizeLimitBytes, levelSwitch, buffered, shared, flushToDiskInterval, RollingInterval.Infinite, rollOnFileSizeLimit: false, null);
		}

		[Obsolete("New code should not be compiled against this obsolete overload")]
		[EditorBrowsable(/*Could not decode attribute arguments.*/)]
		public static LoggerConfiguration File(this LoggerSinkConfiguration sinkConfiguration, string path, LogEventLevel restrictedToMinimumLevel, string outputTemplate, IFormatProvider formatProvider, long? fileSizeLimitBytes, LoggingLevelSwitch levelSwitch, bool buffered, bool shared, TimeSpan? flushToDiskInterval, RollingInterval rollingInterval, bool rollOnFileSizeLimit, int? retainedFileCountLimit, Encoding encoding)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return sinkConfiguration.File(path, restrictedToMinimumLevel, outputTemplate, formatProvider, fileSizeLimitBytes, levelSwitch, buffered, shared, flushToDiskInterval, rollingInterval, rollOnFileSizeLimit, retainedFileCountLimit, encoding, null, null);
		}

		[Obsolete("New code should not be compiled against this obsolete overload")]
		[EditorBrowsable(/*Could not decode attribute arguments.*/)]
		public static LoggerConfiguration File(this LoggerSinkConfiguration sinkConfiguration, ITextFormatter formatter, string path, LogEventLevel restrictedToMinimumLevel, long? fileSizeLimitBytes, LoggingLevelSwitch levelSwitch, bool buffered, bool shared, TimeSpan? flushToDiskInterval, RollingInterval rollingInterval, bool rollOnFileSizeLimit, int? retainedFileCountLimit, Encoding encoding)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return sinkConfiguration.File(formatter, path, restrictedToMinimumLevel, fileSizeLimitBytes, levelSwitch, buffered, shared, flushToDiskInterval, rollingInterval, rollOnFileSizeLimit, retainedFileCountLimit, encoding, null, null);
		}

		public static LoggerConfiguration File(this LoggerSinkConfiguration sinkConfiguration, string path, LogEventLevel restrictedToMinimumLevel = 0, string outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}", IFormatProvider? formatProvider = null, long? fileSizeLimitBytes = 1073741824L, LoggingLevelSwitch? levelSwitch = null, bool buffered = false, bool shared = false, TimeSpan? flushToDiskInterval = null, RollingInterval rollingInterval = RollingInterval.Infinite, bool rollOnFileSizeLimit = false, int? retainedFileCountLimit = 31, Encoding? encoding = null, FileLifecycleHooks? hooks = null, TimeSpan? retainedFileTimeLimit = null)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (sinkConfiguration == null)
			{
				throw new ArgumentNullException("sinkConfiguration");
			}
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			if (outputTemplate == null)
			{
				throw new ArgumentNullException("outputTemplate");
			}
			MessageTemplateTextFormatter formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);
			return sinkConfiguration.File((ITextFormatter)(object)formatter, path, restrictedToMinimumLevel, fileSizeLimitBytes, levelSwitch, buffered, shared, flushToDiskInterval, rollingInterval, rollOnFileSizeLimit, retainedFileCountLimit, encoding, hooks, retainedFileTimeLimit);
		}

		public static LoggerConfiguration File(this LoggerSinkConfiguration sinkConfiguration, ITextFormatter formatter, string path, LogEventLevel restrictedToMinimumLevel = 0, long? fileSizeLimitBytes = 1073741824L, LoggingLevelSwitch? levelSwitch = null, bool buffered = false, bool shared = false, TimeSpan? flushToDiskInterval = null, RollingInterval rollingInterval = RollingInterval.Infinite, bool rollOnFileSizeLimit = false, int? retainedFileCountLimit = 31, Encoding? encoding = null, FileLifecycleHooks? hooks = null, TimeSpan? retainedFileTimeLimit = null)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (sinkConfiguration == null)
			{
				throw new ArgumentNullException("sinkConfiguration");
			}
			if (formatter == null)
			{
				throw new ArgumentNullException("formatter");
			}
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			return ConfigureFile(sinkConfiguration.Sink, formatter, path, restrictedToMinimumLevel, fileSizeLimitBytes, levelSwitch, buffered, propagateExceptions: false, shared, flushToDiskInterval, encoding, rollingInterval, rollOnFileSizeLimit, retainedFileCountLimit, hooks, retainedFileTimeLimit);
		}

		[Obsolete("New code should not be compiled against this obsolete overload")]
		[EditorBrowsable(/*Could not decode attribute arguments.*/)]
		public static LoggerConfiguration File(this LoggerAuditSinkConfiguration sinkConfiguration, string path, LogEventLevel restrictedToMinimumLevel, string outputTemplate, IFormatProvider formatProvider, LoggingLevelSwitch levelSwitch)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return sinkConfiguration.File(path, restrictedToMinimumLevel, outputTemplate, formatProvider, levelSwitch, null, null);
		}

		[Obsolete("New code should not be compiled against this obsolete overload")]
		[EditorBrowsable(/*Could not decode attribute arguments.*/)]
		public static LoggerConfiguration File(this LoggerAuditSinkConfiguration sinkConfiguration, ITextFormatter formatter, string path, LogEventLevel restrictedToMinimumLevel, LoggingLevelSwitch levelSwitch)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return sinkConfiguration.File(formatter, path, restrictedToMinimumLevel, levelSwitch, null, null);
		}

		public static LoggerConfiguration File(this LoggerAuditSinkConfiguration sinkConfiguration, string path, LogEventLevel restrictedToMinimumLevel = 0, string outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}", IFormatProvider? formatProvider = null, LoggingLevelSwitch? levelSwitch = null, Encoding? encoding = null, FileLifecycleHooks? hooks = null)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (sinkConfiguration == null)
			{
				throw new ArgumentNullException("sinkConfiguration");
			}
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			if (outputTemplate == null)
			{
				throw new ArgumentNullException("outputTemplate");
			}
			MessageTemplateTextFormatter formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);
			return sinkConfiguration.File((ITextFormatter)(object)formatter, path, restrictedToMinimumLevel, levelSwitch, encoding, hooks);
		}

		public static LoggerConfiguration File(this LoggerAuditSinkConfiguration sinkConfiguration, ITextFormatter formatter, string path, LogEventLevel restrictedToMinimumLevel = 0, LoggingLevelSwitch? levelSwitch = null, Encoding? encoding = null, FileLifecycleHooks? hooks = null)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (sinkConfiguration == null)
			{
				throw new ArgumentNullException("sinkConfiguration");
			}
			if (formatter == null)
			{
				throw new ArgumentNullException("formatter");
			}
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			return ConfigureFile(sinkConfiguration.Sink, formatter, path, restrictedToMinimumLevel, null, levelSwitch, buffered: false, propagateExceptions: true, shared: false, null, encoding, RollingInterval.Infinite, rollOnFileSizeLimit: false, null, hooks, null);
		}

		private static LoggerConfiguration ConfigureFile(this Func<ILogEventSink, LogEventLevel, LoggingLevelSwitch?, LoggerConfiguration> addSink, ITextFormatter formatter, string path, LogEventLevel restrictedToMinimumLevel, long? fileSizeLimitBytes, LoggingLevelSwitch? levelSwitch, bool buffered, bool propagateExceptions, bool shared, TimeSpan? flushToDiskInterval, Encoding? encoding, RollingInterval rollingInterval, bool rollOnFileSizeLimit, int? retainedFileCountLimit, FileLifecycleHooks? hooks, TimeSpan? retainedFileTimeLimit)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			if (addSink == null)
			{
				throw new ArgumentNullException("addSink");
			}
			if (formatter == null)
			{
				throw new ArgumentNullException("formatter");
			}
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes.GetValueOrDefault() < 1)
			{
				throw new ArgumentException("Invalid value provided; file size limit must be at least 1 byte, or null.", "fileSizeLimitBytes");
			}
			if (retainedFileCountLimit.HasValue && retainedFileCountLimit.GetValueOrDefault() < 1)
			{
				throw new ArgumentException("At least one file must be retained.", "retainedFileCountLimit");
			}
			if (retainedFileTimeLimit.HasValue)
			{
				TimeSpan? val = retainedFileTimeLimit;
				TimeSpan zero = TimeSpan.Zero;
				if (val.HasValue && val.GetValueOrDefault() < zero)
				{
					throw new ArgumentException("Negative value provided; retained file time limit must be non-negative.", "retainedFileTimeLimit");
				}
			}
			if (shared && buffered)
			{
				throw new ArgumentException("Buffered writes are not available when file sharing is enabled.", "buffered");
			}
			if (shared && hooks != null)
			{
				throw new ArgumentException("File lifecycle hooks are not currently supported for shared log files.", "hooks");
			}
			ILogEventSink val2;
			try
			{
				val2 = (ILogEventSink)((!rollOnFileSizeLimit && rollingInterval == RollingInterval.Infinite) ? ((!shared) ? ((object)new FileSink(path, formatter, fileSizeLimitBytes, encoding, buffered, hooks)) : ((object)new SharedFileSink(path, formatter, fileSizeLimitBytes, encoding))) : new RollingFileSink(path, formatter, fileSizeLimitBytes, retainedFileCountLimit, encoding, buffered, shared, rollingInterval, rollOnFileSizeLimit, hooks, retainedFileTimeLimit));
			}
			catch (global::System.Exception ex)
			{
				SelfLog.WriteLine("Unable to open file sink for {0}: {1}", (object)path, (object)ex, (object)null);
				if (propagateExceptions)
				{
					throw;
				}
				return addSink.Invoke((ILogEventSink)(object)new NullSink(), (LogEventLevel)5, (LoggingLevelSwitch)null);
			}
			if (flushToDiskInterval.HasValue)
			{
				val2 = (ILogEventSink)(object)new PeriodicFlushToDiskSink(val2, flushToDiskInterval.Value);
			}
			return addSink.Invoke(val2, restrictedToMinimumLevel, levelSwitch);
		}
	}
	public enum RollingInterval
	{
		Infinite,
		Year,
		Month,
		Day,
		Hour,
		Minute
	}
}
namespace Serilog.Sinks.File
{
	internal static class Clock
	{
		private static Func<global::System.DateTime> _dateTimeNow = () => global::System.DateTime.Now;

		[ThreadStatic]
		private static global::System.DateTime _testDateTimeNow;

		public static global::System.DateTime DateTimeNow => _dateTimeNow.Invoke();

		public static void SetTestDateTimeNow(global::System.DateTime now)
		{
			_testDateTimeNow = now;
			_dateTimeNow = () => _testDateTimeNow;
		}
	}
	internal sealed class FileLifeCycleHookChain : FileLifecycleHooks
	{
		private readonly FileLifecycleHooks _first;

		private readonly FileLifecycleHooks _second;

		public FileLifeCycleHookChain(FileLifecycleHooks first, FileLifecycleHooks second)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			_first = first ?? throw new ArgumentNullException("first");
			_second = second ?? throw new ArgumentNullException("second");
		}

		public override Stream OnFileOpened(string path, Stream underlyingStream, Encoding encoding)
		{
			Stream underlyingStream2 = _first.OnFileOpened(path, underlyingStream, encoding);
			return _second.OnFileOpened(path, underlyingStream2, encoding);
		}

		public override void OnFileDeleting(string path)
		{
			_first.OnFileDeleting(path);
			_second.OnFileDeleting(path);
		}
	}
	public abstract class FileLifecycleHooks
	{
		public virtual Stream OnFileOpened(string path, Stream underlyingStream, Encoding encoding)
		{
			return OnFileOpened(underlyingStream, encoding);
		}

		public virtual Stream OnFileOpened(Stream underlyingStream, Encoding encoding)
		{
			return underlyingStream;
		}

		public virtual void OnFileDeleting(string path)
		{
		}

		public FileLifecycleHooks Then(FileLifecycleHooks next)
		{
			return new FileLifeCycleHookChain(this, next);
		}
	}
	public sealed class FileSink : IFileSink, ILogEventSink, IFlushableFileSink, global::System.IDisposable
	{
		private readonly TextWriter _output;

		private readonly FileStream _underlyingStream;

		private readonly ITextFormatter _textFormatter;

		private readonly long? _fileSizeLimitBytes;

		private readonly bool _buffered;

		private readonly object _syncRoot = new object();

		private readonly WriteCountingStream? _countingStreamWrapper;

		[Obsolete("This type and constructor will be removed from the public API in a future version; use `WriteTo.File()` instead.")]
		public FileSink(string path, ITextFormatter textFormatter, long? fileSizeLimitBytes, Encoding? encoding = null, bool buffered = false)
			: this(path, textFormatter, fileSizeLimitBytes, encoding, buffered, null)
		{
		}

		internal FileSink(string path, ITextFormatter textFormatter, long? fileSizeLimitBytes, Encoding? encoding, bool buffered, FileLifecycleHooks? hooks)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Expected O, but got Unknown
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Expected O, but got Unknown
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes.GetValueOrDefault() < 1)
			{
				throw new ArgumentException("Invalid value provided; file size limit must be at least 1 byte, or null.");
			}
			_textFormatter = textFormatter ?? throw new ArgumentNullException("textFormatter");
			_fileSizeLimitBytes = fileSizeLimitBytes;
			_buffered = buffered;
			string directoryName = Path.GetDirectoryName(path);
			if (!string.IsNullOrWhiteSpace(directoryName) && !Directory.Exists(directoryName))
			{
				Directory.CreateDirectory(directoryName);
			}
			Stream val = (Stream)(object)(_underlyingStream = File.Open(path, (FileMode)4, (FileAccess)2, (FileShare)1));
			val.Seek(0L, (SeekOrigin)2);
			if (_fileSizeLimitBytes.HasValue)
			{
				val = (Stream)(object)(_countingStreamWrapper = new WriteCountingStream((Stream)(object)_underlyingStream));
			}
			if (encoding == null)
			{
				encoding = (Encoding?)new UTF8Encoding(false);
			}
			if (hooks != null)
			{
				val = hooks.OnFileOpened(path, val, encoding) ?? throw new InvalidOperationException("The file lifecycle hook `OnFileOpened(...)` returned `null`.");
			}
			_output = (TextWriter)new StreamWriter(val, encoding);
		}

		bool IFileSink.EmitOrOverflow(LogEvent logEvent)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (logEvent == null)
			{
				throw new ArgumentNullException("logEvent");
			}
			lock (_syncRoot)
			{
				if (_fileSizeLimitBytes.HasValue && _countingStreamWrapper.CountedLength >= _fileSizeLimitBytes.Value)
				{
					return false;
				}
				_textFormatter.Format(logEvent, _output);
				if (!_buffered)
				{
					_output.Flush();
				}
				return true;
			}
		}

		public void Emit(LogEvent logEvent)
		{
			((IFileSink)this).EmitOrOverflow(logEvent);
		}

		public void Dispose()
		{
			lock (_syncRoot)
			{
				_output.Dispose();
			}
		}

		public void FlushToDisk()
		{
			lock (_syncRoot)
			{
				_output.Flush();
				_underlyingStream.Flush(true);
			}
		}
	}
	internal interface IFileSink : ILogEventSink, IFlushableFileSink
	{
		bool EmitOrOverflow(LogEvent logEvent);
	}
	public interface IFlushableFileSink
	{
		void FlushToDisk();
	}
	internal static class IOErrors
	{
		public static bool IsLockedFile(IOException ex)
		{
			return true;
		}
	}
	internal sealed class NullSink : ILogEventSink
	{
		public void Emit(LogEvent logEvent)
		{
		}
	}
	internal sealed class PathRoller
	{
		[CompilerGenerated]
		private sealed class <SelectMatches>d__15 : global::System.Collections.Generic.IEnumerable<RollingLogFile>, global::System.Collections.IEnumerable, global::System.Collections.Generic.IEnumerator<RollingLogFile>, global::System.Collections.IEnumerator, global::System.IDisposable
		{
			private int <>1__state;

			private RollingLogFile <>2__current;

			private int <>l__initialThreadId;

			private global::System.Collections.Generic.IEnumerable<string> filenames;

			public global::System.Collections.Generic.IEnumerable<string> <>3__filenames;

			public PathRoller <>4__this;

			private global::System.Collections.Generic.IEnumerator<string> <>7__wrap1;

			RollingLogFile global::System.Collections.Generic.IEnumerator<RollingLogFile>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object global::System.Collections.IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <SelectMatches>d__15(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void global::System.IDisposable.Dispose()
			{
				int num = <>1__state;
				if (num == -3 || num == 1)
				{
					try
					{
					}
					finally
					{
						<>m__Finally1();
					}
				}
			}

			private bool MoveNext()
			{
				try
				{
					int num = <>1__state;
					PathRoller pathRoller = <>4__this;
					switch (num)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						<>7__wrap1 = filenames.GetEnumerator();
						<>1__state = -3;
						break;
					case 1:
						<>1__state = -3;
						break;
					}
					global::System.DateTime dateTime2 = default(global::System.DateTime);
					while (((global::System.Collections.IEnumerator)<>7__wrap1).MoveNext())
					{
						string current = <>7__wrap1.Current;
						Match val = pathRoller._filenameMatcher.Match(current);
						if (((Group)val).Success)
						{
							int? sequenceNumber = null;
							Group val2 = val.Groups["sequence"];
							if (val2.Captures.Count != 0)
							{
								string text = val2.Captures[0].Value.Substring(1);
								sequenceNumber = int.Parse(text, (IFormatProvider)(object)CultureInfo.InvariantCulture);
							}
							global::System.DateTime? dateTime = null;
							Group val3 = val.Groups["period"];
							if (val3.Captures.Count != 0 && global::System.DateTime.TryParseExact(val3.Captures[0].Value, pathRoller._periodFormat, (IFormatProvider)(object)CultureInfo.InvariantCulture, (DateTimeStyles)0, ref dateTime2))
							{
								dateTime = dateTime2;
							}
							<>2__current = new RollingLogFile(current, dateTime, sequenceNumber);
							<>1__state = 1;
							return true;
						}
					}
					<>m__Finally1();
					<>7__wrap1 = null;
					return false;
				}
				catch
				{
					//try-fault
					((global::System.IDisposable)this).Dispose();
					throw;
				}
			}

			bool global::System.Collections.IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			private void <>m__Finally1()
			{
				<>1__state = -1;
				if (<>7__wrap1 != null)
				{
					((global::System.IDisposable)<>7__wrap1).Dispose();
				}
			}

			[DebuggerHidden]
			void global::System.Collections.IEnumerator.Reset()
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			global::System.Collections.Generic.IEnumerator<RollingLogFile> global::System.Collections.Generic.IEnumerable<RollingLogFile>.GetEnumerator()
			{
				<SelectMatches>d__15 <SelectMatches>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					<SelectMatches>d__ = this;
				}
				else
				{
					<SelectMatches>d__ = new <SelectMatches>d__15(0)
					{
						<>4__this = <>4__this
					};
				}
				<SelectMatches>d__.filenames = <>3__filenames;
				return <SelectMatches>d__;
			}

			[DebuggerHidden]
			global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator()
			{
				return (global::System.Collections.IEnumerator)((global::System.Collections.Generic.IEnumerable<RollingLogFile>)this).GetEnumerator();
			}
		}

		private const string PeriodMatchGroup = "period";

		private const string SequenceNumberMatchGroup = "sequence";

		private readonly string _directory;

		private readonly string _filenamePrefix;

		private readonly string _filenameSuffix;

		private readonly Regex _filenameMatcher;

		private readonly RollingInterval _interval;

		private readonly string _periodFormat;

		public string LogFileDirectory => _directory;

		[field: CompilerGenerated]
		public string DirectorySearchPattern
		{
			[CompilerGenerated]
			get;
		}

		public PathRoller(string path, RollingInterval interval)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Expected O, but got Unknown
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			_interval = interval;
			_periodFormat = interval.GetFormat();
			string text = Path.GetDirectoryName(path);
			if (string.IsNullOrEmpty(text))
			{
				text = Directory.GetCurrentDirectory();
			}
			_directory = Path.GetFullPath(text);
			_filenamePrefix = Path.GetFileNameWithoutExtension(path);
			_filenameSuffix = Path.GetExtension(path);
			_filenameMatcher = new Regex(string.Concat(new string[7]
			{
				"^",
				Regex.Escape(_filenamePrefix),
				"(?<period>\\d{",
				_periodFormat.Length.ToString(),
				"})(?<sequence>_[0-9]{3,}){0,1}",
				Regex.Escape(_filenameSuffix),
				"$"
			}), (RegexOptions)8);
			DirectorySearchPattern = _filenamePrefix + "*" + _filenameSuffix;
		}

		public void GetLogFilePath(global::System.DateTime date, int? sequenceNumber, out string path)
		{
			string text = GetCurrentCheckpoint(date)?.ToString(_periodFormat, (IFormatProvider)(object)CultureInfo.InvariantCulture) ?? "";
			if (sequenceNumber.HasValue)
			{
				text = text + "_" + sequenceNumber.Value.ToString("000", (IFormatProvider)(object)CultureInfo.InvariantCulture);
			}
			path = Path.Combine(_directory, _filenamePrefix + text + _filenameSuffix);
		}

		[IteratorStateMachine(typeof(<SelectMatches>d__15))]
		public global::System.Collections.Generic.IEnumerable<RollingLogFile> SelectMatches(global::System.Collections.Generic.IEnumerable<string> filenames)
		{
			global::System.Collections.Generic.IEnumerator<string> enumerator = filenames.GetEnumerator();
			try
			{
				global::System.DateTime dateTime2 = default(global::System.DateTime);
				while (((global::System.Collections.IEnumerator)enumerator).MoveNext())
				{
					string current = enumerator.Current;
					Match val = _filenameMatcher.Match(current);
					if (((Group)val).Success)
					{
						int? sequenceNumber = null;
						Group val2 = val.Groups["sequence"];
						if (val2.Captures.Count != 0)
						{
							string text = val2.Captures[0].Value.Substring(1);
							sequenceNumber = int.Parse(text, (IFormatProvider)(object)CultureInfo.InvariantCulture);
						}
						global::System.DateTime? dateTime = null;
						Group val3 = val.Groups["period"];
						if (val3.Captures.Count != 0 && global::System.DateTime.TryParseExact(val3.Captures[0].Value, _periodFormat, (IFormatProvider)(object)CultureInfo.InvariantCulture, (DateTimeStyles)0, ref dateTime2))
						{
							dateTime = dateTime2;
						}
						yield return new RollingLogFile(current, dateTime, sequenceNumber);
					}
				}
			}
			finally
			{
				((global::System.IDisposable)enumerator)?.Dispose();
			}
		}

		public global::System.DateTime? GetCurrentCheckpoint(global::System.DateTime instant)
		{
			return _interval.GetCurrentCheckpoint(instant);
		}

		public global::System.DateTime? GetNextCheckpoint(global::System.DateTime instant)
		{
			return _interval.GetNextCheckpoint(instant);
		}
	}
	[Obsolete("This type will be removed from the public API in a future version; use `WriteTo.File(flushToDiskInterval:)` instead.")]
	public class PeriodicFlushToDiskSink : ILogEventSink, global::System.IDisposable
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static TimerCallback <>9__3_1;

			internal void <.ctor>b__3_1(object? _)
			{
			}
		}

		private readonly ILogEventSink _sink;

		private readonly Timer _timer;

		private int _flushRequired;

		public PeriodicFlushToDiskSink(ILogEventSink sink, TimeSpan flushInterval)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Expected O, but got Unknown
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			PeriodicFlushToDiskSink periodicFlushToDiskSink = this;
			_sink = sink ?? throw new ArgumentNullException("sink");
			IFlushableFileSink flushable = sink as IFlushableFileSink;
			if (flushable != null)
			{
				_timer = new Timer((TimerCallback)delegate
				{
					periodicFlushToDiskSink.FlushToDisk(flushable);
				}, (object)null, flushInterval, flushInterval);
				return;
			}
			object obj = <>c.<>9__3_1;
			if (obj == null)
			{
				TimerCallback val = delegate
				{
				};
				<>c.<>9__3_1 = val;
				obj = (object)val;
			}
			_timer = new Timer((TimerCallback)obj, (object)null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
			SelfLog.WriteLine("{0} configured to flush {1}, but {2} not implemented", (object)typeof(PeriodicFlushToDiskSink), (object)sink, (object)"IFlushableFileSink");
		}

		public void Emit(LogEvent logEvent)
		{
			_sink.Emit(logEvent);
			Interlocked.Exchange(ref _flushRequired, 1);
		}

		public void Dispose()
		{
			_timer.Dispose();
			(_sink as global::System.IDisposable)?.Dispose();
		}

		private void FlushToDisk(IFlushableFileSink flushable)
		{
			try
			{
				if (Interlocked.CompareExchange(ref _flushRequired, 0, 1) == 1)
				{
					flushable.FlushToDisk();
				}
			}
			catch (global::System.Exception ex)
			{
				SelfLog.WriteLine("{0} could not flush the underlying sink to disk: {1}", (object)typeof(PeriodicFlushToDiskSink), (object)ex, (object)null);
			}
		}
	}
	internal sealed class RollingFileSink : ILogEventSink, IFlushableFileSink, global::System.IDisposable
	{
		private readonly PathRoller _roller;

		private readonly ITextFormatter _textFormatter;

		private readonly long? _fileSizeLimitBytes;

		private readonly int? _retainedFileCountLimit;

		private readonly TimeSpan? _retainedFileTimeLimit;

		private readonly Encoding? _encoding;

		private readonly bool _buffered;

		private readonly bool _shared;

		private readonly bool _rollOnFileSizeLimit;

		private readonly FileLifecycleHooks? _hooks;

		private readonly object _syncRoot = new object();

		private bool _isDisposed;

		private global::System.DateTime? _nextCheckpoint;

		private IFileSink? _currentFile;

		private int? _currentFileSequence;

		public RollingFileSink(string path, ITextFormatter textFormatter, long? fileSizeLimitBytes, int? retainedFileCountLimit, Encoding? encoding, bool buffered, bool shared, RollingInterval rollingInterval, bool rollOnFileSizeLimit, FileLifecycleHooks? hooks, TimeSpan? retainedFileTimeLimit)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes.GetValueOrDefault() < 1)
			{
				throw new ArgumentException("Invalid value provided; file size limit must be at least 1 byte, or null.");
			}
			if (retainedFileCountLimit.HasValue && retainedFileCountLimit.GetValueOrDefault() < 1)
			{
				throw new ArgumentException("Zero or negative value provided; retained file count limit must be at least 1.");
			}
			if (retainedFileTimeLimit.HasValue)
			{
				TimeSpan? val = retainedFileTimeLimit;
				TimeSpan zero = TimeSpan.Zero;
				if (val.HasValue && val.GetValueOrDefault() < zero)
				{
					throw new ArgumentException("Negative value provided; retained file time limit must be non-negative.", "retainedFileTimeLimit");
				}
			}
			_roller = new PathRoller(path, rollingInterval);
			_textFormatter = textFormatter;
			_fileSizeLimitBytes = fileSizeLimitBytes;
			_retainedFileCountLimit = retainedFileCountLimit;
			_retainedFileTimeLimit = retainedFileTimeLimit;
			_encoding = encoding;
			_buffered = buffered;
			_shared = shared;
			_rollOnFileSizeLimit = rollOnFileSizeLimit;
			_hooks = hooks;
		}

		public void Emit(LogEvent logEvent)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (logEvent == null)
			{
				throw new ArgumentNullException("logEvent");
			}
			lock (_syncRoot)
			{
				if (_isDisposed)
				{
					throw new ObjectDisposedException("The log file has been disposed.");
				}
				global::System.DateTime dateTimeNow = Clock.DateTimeNow;
				AlignCurrentFileTo(dateTimeNow);
				while (true)
				{
					IFileSink? currentFile = _currentFile;
					if (currentFile != null && !currentFile.EmitOrOverflow(logEvent) && _rollOnFileSizeLimit)
					{
						AlignCurrentFileTo(dateTimeNow, nextSequence: true);
						continue;
					}
					break;
				}
			}
		}

		private void AlignCurrentFileTo(global::System.DateTime now, bool nextSequence = false)
		{
			if (!_nextCheckpoint.HasValue)
			{
				OpenFile(now);
			}
			else if (nextSequence || now >= _nextCheckpoint.Value)
			{
				int? minSequence = null;
				if (nextSequence)
				{
					minSequence = (_currentFileSequence.HasValue ? new int?(_currentFileSequence.Value + 1) : new int?(1));
				}
				CloseFile();
				OpenFile(now, minSequence);
			}
		}

		private void OpenFile(global::System.DateTime now, int? minSequence = null)
		{
			//IL_01a5: Expected O, but got Unknown
			global::System.DateTime? currentCheckpoint = _roller.GetCurrentCheckpoint(now);
			_nextCheckpoint = _roller.GetNextCheckpoint(now) ?? now.AddMinutes(30.0);
			global::System.Collections.Generic.IEnumerable<string> filenames = Enumerable.Empty<string>();
			try
			{
				if (Directory.Exists(_roller.LogFileDirectory))
				{
					filenames = Enumerable.Select<string, string>((global::System.Collections.Generic.IEnumerable<string>)Directory.GetFiles(_roller.LogFileDirectory, _roller.DirectorySearchPattern), (Func<string, string>)((string f) => Path.GetFileName(f)));
				}
			}
			catch (DirectoryNotFoundException)
			{
			}
			int? num = Enumerable.MaxBy<RollingLogFile, int?>(Enumerable.Where<RollingLogFile>(_roller.SelectMatches(filenames), (Func<RollingLogFile, bool>)delegate(RollingLogFile m)
			{
				global::System.DateTime? dateTime = m.DateTime;
				global::System.DateTime? dateTime2 = currentCheckpoint;
				if (dateTime.HasValue != dateTime2.HasValue)
				{
					return false;
				}
				return !dateTime.HasValue || dateTime.GetValueOrDefault() == dateTime2.GetValueOrDefault();
			}), (Func<RollingLogFile, int?>)((RollingLogFile m) => m.SequenceNumber))?.SequenceNumber;
			if (minSequence.HasValue && (!num.HasValue || num.Value < minSequence.Value))
			{
				num = minSequence;
			}
			for (int i = 0; i < 3; i++)
			{
				_roller.GetLogFilePath(now, num, out string path);
				try
				{
					IFileSink currentFile;
					if (!_shared)
					{
						IFileSink fileSink = new FileSink(path, _textFormatter, _fileSizeLimitBytes, _encoding, _buffered, _hooks);
						currentFile = fileSink;
					}
					else
					{
						IFileSink fileSink = new SharedFileSink(path, _textFormatter, _fileSizeLimitBytes, _encoding);
						currentFile = fileSink;
					}
					_currentFile = currentFile;
					_currentFileSequence = num;
				}
				catch (IOException val2)
				{
					if (IOErrors.IsLockedFile(val2))
					{
						SelfLog.WriteLine("File target {0} was locked, attempting to open next in sequence (attempt {1})", (object)path, (object)(i + 1), (object)null);
						num = num.GetValueOrDefault() + 1;
						continue;
					}
					throw;
				}
				ApplyRetentionPolicy(path, now);
				break;
			}
		}

		private void ApplyRetentionPolicy(string currentFilePath, global::System.DateTime now)
		{
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			if (!_retainedFileCountLimit.HasValue && !_retainedFileTimeLimit.HasValue)
			{
				return;
			}
			string currentFileName = Path.GetFileName(currentFilePath);
			global::System.Collections.Generic.IEnumerable<string> filenames = Enumerable.Union<string>(Enumerable.Select<string, string>((global::System.Collections.Generic.IEnumerable<string>)Directory.GetFiles(_roller.LogFileDirectory, _roller.DirectorySearchPattern), (Func<string, string>)((string f) => Path.GetFileName(f))), (global::System.Collections.Generic.IEnumerable<string>)new string[1] { currentFileName });
			Enumerator<string> enumerator = Enumerable.ToList<string>(Enumerable.Select<RollingLogFile, string>(Enumerable.SkipWhile<RollingLogFile>(Enumerable.Where<RollingLogFile>((global::System.Collections.Generic.IEnumerable<RollingLogFile>)Enumerable.ThenByDescending<RollingLogFile, int?>(Enumerable.OrderByDescending<RollingLogFile, global::System.DateTime?>(_roller.SelectMatches(filenames), (Func<RollingLogFile, global::System.DateTime?>)((RollingLogFile m) => m.DateTime)), (Func<RollingLogFile, int?>)((RollingLogFile m) => m.SequenceNumber)), (Func<RollingLogFile, bool>)((RollingLogFile n) => StringComparer.OrdinalIgnoreCase.Compare(currentFileName, n.Filename) != 0)), (Func<RollingLogFile, int, bool>)((RollingLogFile f, int i) => ShouldRetainFile(f, i, now))), (Func<RollingLogFile, string>)((RollingLogFile x) => x.Filename))).GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					string current = enumerator.Current;
					string text = Path.Combine(_roller.LogFileDirectory, current);
					try
					{
						_hooks?.OnFileDeleting(text);
						File.Delete(text);
					}
					catch (global::System.Exception ex)
					{
						SelfLog.WriteLine("Error {0} while processing obsolete log file {1}", (object)ex, (object)text, (object)null);
					}
				}
			}
			finally
			{
				((global::System.IDisposable)enumerator).Dispose();
			}
		}

		private bool ShouldRetainFile(RollingLogFile file, int index, global::System.DateTime now)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			if (_retainedFileCountLimit.HasValue && index >= _retainedFileCountLimit.Value - 1)
			{
				return false;
			}
			if (_retainedFileTimeLimit.HasValue && file.DateTime.HasValue && file.DateTime.Value < now.Subtract(_retainedFileTimeLimit.Value))
			{
				return false;
			}
			return true;
		}

		public void Dispose()
		{
			lock (_syncRoot)
			{
				if (_currentFile != null)
				{
					CloseFile();
					_isDisposed = true;
				}
			}
		}

		private void CloseFile()
		{
			if (_currentFile != null)
			{
				(_currentFile as global::System.IDisposable)?.Dispose();
				_currentFile = null;
			}
			_nextCheckpoint = null;
		}

		public void FlushToDisk()
		{
			lock (_syncRoot)
			{
				_currentFile?.FlushToDisk();
			}
		}
	}
	internal static class RollingIntervalExtensions
	{
		public static string GetFormat(this RollingInterval interval)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			return interval switch
			{
				RollingInterval.Infinite => "", 
				RollingInterval.Year => "yyyy", 
				RollingInterval.Month => "yyyyMM", 
				RollingInterval.Day => "yyyyMMdd", 
				RollingInterval.Hour => "yyyyMMddHH", 
				RollingInterval.Minute => "yyyyMMddHHmm", 
				_ => throw new ArgumentException("Invalid rolling interval."), 
			};
		}

		public static global::System.DateTime? GetCurrentCheckpoint(this RollingInterval interval, global::System.DateTime instant)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			return interval switch
			{
				RollingInterval.Infinite => null, 
				RollingInterval.Year => new global::System.DateTime(instant.Year, 1, 1, 0, 0, 0, instant.Kind), 
				RollingInterval.Month => new global::System.DateTime(instant.Year, instant.Month, 1, 0, 0, 0, instant.Kind), 
				RollingInterval.Day => new global::System.DateTime(instant.Year, instant.Month, instant.Day, 0, 0, 0, instant.Kind), 
				RollingInterval.Hour => new global::System.DateTime(instant.Year, instant.Month, instant.Day, instant.Hour, 0, 0, instant.Kind), 
				RollingInterval.Minute => new global::System.DateTime(instant.Year, instant.Month, instant.Day, instant.Hour, instant.Minute, 0, instant.Kind), 
				_ => throw new ArgumentException("Invalid rolling interval."), 
			};
		}

		public static global::System.DateTime? GetNextCheckpoint(this RollingInterval interval, global::System.DateTime instant)
		{
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			global::System.DateTime? currentCheckpoint = interval.GetCurrentCheckpoint(instant);
			if (!currentCheckpoint.HasValue)
			{
				return null;
			}
			return interval switch
			{
				RollingInterval.Year => currentCheckpoint.Value.AddYears(1), 
				RollingInterval.Month => currentCheckpoint.Value.AddMonths(1), 
				RollingInterval.Day => currentCheckpoint.Value.AddDays(1.0), 
				RollingInterval.Hour => currentCheckpoint.Value.AddHours(1.0), 
				RollingInterval.Minute => currentCheckpoint.Value.AddMinutes(1.0), 
				_ => throw new ArgumentException("Invalid rolling interval."), 
			};
		}
	}
	internal class RollingLogFile
	{
		[field: CompilerGenerated]
		public string Filename
		{
			[CompilerGenerated]
			get;
		}

		[field: CompilerGenerated]
		public global::System.DateTime? DateTime
		{
			[CompilerGenerated]
			get;
		}

		[field: CompilerGenerated]
		public int? SequenceNumber
		{
			[CompilerGenerated]
			get;
		}

		public RollingLogFile(string filename, global::System.DateTime? dateTime, int? sequenceNumber)
		{
			Filename = filename;
			DateTime = dateTime;
			SequenceNumber = sequenceNumber;
			base..ctor();
		}
	}
	[Obsolete("This type will be removed from the public API in a future version; use `WriteTo.File(shared: true)` instead.")]
	public sealed class SharedFileSink : IFileSink, ILogEventSink, IFlushableFileSink, global::System.IDisposable
	{
		private readonly TextWriter _output;

		private readonly FileStream _underlyingStream;

		private readonly ITextFormatter _textFormatter;

		private readonly long? _fileSizeLimitBytes;

		private readonly object _syncRoot = new object();

		private const string MutexNameSuffix = ".serilog";

		private const int MutexWaitTimeout = 10000;

		private readonly Mutex _mutex;

		public SharedFileSink(string path, ITextFormatter textFormatter, long? fileSizeLimitBytes, Encoding? encoding = null)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Expected O, but got Unknown
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Expected O, but got Unknown
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes.GetValueOrDefault() < 1)
			{
				throw new ArgumentException("Invalid value provided; file size limit must be at least 1 byte, or null.");
			}
			_textFormatter = textFormatter ?? throw new ArgumentNullException("textFormatter");
			_fileSizeLimitBytes = fileSizeLimitBytes;
			string directoryName = Path.GetDirectoryName(path);
			if (!string.IsNullOrWhiteSpace(directoryName) && !Directory.Exists(directoryName))
			{
				Directory.CreateDirectory(directoryName);
			}
			string text = Path.GetFullPath(path).Replace(Path.DirectorySeparatorChar, ':') + ".serilog";
			_mutex = new Mutex(false, text);
			_underlyingStream = File.Open(path, (FileMode)6, (FileAccess)2, (FileShare)3);
			_output = (TextWriter)new StreamWriter((Stream)(object)_underlyingStream, (Encoding)(((object)encoding) ?? ((object)new UTF8Encoding(false))));
		}

		bool IFileSink.EmitOrOverflow(LogEvent logEvent)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (logEvent == null)
			{
				throw new ArgumentNullException("logEvent");
			}
			lock (_syncRoot)
			{
				if (!TryAcquireMutex())
				{
					return true;
				}
				try
				{
					((Stream)_underlyingStream).Seek(0L, (SeekOrigin)2);
					if (_fileSizeLimitBytes.HasValue && ((Stream)_underlyingStream).Length >= _fileSizeLimitBytes.Value)
					{
						return false;
					}
					_textFormatter.Format(logEvent, _output);
					_output.Flush();
					((Stream)_underlyingStream).Flush();
					return true;
				}
				finally
				{
					ReleaseMutex();
				}
			}
		}

		public void Emit(LogEvent logEvent)
		{
			((IFileSink)this).EmitOrOverflow(logEvent);
		}

		public void Dispose()
		{
			lock (_syncRoot)
			{
				_output.Dispose();
				((WaitHandle)_mutex).Dispose();
			}
		}

		public void FlushToDisk()
		{
			lock (_syncRoot)
			{
				if (!TryAcquireMutex())
				{
					return;
				}
				try
				{
					_underlyingStream.Flush(true);
				}
				finally
				{
					ReleaseMutex();
				}
			}
		}

		private bool TryAcquireMutex()
		{
			try
			{
				if (!((WaitHandle)_mutex).WaitOne(10000))
				{
					SelfLog.WriteLine("Shared file mutex could not be acquired within {0} ms", (object)10000, (object)null, (object)null);
					return false;
				}
			}
			catch (AbandonedMutexException)
			{
				SelfLog.WriteLine("Inherited shared file mutex after abandonment by another process", (object)null, (object)null, (object)null);
			}
			return true;
		}

		private void ReleaseMutex()
		{
			_mutex.ReleaseMutex();
		}
	}
	internal sealed class WriteCountingStream : Stream
	{
		private readonly Stream _stream;

		[field: CompilerGenerated]
		public long CountedLength
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			private set;
		}

		public override bool CanRead => false;

		public override bool CanSeek => _stream.CanSeek;

		public override bool CanWrite => true;

		public override long Length => _stream.Length;

		public override long Position
		{
			get
			{
				return _stream.Position;
			}
			set
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				throw new NotSupportedException();
			}
		}

		public WriteCountingStream(Stream stream)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			_stream = stream ?? throw new ArgumentNullException("stream");
			CountedLength = stream.Length;
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				_stream.Dispose();
			}
			((Stream)this).Dispose(disposing);
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			_stream.Write(buffer, offset, count);
			CountedLength += count;
		}

		public override void Flush()
		{
			_stream.Flush();
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			throw new InvalidOperationException("Seek operations are not available through `WriteCountingStream`.");
		}

		public override void SetLength(long value)
		{
			_stream.SetLength(value);
			if (value < CountedLength)
			{
				CountedLength = _stream.Length;
			}
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			throw new NotSupportedException();
		}
	}
}