Decompiled source of AtlyssDiscordRichPresence v1.4.0

plugins/DiscordRPC.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using DiscordRPC.Converters;
using DiscordRPC.Events;
using DiscordRPC.Exceptions;
using DiscordRPC.Helper;
using DiscordRPC.IO;
using DiscordRPC.Logging;
using DiscordRPC.Message;
using DiscordRPC.RPC;
using DiscordRPC.RPC.Commands;
using DiscordRPC.RPC.Payload;
using DiscordRPC.Registry;
using Microsoft.Win32;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("Discord RPC")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Discord RPC")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("819d20d6-8d88-45c1-a4d2-aa21f10abd19")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace DiscordRPC
{
	public class Configuration
	{
		[JsonProperty("api_endpoint")]
		public string ApiEndpoint { get; set; }

		[JsonProperty("cdn_host")]
		public string CdnHost { get; set; }

		[JsonProperty("environment")]
		public string Environment { get; set; }
	}
	public sealed class DiscordRpcClient : IDisposable
	{
		private ILogger _logger;

		private RpcConnection connection;

		private bool _shutdownOnly = true;

		private object _sync = new object();

		public bool HasRegisteredUriScheme { get; private set; }

		public string ApplicationID { get; private set; }

		public string SteamID { get; private set; }

		public int ProcessID { get; private set; }

		public int MaxQueueSize { get; private set; }

		public bool IsDisposed { get; private set; }

		public ILogger Logger
		{
			get
			{
				return _logger;
			}
			set
			{
				_logger = value;
				if (connection != null)
				{
					connection.Logger = value;
				}
			}
		}

		public bool AutoEvents { get; private set; }

		public bool SkipIdenticalPresence { get; set; }

		public int TargetPipe { get; private set; }

		public RichPresence CurrentPresence { get; private set; }

		public EventType Subscription { get; private set; }

		public User CurrentUser { get; private set; }

		public Configuration Configuration { get; private set; }

		public bool IsInitialized { get; private set; }

		public bool ShutdownOnly
		{
			get
			{
				return _shutdownOnly;
			}
			set
			{
				_shutdownOnly = value;
				if (connection != null)
				{
					connection.ShutdownOnly = value;
				}
			}
		}

		public event OnReadyEvent OnReady;

		public event OnCloseEvent OnClose;

		public event OnErrorEvent OnError;

		public event OnPresenceUpdateEvent OnPresenceUpdate;

		public event OnSubscribeEvent OnSubscribe;

		public event OnUnsubscribeEvent OnUnsubscribe;

		public event OnJoinEvent OnJoin;

		public event OnSpectateEvent OnSpectate;

		public event OnJoinRequestedEvent OnJoinRequested;

		public event OnConnectionEstablishedEvent OnConnectionEstablished;

		public event OnConnectionFailedEvent OnConnectionFailed;

		public event OnRpcMessageEvent OnRpcMessage;

		public DiscordRpcClient(string applicationID)
			: this(applicationID, -1, null, autoEvents: true, null)
		{
		}

		public DiscordRpcClient(string applicationID, int pipe = -1, ILogger logger = null, bool autoEvents = true, INamedPipeClient client = null)
		{
			if (string.IsNullOrEmpty(applicationID))
			{
				throw new ArgumentNullException("applicationID");
			}
			ApplicationID = applicationID.Trim();
			TargetPipe = pipe;
			ProcessID = Process.GetCurrentProcess().Id;
			HasRegisteredUriScheme = false;
			AutoEvents = autoEvents;
			SkipIdenticalPresence = true;
			_logger = logger ?? new NullLogger();
			connection = new RpcConnection(ApplicationID, ProcessID, TargetPipe, client ?? new ManagedNamedPipeClient(), (!autoEvents) ? 128u : 0u)
			{
				ShutdownOnly = _shutdownOnly,
				Logger = _logger
			};
			connection.OnRpcMessage += delegate(object sender, IMessage msg)
			{
				if (this.OnRpcMessage != null)
				{
					this.OnRpcMessage(this, msg);
				}
				if (AutoEvents)
				{
					ProcessMessage(msg);
				}
			};
		}

		public IMessage[] Invoke()
		{
			if (AutoEvents)
			{
				Logger.Error("Cannot Invoke client when AutomaticallyInvokeEvents has been set.");
				return new IMessage[0];
			}
			IMessage[] array = connection.DequeueMessages();
			foreach (IMessage message in array)
			{
				ProcessMessage(message);
			}
			return array;
		}

		private void ProcessMessage(IMessage message)
		{
			if (message == null)
			{
				return;
			}
			switch (message.Type)
			{
			case MessageType.PresenceUpdate:
				lock (_sync)
				{
					if (message is PresenceMessage presenceMessage)
					{
						if (presenceMessage.Presence == null)
						{
							CurrentPresence = null;
						}
						else if (CurrentPresence == null)
						{
							CurrentPresence = new RichPresence().Merge(presenceMessage.Presence);
						}
						else
						{
							CurrentPresence.Merge(presenceMessage.Presence);
						}
						presenceMessage.Presence = CurrentPresence;
					}
				}
				if (this.OnPresenceUpdate != null)
				{
					this.OnPresenceUpdate(this, message as PresenceMessage);
				}
				break;
			case MessageType.Ready:
				if (message is ReadyMessage readyMessage)
				{
					lock (_sync)
					{
						Configuration = readyMessage.Configuration;
						CurrentUser = readyMessage.User;
					}
					SynchronizeState();
				}
				if (this.OnReady != null)
				{
					this.OnReady(this, message as ReadyMessage);
				}
				break;
			case MessageType.Close:
				if (this.OnClose != null)
				{
					this.OnClose(this, message as CloseMessage);
				}
				break;
			case MessageType.Error:
				if (this.OnError != null)
				{
					this.OnError(this, message as ErrorMessage);
				}
				break;
			case MessageType.JoinRequest:
				if (Configuration != null && message is JoinRequestMessage joinRequestMessage)
				{
					joinRequestMessage.User.SetConfiguration(Configuration);
				}
				if (this.OnJoinRequested != null)
				{
					this.OnJoinRequested(this, message as JoinRequestMessage);
				}
				break;
			case MessageType.Subscribe:
				lock (_sync)
				{
					SubscribeMessage subscribeMessage = message as SubscribeMessage;
					Subscription |= subscribeMessage.Event;
				}
				if (this.OnSubscribe != null)
				{
					this.OnSubscribe(this, message as SubscribeMessage);
				}
				break;
			case MessageType.Unsubscribe:
				lock (_sync)
				{
					UnsubscribeMessage unsubscribeMessage = message as UnsubscribeMessage;
					Subscription &= ~unsubscribeMessage.Event;
				}
				if (this.OnUnsubscribe != null)
				{
					this.OnUnsubscribe(this, message as UnsubscribeMessage);
				}
				break;
			case MessageType.Join:
				if (this.OnJoin != null)
				{
					this.OnJoin(this, message as JoinMessage);
				}
				break;
			case MessageType.Spectate:
				if (this.OnSpectate != null)
				{
					this.OnSpectate(this, message as SpectateMessage);
				}
				break;
			case MessageType.ConnectionEstablished:
				if (this.OnConnectionEstablished != null)
				{
					this.OnConnectionEstablished(this, message as ConnectionEstablishedMessage);
				}
				break;
			case MessageType.ConnectionFailed:
				if (this.OnConnectionFailed != null)
				{
					this.OnConnectionFailed(this, message as ConnectionFailedMessage);
				}
				break;
			default:
				Logger.Error("Message was queued with no appropriate handle! {0}", message.Type);
				break;
			}
		}

		public void Respond(JoinRequestMessage request, bool acceptRequest)
		{
			if (IsDisposed)
			{
				throw new ObjectDisposedException("Discord IPC Client");
			}
			if (connection == null)
			{
				throw new ObjectDisposedException("Connection", "Cannot initialize as the connection has been deinitialized");
			}
			if (!IsInitialized)
			{
				throw new UninitializedException();
			}
			connection.EnqueueCommand(new RespondCommand
			{
				Accept = acceptRequest,
				UserID = request.User.ID.ToString()
			});
		}

		public void SetPresence(RichPresence presence)
		{
			if (IsDisposed)
			{
				throw new ObjectDisposedException("Discord IPC Client");
			}
			if (connection == null)
			{
				throw new ObjectDisposedException("Connection", "Cannot initialize as the connection has been deinitialized");
			}
			if (!IsInitialized)
			{
				Logger.Warning("The client is not yet initialized, storing the presence as a state instead.");
			}
			if (presence == null)
			{
				if (!SkipIdenticalPresence || CurrentPresence != null)
				{
					connection.EnqueueCommand(new PresenceCommand
					{
						PID = ProcessID,
						Presence = null
					});
				}
			}
			else
			{
				if (presence.HasSecrets() && !HasRegisteredUriScheme)
				{
					throw new BadPresenceException("Cannot send a presence with secrets as this object has not registered a URI scheme. Please enable the uri scheme registration in the DiscordRpcClient constructor.");
				}
				if (presence.HasParty() && presence.Party.Max < presence.Party.Size)
				{
					throw new BadPresenceException("Presence maximum party size cannot be smaller than the current size.");
				}
				if (presence.HasSecrets() && !presence.HasParty())
				{
					Logger.Warning("The presence has set the secrets but no buttons will show as there is no party available.");
				}
				if (!SkipIdenticalPresence || !presence.Matches(CurrentPresence))
				{
					connection.EnqueueCommand(new PresenceCommand
					{
						PID = ProcessID,
						Presence = presence.Clone()
					});
				}
			}
			lock (_sync)
			{
				CurrentPresence = presence?.Clone();
			}
		}

		public RichPresence Update(Action<RichPresence> func)
		{
			if (!IsInitialized)
			{
				throw new UninitializedException();
			}
			RichPresence richPresence;
			lock (_sync)
			{
				richPresence = ((CurrentPresence == null) ? new RichPresence() : CurrentPresence.Clone());
			}
			func(richPresence);
			SetPresence(richPresence);
			return richPresence;
		}

		public RichPresence UpdateType(ActivityType type)
		{
			return Update(delegate(RichPresence p)
			{
				p.Type = type;
			});
		}

		public RichPresence UpdateButtons(Button[] buttons = null)
		{
			return Update(delegate(RichPresence p)
			{
				p.Buttons = buttons;
			});
		}

		public RichPresence SetButton(Button button, int index = 0)
		{
			return Update(delegate(RichPresence p)
			{
				p.Buttons[index] = button;
			});
		}

		public RichPresence UpdateDetails(string details)
		{
			return Update(delegate(RichPresence p)
			{
				p.Details = details;
			});
		}

		public RichPresence UpdateState(string state)
		{
			return Update(delegate(RichPresence p)
			{
				p.State = state;
			});
		}

		public RichPresence UpdateParty(Party party)
		{
			return Update(delegate(RichPresence p)
			{
				p.Party = party;
			});
		}

		public RichPresence UpdatePartySize(int size)
		{
			return Update(delegate(RichPresence p)
			{
				if (p.Party == null)
				{
					throw new BadPresenceException("Cannot set the size of the party if the party does not exist");
				}
				p.Party.Size = size;
			});
		}

		public RichPresence UpdatePartySize(int size, int max)
		{
			return Update(delegate(RichPresence p)
			{
				if (p.Party == null)
				{
					throw new BadPresenceException("Cannot set the size of the party if the party does not exist");
				}
				p.Party.Size = size;
				p.Party.Max = max;
			});
		}

		public RichPresence UpdateLargeAsset(string key = null, string tooltip = null)
		{
			return Update(delegate(RichPresence p)
			{
				if (p.Assets == null)
				{
					p.Assets = new Assets();
				}
				p.Assets.LargeImageKey = key ?? p.Assets.LargeImageKey;
				p.Assets.LargeImageText = tooltip ?? p.Assets.LargeImageText;
			});
		}

		public RichPresence UpdateSmallAsset(string key = null, string tooltip = null)
		{
			return Update(delegate(RichPresence p)
			{
				if (p.Assets == null)
				{
					p.Assets = new Assets();
				}
				p.Assets.SmallImageKey = key ?? p.Assets.SmallImageKey;
				p.Assets.SmallImageText = tooltip ?? p.Assets.SmallImageText;
			});
		}

		public RichPresence UpdateSecrets(Secrets secrets)
		{
			return Update(delegate(RichPresence p)
			{
				p.Secrets = secrets;
			});
		}

		public RichPresence UpdateStartTime()
		{
			return UpdateStartTime(DateTime.UtcNow);
		}

		public RichPresence UpdateStartTime(DateTime time)
		{
			return Update(delegate(RichPresence p)
			{
				if (p.Timestamps == null)
				{
					p.Timestamps = new Timestamps();
				}
				p.Timestamps.Start = time;
			});
		}

		public RichPresence UpdateEndTime()
		{
			return UpdateEndTime(DateTime.UtcNow);
		}

		public RichPresence UpdateEndTime(DateTime time)
		{
			return Update(delegate(RichPresence p)
			{
				if (p.Timestamps == null)
				{
					p.Timestamps = new Timestamps();
				}
				p.Timestamps.End = time;
			});
		}

		public RichPresence UpdateClearTime()
		{
			return Update(delegate(RichPresence p)
			{
				p.Timestamps = null;
			});
		}

		public void ClearPresence()
		{
			if (IsDisposed)
			{
				throw new ObjectDisposedException("Discord IPC Client");
			}
			if (!IsInitialized)
			{
				throw new UninitializedException();
			}
			if (connection == null)
			{
				throw new ObjectDisposedException("Connection", "Cannot initialize as the connection has been deinitialized");
			}
			SetPresence(null);
		}

		public bool RegisterUriScheme(string steamAppID = null, string executable = null)
		{
			UriSchemeRegister uriSchemeRegister = new UriSchemeRegister(_logger, ApplicationID, steamAppID, executable);
			return HasRegisteredUriScheme = uriSchemeRegister.RegisterUriScheme();
		}

		public void Subscribe(EventType type)
		{
			SetSubscription(Subscription | type);
		}

		[Obsolete("Replaced with Unsubscribe", true)]
		public void Unubscribe(EventType type)
		{
			SetSubscription(Subscription & ~type);
		}

		public void Unsubscribe(EventType type)
		{
			SetSubscription(Subscription & ~type);
		}

		public void SetSubscription(EventType type)
		{
			if (IsInitialized)
			{
				SubscribeToTypes(Subscription & ~type, isUnsubscribe: true);
				SubscribeToTypes(~Subscription & type, isUnsubscribe: false);
			}
			else
			{
				Logger.Warning("Client has not yet initialized, but events are being subscribed too. Storing them as state instead.");
			}
			lock (_sync)
			{
				Subscription = type;
			}
		}

		private void SubscribeToTypes(EventType type, bool isUnsubscribe)
		{
			if (type != 0)
			{
				if (IsDisposed)
				{
					throw new ObjectDisposedException("Discord IPC Client");
				}
				if (!IsInitialized)
				{
					throw new UninitializedException();
				}
				if (connection == null)
				{
					throw new ObjectDisposedException("Connection", "Cannot initialize as the connection has been deinitialized");
				}
				if (!HasRegisteredUriScheme)
				{
					throw new InvalidConfigurationException("Cannot subscribe/unsubscribe to an event as this application has not registered a URI Scheme. Call RegisterUriScheme().");
				}
				if ((type & EventType.Spectate) == EventType.Spectate)
				{
					connection.EnqueueCommand(new SubscribeCommand
					{
						Event = ServerEvent.ActivitySpectate,
						IsUnsubscribe = isUnsubscribe
					});
				}
				if ((type & EventType.Join) == EventType.Join)
				{
					connection.EnqueueCommand(new SubscribeCommand
					{
						Event = ServerEvent.ActivityJoin,
						IsUnsubscribe = isUnsubscribe
					});
				}
				if ((type & EventType.JoinRequest) == EventType.JoinRequest)
				{
					connection.EnqueueCommand(new SubscribeCommand
					{
						Event = ServerEvent.ActivityJoinRequest,
						IsUnsubscribe = isUnsubscribe
					});
				}
			}
		}

		public void SynchronizeState()
		{
			if (!IsInitialized)
			{
				throw new UninitializedException();
			}
			SetPresence(CurrentPresence);
			if (HasRegisteredUriScheme)
			{
				SubscribeToTypes(Subscription, isUnsubscribe: false);
			}
		}

		public bool Initialize()
		{
			if (IsDisposed)
			{
				throw new ObjectDisposedException("Discord IPC Client");
			}
			if (IsInitialized)
			{
				throw new UninitializedException("Cannot initialize a client that is already initialized");
			}
			if (connection == null)
			{
				throw new ObjectDisposedException("Connection", "Cannot initialize as the connection has been deinitialized");
			}
			return IsInitialized = connection.AttemptConnection();
		}

		public void Deinitialize()
		{
			if (!IsInitialized)
			{
				throw new UninitializedException("Cannot deinitialize a client that has not been initalized.");
			}
			connection.Close();
			IsInitialized = false;
		}

		public void Dispose()
		{
			if (!IsDisposed)
			{
				if (IsInitialized)
				{
					Deinitialize();
				}
				IsDisposed = true;
			}
		}
	}
	[Flags]
	public enum EventType
	{
		None = 0,
		Spectate = 1,
		Join = 2,
		JoinRequest = 4
	}
	[Serializable]
	[JsonObject(/*Could not decode attribute arguments.*/)]
	public class BaseRichPresence
	{
		protected internal string _state;

		protected internal string _details;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string State
		{
			get
			{
				return _state;
			}
			set
			{
				if (!ValidateString(value, out _state, 128, Encoding.UTF8))
				{
					throw new StringOutOfRangeException("State", 0, 128);
				}
			}
		}

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string Details
		{
			get
			{
				return _details;
			}
			set
			{
				if (!ValidateString(value, out _details, 128, Encoding.UTF8))
				{
					throw new StringOutOfRangeException(128);
				}
			}
		}

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Timestamps Timestamps { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Assets Assets { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Party Party { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Secrets Secrets { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public ActivityType Type { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		[Obsolete("This was going to be used, but was replaced by JoinSecret instead")]
		private bool Instance { get; set; }

		public bool HasTimestamps()
		{
			return Timestamps != null && (Timestamps.Start.HasValue || Timestamps.End.HasValue);
		}

		public bool HasAssets()
		{
			return Assets != null;
		}

		public bool HasParty()
		{
			return Party != null && Party.ID != null;
		}

		public bool HasSecrets()
		{
			return Secrets != null && (Secrets.JoinSecret != null || Secrets.SpectateSecret != null);
		}

		internal static bool ValidateString(string str, out string result, int bytes, Encoding encoding)
		{
			result = str;
			if (str == null)
			{
				return true;
			}
			string str2 = str.Trim();
			if (!str2.WithinLength(bytes, encoding))
			{
				return false;
			}
			result = str2.GetNullOrString();
			return true;
		}

		public static implicit operator bool(BaseRichPresence presesnce)
		{
			return presesnce != null;
		}

		internal virtual bool Matches(RichPresence other)
		{
			if (other == null)
			{
				return false;
			}
			if (State != other.State || Details != other.Details || Type != other.Type)
			{
				return false;
			}
			if (Timestamps != null)
			{
				if (other.Timestamps == null || other.Timestamps.StartUnixMilliseconds != Timestamps.StartUnixMilliseconds || other.Timestamps.EndUnixMilliseconds != Timestamps.EndUnixMilliseconds)
				{
					return false;
				}
			}
			else if (other.Timestamps != null)
			{
				return false;
			}
			if (Secrets != null)
			{
				if (other.Secrets == null || other.Secrets.JoinSecret != Secrets.JoinSecret || other.Secrets.MatchSecret != Secrets.MatchSecret || other.Secrets.SpectateSecret != Secrets.SpectateSecret)
				{
					return false;
				}
			}
			else if (other.Secrets != null)
			{
				return false;
			}
			if (Party != null)
			{
				if (other.Party == null || other.Party.ID != Party.ID || other.Party.Max != Party.Max || other.Party.Size != Party.Size || other.Party.Privacy != Party.Privacy)
				{
					return false;
				}
			}
			else if (other.Party != null)
			{
				return false;
			}
			if (Assets != null)
			{
				if (other.Assets == null || other.Assets.LargeImageKey != Assets.LargeImageKey || other.Assets.LargeImageText != Assets.LargeImageText || other.Assets.SmallImageKey != Assets.SmallImageKey || other.Assets.SmallImageText != Assets.SmallImageText)
				{
					return false;
				}
			}
			else if (other.Assets != null)
			{
				return false;
			}
			return Instance == other.Instance;
		}

		public RichPresence ToRichPresence()
		{
			RichPresence richPresence = new RichPresence();
			richPresence.State = State;
			richPresence.Details = Details;
			richPresence.Type = Type;
			richPresence.Party = ((!HasParty()) ? Party : null);
			richPresence.Secrets = ((!HasSecrets()) ? Secrets : null);
			if (HasAssets())
			{
				richPresence.Assets = new Assets
				{
					SmallImageKey = Assets.SmallImageKey,
					SmallImageText = Assets.SmallImageText,
					LargeImageKey = Assets.LargeImageKey,
					LargeImageText = Assets.LargeImageText
				};
			}
			if (HasTimestamps())
			{
				richPresence.Timestamps = new Timestamps();
				if (Timestamps.Start.HasValue)
				{
					richPresence.Timestamps.Start = Timestamps.Start;
				}
				if (Timestamps.End.HasValue)
				{
					richPresence.Timestamps.End = Timestamps.End;
				}
			}
			return richPresence;
		}
	}
	[Serializable]
	public class Secrets
	{
		private string _matchSecret;

		private string _joinSecret;

		private string _spectateSecret;

		[Obsolete("This feature has been deprecated my Mason in issue #152 on the offical library. Was originally used as a Notify Me feature, it has been replaced with Join / Spectate.")]
		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string MatchSecret
		{
			get
			{
				return _matchSecret;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _matchSecret, 128, Encoding.UTF8))
				{
					throw new StringOutOfRangeException(128);
				}
			}
		}

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string JoinSecret
		{
			get
			{
				return _joinSecret;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _joinSecret, 128, Encoding.UTF8))
				{
					throw new StringOutOfRangeException(128);
				}
			}
		}

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string SpectateSecret
		{
			get
			{
				return _spectateSecret;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _spectateSecret, 128, Encoding.UTF8))
				{
					throw new StringOutOfRangeException(128);
				}
			}
		}

		public static Encoding Encoding => Encoding.UTF8;

		public static int SecretLength => 128;

		public static string CreateSecret(Random random)
		{
			byte[] array = new byte[SecretLength];
			random.NextBytes(array);
			return Encoding.GetString(array);
		}

		public static string CreateFriendlySecret(Random random)
		{
			string text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < SecretLength; i++)
			{
				stringBuilder.Append(text[random.Next(text.Length)]);
			}
			return stringBuilder.ToString();
		}
	}
	[Serializable]
	public class Assets
	{
		private string _largeimagekey;

		private bool _islargeimagekeyexternal;

		private string _largeimagetext;

		private string _smallimagekey;

		private bool _issmallimagekeyexternal;

		private string _smallimagetext;

		private ulong? _largeimageID;

		private ulong? _smallimageID;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string LargeImageKey
		{
			get
			{
				return _largeimagekey;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _largeimagekey, 256, Encoding.UTF8))
				{
					throw new StringOutOfRangeException(256);
				}
				_islargeimagekeyexternal = _largeimagekey?.StartsWith("mp:external/") ?? false;
				_largeimageID = null;
			}
		}

		[JsonIgnore]
		public bool IsLargeImageKeyExternal => _islargeimagekeyexternal;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string LargeImageText
		{
			get
			{
				return _largeimagetext;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _largeimagetext, 128, Encoding.UTF8))
				{
					throw new StringOutOfRangeException(128);
				}
			}
		}

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string SmallImageKey
		{
			get
			{
				return _smallimagekey;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _smallimagekey, 256, Encoding.UTF8))
				{
					throw new StringOutOfRangeException(256);
				}
				_issmallimagekeyexternal = _smallimagekey?.StartsWith("mp:external/") ?? false;
				_smallimageID = null;
			}
		}

		[JsonIgnore]
		public bool IsSmallImageKeyExternal => _issmallimagekeyexternal;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string SmallImageText
		{
			get
			{
				return _smallimagetext;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _smallimagetext, 128, Encoding.UTF8))
				{
					throw new StringOutOfRangeException(128);
				}
			}
		}

		[JsonIgnore]
		public ulong? LargeImageID => _largeimageID;

		[JsonIgnore]
		public ulong? SmallImageID => _smallimageID;

		internal void Merge(Assets other)
		{
			_smallimagetext = other._smallimagetext;
			_largeimagetext = other._largeimagetext;
			if (ulong.TryParse(other._largeimagekey, out var result))
			{
				_largeimageID = result;
			}
			else
			{
				_largeimagekey = other._largeimagekey;
				_largeimageID = null;
			}
			if (ulong.TryParse(other._smallimagekey, out var result2))
			{
				_smallimageID = result2;
				return;
			}
			_smallimagekey = other._smallimagekey;
			_smallimageID = null;
		}
	}
	[Serializable]
	public class Timestamps
	{
		public static Timestamps Now => new Timestamps(DateTime.UtcNow);

		[JsonIgnore]
		public DateTime? Start { get; set; }

		[JsonIgnore]
		public DateTime? End { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public ulong? StartUnixMilliseconds
		{
			get
			{
				return Start.HasValue ? new ulong?(ToUnixMilliseconds(Start.Value)) : null;
			}
			set
			{
				Start = (value.HasValue ? new DateTime?(FromUnixMilliseconds(value.Value)) : null);
			}
		}

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public ulong? EndUnixMilliseconds
		{
			get
			{
				return End.HasValue ? new ulong?(ToUnixMilliseconds(End.Value)) : null;
			}
			set
			{
				End = (value.HasValue ? new DateTime?(FromUnixMilliseconds(value.Value)) : null);
			}
		}

		public static Timestamps FromTimeSpan(double seconds)
		{
			return FromTimeSpan(TimeSpan.FromSeconds(seconds));
		}

		public static Timestamps FromTimeSpan(TimeSpan timespan)
		{
			return new Timestamps
			{
				Start = DateTime.UtcNow,
				End = DateTime.UtcNow + timespan
			};
		}

		public Timestamps()
		{
			Start = null;
			End = null;
		}

		public Timestamps(DateTime start)
		{
			Start = start;
			End = null;
		}

		public Timestamps(DateTime start, DateTime end)
		{
			Start = start;
			End = end;
		}

		public static DateTime FromUnixMilliseconds(ulong unixTime)
		{
			return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Convert.ToDouble(unixTime));
		}

		public static ulong ToUnixMilliseconds(DateTime date)
		{
			DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
			return Convert.ToUInt64((date - dateTime).TotalMilliseconds);
		}
	}
	[Serializable]
	public class Party
	{
		public enum PrivacySetting
		{
			Private,
			Public
		}

		private string _partyid;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string ID
		{
			get
			{
				return _partyid;
			}
			set
			{
				_partyid = value.GetNullOrString();
			}
		}

		[JsonIgnore]
		public int Size { get; set; }

		[JsonIgnore]
		public int Max { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public PrivacySetting Privacy { get; set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		private int[] _size
		{
			get
			{
				int num = Math.Max(1, Size);
				return new int[2]
				{
					num,
					Math.Max(num, Max)
				};
			}
			set
			{
				if (value.Length != 2)
				{
					Size = 0;
					Max = 0;
				}
				else
				{
					Size = value[0];
					Max = value[1];
				}
			}
		}
	}
	public class Button
	{
		private string _label;

		private string _url;

		[JsonProperty("label")]
		public string Label
		{
			get
			{
				return _label;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _label, 32, Encoding.UTF8))
				{
					throw new StringOutOfRangeException(32);
				}
			}
		}

		[JsonProperty("url")]
		public string Url
		{
			get
			{
				return _url;
			}
			set
			{
				if (!BaseRichPresence.ValidateString(value, out _url, 512, Encoding.UTF8))
				{
					throw new StringOutOfRangeException(512);
				}
				if (!Uri.TryCreate(_url, UriKind.Absolute, out Uri _))
				{
					throw new ArgumentException("Url must be a valid URI");
				}
			}
		}
	}
	public enum ActivityType
	{
		Playing = 0,
		Listening = 2,
		Watching = 3,
		Competing = 5
	}
	public sealed class RichPresence : BaseRichPresence
	{
		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Button[] Buttons { get; set; }

		public bool HasButtons()
		{
			return Buttons != null && Buttons.Length != 0;
		}

		public RichPresence WithState(string state)
		{
			base.State = state;
			return this;
		}

		public RichPresence WithDetails(string details)
		{
			base.Details = details;
			return this;
		}

		public RichPresence WithType(ActivityType type)
		{
			base.Type = type;
			return this;
		}

		public RichPresence WithTimestamps(Timestamps timestamps)
		{
			base.Timestamps = timestamps;
			return this;
		}

		public RichPresence WithAssets(Assets assets)
		{
			base.Assets = assets;
			return this;
		}

		public RichPresence WithParty(Party party)
		{
			base.Party = party;
			return this;
		}

		public RichPresence WithSecrets(Secrets secrets)
		{
			base.Secrets = secrets;
			return this;
		}

		public RichPresence Clone()
		{
			RichPresence richPresence = new RichPresence();
			richPresence.State = ((_state != null) ? (_state.Clone() as string) : null);
			richPresence.Details = ((_details != null) ? (_details.Clone() as string) : null);
			richPresence.Type = base.Type;
			richPresence.Buttons = ((!HasButtons()) ? null : (Buttons.Clone() as Button[]));
			richPresence.Secrets = ((!HasSecrets()) ? null : new Secrets
			{
				JoinSecret = ((base.Secrets.JoinSecret != null) ? (base.Secrets.JoinSecret.Clone() as string) : null),
				SpectateSecret = ((base.Secrets.SpectateSecret != null) ? (base.Secrets.SpectateSecret.Clone() as string) : null)
			});
			richPresence.Timestamps = ((!HasTimestamps()) ? null : new Timestamps
			{
				Start = base.Timestamps.Start,
				End = base.Timestamps.End
			});
			richPresence.Assets = ((!HasAssets()) ? null : new Assets
			{
				LargeImageKey = ((base.Assets.LargeImageKey != null) ? (base.Assets.LargeImageKey.Clone() as string) : null),
				LargeImageText = ((base.Assets.LargeImageText != null) ? (base.Assets.LargeImageText.Clone() as string) : null),
				SmallImageKey = ((base.Assets.SmallImageKey != null) ? (base.Assets.SmallImageKey.Clone() as string) : null),
				SmallImageText = ((base.Assets.SmallImageText != null) ? (base.Assets.SmallImageText.Clone() as string) : null)
			});
			richPresence.Party = ((!HasParty()) ? null : new Party
			{
				ID = base.Party.ID,
				Size = base.Party.Size,
				Max = base.Party.Max,
				Privacy = base.Party.Privacy
			});
			return richPresence;
		}

		internal RichPresence Merge(BaseRichPresence presence)
		{
			_state = presence.State;
			_details = presence.Details;
			base.Type = presence.Type;
			base.Party = presence.Party;
			base.Timestamps = presence.Timestamps;
			base.Secrets = presence.Secrets;
			if (presence.HasAssets())
			{
				if (!HasAssets())
				{
					base.Assets = presence.Assets;
				}
				else
				{
					base.Assets.Merge(presence.Assets);
				}
			}
			else
			{
				base.Assets = null;
			}
			return this;
		}

		internal override bool Matches(RichPresence other)
		{
			if (!base.Matches(other))
			{
				return false;
			}
			if ((Buttons == null) ^ (other.Buttons == null))
			{
				return false;
			}
			if (Buttons != null)
			{
				if (Buttons.Length != other.Buttons.Length)
				{
					return false;
				}
				for (int i = 0; i < Buttons.Length; i++)
				{
					Button button = Buttons[i];
					Button button2 = other.Buttons[i];
					if (button.Label != button2.Label || button.Url != button2.Url)
					{
						return false;
					}
				}
			}
			return true;
		}

		public static implicit operator bool(RichPresence presesnce)
		{
			return presesnce != null;
		}
	}
	internal sealed class RichPresenceResponse : BaseRichPresence
	{
		[JsonProperty("application_id")]
		public string ClientID { get; private set; }

		[JsonProperty("name")]
		public string Name { get; private set; }
	}
	public class User
	{
		public enum AvatarFormat
		{
			PNG,
			JPEG,
			WebP,
			GIF
		}

		public enum AvatarSize
		{
			x16 = 0x10,
			x32 = 0x20,
			x64 = 0x40,
			x128 = 0x80,
			x256 = 0x100,
			x512 = 0x200,
			x1024 = 0x400,
			x2048 = 0x800
		}

		[Flags]
		public enum Flag
		{
			None = 0,
			Employee = 1,
			Partner = 2,
			HypeSquad = 4,
			BugHunter = 8,
			HouseBravery = 0x40,
			HouseBrilliance = 0x80,
			HouseBalance = 0x100,
			EarlySupporter = 0x200,
			TeamUser = 0x400
		}

		public enum PremiumType
		{
			None,
			NitroClassic,
			Nitro
		}

		[JsonProperty("id")]
		public ulong ID { get; private set; }

		[JsonProperty("username")]
		public string Username { get; private set; }

		[JsonProperty("discriminator")]
		[Obsolete("Discord no longer uses discriminators.")]
		public int Discriminator { get; private set; }

		[JsonProperty("global_name")]
		public string DisplayName { get; private set; }

		[JsonProperty("avatar")]
		public string Avatar { get; private set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Flag Flags { get; private set; }

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public PremiumType Premium { get; private set; }

		public string CdnEndpoint { get; private set; }

		internal User()
		{
			CdnEndpoint = "cdn.discordapp.com";
		}

		internal void SetConfiguration(Configuration configuration)
		{
			CdnEndpoint = configuration.CdnHost;
		}

		public string GetAvatarURL(AvatarFormat format)
		{
			return GetAvatarURL(format, AvatarSize.x128);
		}

		public string GetAvatarURL(AvatarFormat format, AvatarSize size)
		{
			string text = $"/avatars/{ID}/{Avatar}";
			if (string.IsNullOrEmpty(Avatar))
			{
				if (format != 0)
				{
					throw new BadImageFormatException("The user has no avatar and the requested format " + format.ToString() + " is not supported. (Only supports PNG).");
				}
				int num = (int)((ID >> 22) % 6);
				if (Discriminator > 0)
				{
					num = Discriminator % 5;
				}
				text = $"/embed/avatars/{num}";
			}
			return $"https://{CdnEndpoint}{text}{GetAvatarExtension(format)}?size={(int)size}";
		}

		public string GetAvatarExtension(AvatarFormat format)
		{
			return "." + format.ToString().ToLowerInvariant();
		}

		public override string ToString()
		{
			if (!string.IsNullOrEmpty(DisplayName))
			{
				return DisplayName;
			}
			if (Discriminator != 0)
			{
				return Username + "#" + Discriminator.ToString("D4");
			}
			return Username;
		}
	}
}
namespace DiscordRPC.RPC
{
	internal class RpcConnection : IDisposable
	{
		public static readonly int VERSION = 1;

		public static readonly int POLL_RATE = 1000;

		private static readonly bool CLEAR_ON_SHUTDOWN = true;

		private static readonly bool LOCK_STEP = false;

		private ILogger _logger;

		private RpcState _state;

		private readonly object l_states = new object();

		private Configuration _configuration = null;

		private readonly object l_config = new object();

		private volatile bool aborting = false;

		private volatile bool shutdown = false;

		private string applicationID;

		private int processID;

		private long nonce;

		private Thread thread;

		private INamedPipeClient namedPipe;

		private int targetPipe;

		private readonly object l_rtqueue = new object();

		private readonly uint _maxRtQueueSize;

		private Queue<ICommand> _rtqueue;

		private readonly object l_rxqueue = new object();

		private readonly uint _maxRxQueueSize;

		private Queue<IMessage> _rxqueue;

		private AutoResetEvent queueUpdatedEvent = new AutoResetEvent(initialState: false);

		private BackoffDelay delay;

		public ILogger Logger
		{
			get
			{
				return _logger;
			}
			set
			{
				_logger = value;
				if (namedPipe != null)
				{
					namedPipe.Logger = value;
				}
			}
		}

		public RpcState State
		{
			get
			{
				lock (l_states)
				{
					return _state;
				}
			}
		}

		public Configuration Configuration
		{
			get
			{
				Configuration result = null;
				lock (l_config)
				{
					result = _configuration;
				}
				return result;
			}
		}

		public bool IsRunning => thread != null;

		public bool ShutdownOnly { get; set; }

		public event OnRpcMessageEvent OnRpcMessage;

		public RpcConnection(string applicationID, int processID, int targetPipe, INamedPipeClient client, uint maxRxQueueSize = 128u, uint maxRtQueueSize = 512u)
		{
			this.applicationID = applicationID;
			this.processID = processID;
			this.targetPipe = targetPipe;
			namedPipe = client;
			ShutdownOnly = true;
			Logger = new ConsoleLogger();
			delay = new BackoffDelay(500, 60000);
			_maxRtQueueSize = maxRtQueueSize;
			_rtqueue = new Queue<ICommand>((int)(_maxRtQueueSize + 1));
			_maxRxQueueSize = maxRxQueueSize;
			_rxqueue = new Queue<IMessage>((int)(_maxRxQueueSize + 1));
			nonce = 0L;
		}

		private long GetNextNonce()
		{
			nonce++;
			return nonce;
		}

		internal void EnqueueCommand(ICommand command)
		{
			Logger.Trace("Enqueue Command: {0}", command.GetType().FullName);
			if (aborting || shutdown)
			{
				return;
			}
			lock (l_rtqueue)
			{
				if (_rtqueue.Count == _maxRtQueueSize)
				{
					Logger.Error("Too many enqueued commands, dropping oldest one. Maybe you are pushing new presences to fast?");
					_rtqueue.Dequeue();
				}
				_rtqueue.Enqueue(command);
			}
		}

		private void EnqueueMessage(IMessage message)
		{
			try
			{
				if (this.OnRpcMessage != null)
				{
					this.OnRpcMessage(this, message);
				}
			}
			catch (Exception ex)
			{
				Logger.Error("Unhandled Exception while processing event: {0}", ex.GetType().FullName);
				Logger.Error(ex.Message);
				Logger.Error(ex.StackTrace);
			}
			if (_maxRxQueueSize == 0)
			{
				Logger.Trace("Enqueued Message, but queue size is 0.");
				return;
			}
			Logger.Trace("Enqueue Message: {0}", message.Type);
			lock (l_rxqueue)
			{
				if (_rxqueue.Count == _maxRxQueueSize)
				{
					Logger.Warning("Too many enqueued messages, dropping oldest one.");
					_rxqueue.Dequeue();
				}
				_rxqueue.Enqueue(message);
			}
		}

		internal IMessage DequeueMessage()
		{
			lock (l_rxqueue)
			{
				if (_rxqueue.Count == 0)
				{
					return null;
				}
				return _rxqueue.Dequeue();
			}
		}

		internal IMessage[] DequeueMessages()
		{
			lock (l_rxqueue)
			{
				IMessage[] result = _rxqueue.ToArray();
				_rxqueue.Clear();
				return result;
			}
		}

		private void MainLoop()
		{
			Logger.Info("RPC Connection Started");
			if (Logger.Level <= LogLevel.Trace)
			{
				Logger.Trace("============================");
				Logger.Trace("Assembly:             " + Assembly.GetAssembly(typeof(RichPresence)).FullName);
				Logger.Trace("Pipe:                 " + namedPipe.GetType().FullName);
				Logger.Trace("Platform:             " + Environment.OSVersion.ToString());
				Logger.Trace("applicationID:        " + applicationID);
				Logger.Trace("targetPipe:           " + targetPipe);
				ILogger logger = Logger;
				int pOLL_RATE = POLL_RATE;
				logger.Trace("POLL_RATE:            " + pOLL_RATE);
				ILogger logger2 = Logger;
				uint maxRtQueueSize = _maxRtQueueSize;
				logger2.Trace("_maxRtQueueSize:      " + maxRtQueueSize);
				ILogger logger3 = Logger;
				maxRtQueueSize = _maxRxQueueSize;
				logger3.Trace("_maxRxQueueSize:      " + maxRtQueueSize);
				Logger.Trace("============================");
			}
			while (!aborting && !shutdown)
			{
				try
				{
					if (namedPipe == null)
					{
						Logger.Error("Something bad has happened with our pipe client!");
						aborting = true;
						return;
					}
					Logger.Trace("Connecting to the pipe through the {0}", namedPipe.GetType().FullName);
					if (namedPipe.Connect(targetPipe))
					{
						Logger.Trace("Connected to the pipe. Attempting to establish handshake...");
						EnqueueMessage(new ConnectionEstablishedMessage
						{
							ConnectedPipe = namedPipe.ConnectedPipe
						});
						EstablishHandshake();
						Logger.Trace("Connection Established. Starting reading loop...");
						bool flag = true;
						while (flag && !aborting && !shutdown && namedPipe.IsConnected)
						{
							if (namedPipe.ReadFrame(out var frame))
							{
								Logger.Trace("Read Payload: {0}", frame.Opcode);
								switch (frame.Opcode)
								{
								case Opcode.Close:
								{
									ClosePayload @object = frame.GetObject<ClosePayload>();
									Logger.Warning("We have been told to terminate by discord: ({0}) {1}", @object.Code, @object.Reason);
									EnqueueMessage(new CloseMessage
									{
										Code = @object.Code,
										Reason = @object.Reason
									});
									flag = false;
									break;
								}
								case Opcode.Ping:
									Logger.Trace("PING");
									frame.Opcode = Opcode.Pong;
									namedPipe.WriteFrame(frame);
									break;
								case Opcode.Pong:
									Logger.Trace("PONG");
									break;
								case Opcode.Frame:
								{
									if (shutdown)
									{
										Logger.Warning("Skipping frame because we are shutting down.");
										break;
									}
									if (frame.Data == null)
									{
										Logger.Error("We received no data from the frame so we cannot get the event payload!");
										break;
									}
									EventPayload eventPayload = null;
									try
									{
										eventPayload = frame.GetObject<EventPayload>();
									}
									catch (Exception ex)
									{
										Logger.Error("Failed to parse event! {0}", ex.Message);
										Logger.Error("Data: {0}", frame.Message);
									}
									try
									{
										if (eventPayload != null)
										{
											ProcessFrame(eventPayload);
										}
									}
									catch (Exception ex2)
									{
										Logger.Error("Failed to process event! {0}", ex2.Message);
										Logger.Error("Data: {0}", frame.Message);
									}
									break;
								}
								default:
									Logger.Error("Invalid opcode: {0}", frame.Opcode);
									flag = false;
									break;
								}
							}
							if (!aborting && namedPipe.IsConnected)
							{
								ProcessCommandQueue();
								queueUpdatedEvent.WaitOne(POLL_RATE);
							}
						}
						Logger.Trace("Left main read loop for some reason. Aborting: {0}, Shutting Down: {1}", aborting, shutdown);
					}
					else
					{
						Logger.Error("Failed to connect for some reason.");
						EnqueueMessage(new ConnectionFailedMessage
						{
							FailedPipe = targetPipe
						});
					}
					if (!aborting && !shutdown)
					{
						long num = delay.NextDelay();
						Logger.Trace("Waiting {0}ms before attempting to connect again", num);
						Thread.Sleep(delay.NextDelay());
					}
				}
				catch (Exception ex3)
				{
					Logger.Error("Unhandled Exception: {0}", ex3.GetType().FullName);
					Logger.Error(ex3.Message);
					Logger.Error(ex3.StackTrace);
				}
				finally
				{
					if (namedPipe.IsConnected)
					{
						Logger.Trace("Closing the named pipe.");
						namedPipe.Close();
					}
					SetConnectionState(RpcState.Disconnected);
				}
			}
			Logger.Trace("Left Main Loop");
			if (namedPipe != null)
			{
				namedPipe.Dispose();
			}
			Logger.Info("Thread Terminated, no longer performing RPC connection.");
		}

		private void ProcessFrame(EventPayload response)
		{
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Expected O, but got Unknown
			Logger.Info("Handling Response. Cmd: {0}, Event: {1}", response.Command, response.Event);
			if (response.Event.HasValue && response.Event.Value == ServerEvent.Error)
			{
				Logger.Error("Error received from the RPC");
				ErrorMessage @object = response.GetObject<ErrorMessage>();
				Logger.Error("Server responded with an error message: ({0}) {1}", @object.Code.ToString(), @object.Message);
				EnqueueMessage(@object);
			}
			else if (State == RpcState.Connecting && response.Command == Command.Dispatch && response.Event.HasValue && response.Event.Value == ServerEvent.Ready)
			{
				Logger.Info("Connection established with the RPC");
				SetConnectionState(RpcState.Connected);
				delay.Reset();
				ReadyMessage object2 = response.GetObject<ReadyMessage>();
				lock (l_config)
				{
					_configuration = object2.Configuration;
					object2.User.SetConfiguration(_configuration);
				}
				EnqueueMessage(object2);
			}
			else if (State == RpcState.Connected)
			{
				switch (response.Command)
				{
				case Command.Dispatch:
					ProcessDispatch(response);
					break;
				case Command.SetActivity:
				{
					if (response.Data == null)
					{
						EnqueueMessage(new PresenceMessage());
						break;
					}
					RichPresenceResponse object3 = response.GetObject<RichPresenceResponse>();
					EnqueueMessage(new PresenceMessage(object3));
					break;
				}
				case Command.Subscribe:
				case Command.Unsubscribe:
				{
					JsonSerializer val = new JsonSerializer();
					((Collection<JsonConverter>)(object)val.Converters).Add((JsonConverter)(object)new EnumSnakeCaseConverter());
					ServerEvent value = response.GetObject<EventPayload>().Event.Value;
					if (response.Command == Command.Subscribe)
					{
						EnqueueMessage(new SubscribeMessage(value));
					}
					else
					{
						EnqueueMessage(new UnsubscribeMessage(value));
					}
					break;
				}
				case Command.SendActivityJoinInvite:
					Logger.Trace("Got invite response ack.");
					break;
				case Command.CloseActivityJoinRequest:
					Logger.Trace("Got invite response reject ack.");
					break;
				default:
					Logger.Error("Unkown frame was received! {0}", response.Command);
					break;
				}
			}
			else
			{
				Logger.Trace("Received a frame while we are disconnected. Ignoring. Cmd: {0}, Event: {1}", response.Command, response.Event);
			}
		}

		private void ProcessDispatch(EventPayload response)
		{
			if (response.Command == Command.Dispatch && response.Event.HasValue)
			{
				switch (response.Event.Value)
				{
				case ServerEvent.ActivitySpectate:
				{
					SpectateMessage object3 = response.GetObject<SpectateMessage>();
					EnqueueMessage(object3);
					break;
				}
				case ServerEvent.ActivityJoin:
				{
					JoinMessage object2 = response.GetObject<JoinMessage>();
					EnqueueMessage(object2);
					break;
				}
				case ServerEvent.ActivityJoinRequest:
				{
					JoinRequestMessage @object = response.GetObject<JoinRequestMessage>();
					EnqueueMessage(@object);
					break;
				}
				default:
					Logger.Warning("Ignoring {0}", response.Event.Value);
					break;
				}
			}
		}

		private void ProcessCommandQueue()
		{
			if (State != RpcState.Connected)
			{
				return;
			}
			if (aborting)
			{
				Logger.Warning("We have been told to write a queue but we have also been aborted.");
			}
			bool flag = true;
			ICommand command = null;
			while (flag && namedPipe.IsConnected)
			{
				lock (l_rtqueue)
				{
					flag = _rtqueue.Count > 0;
					if (!flag)
					{
						break;
					}
					command = _rtqueue.Peek();
				}
				if (shutdown || (!aborting && LOCK_STEP))
				{
					flag = false;
				}
				IPayload payload = command.PreparePayload(GetNextNonce());
				Logger.Trace("Attempting to send payload: {0}", payload.Command);
				PipeFrame frame = default(PipeFrame);
				if (command is CloseCommand)
				{
					SendHandwave();
					Logger.Trace("Handwave sent, ending queue processing.");
					lock (l_rtqueue)
					{
						_rtqueue.Dequeue();
						break;
					}
				}
				if (aborting)
				{
					Logger.Warning("- skipping frame because of abort.");
					lock (l_rtqueue)
					{
						_rtqueue.Dequeue();
					}
					continue;
				}
				frame.SetObject(Opcode.Frame, payload);
				Logger.Trace("Sending payload: {0}", payload.Command);
				if (namedPipe.WriteFrame(frame))
				{
					Logger.Trace("Sent Successfully.");
					lock (l_rtqueue)
					{
						_rtqueue.Dequeue();
					}
					continue;
				}
				Logger.Warning("Something went wrong during writing!");
				break;
			}
		}

		private void EstablishHandshake()
		{
			Logger.Trace("Attempting to establish a handshake...");
			if (State != 0)
			{
				Logger.Error("State must be disconnected in order to start a handshake!");
				return;
			}
			Logger.Trace("Sending Handshake...");
			if (!namedPipe.WriteFrame(new PipeFrame(Opcode.Handshake, new Handshake
			{
				Version = VERSION,
				ClientID = applicationID
			})))
			{
				Logger.Error("Failed to write a handshake.");
			}
			else
			{
				SetConnectionState(RpcState.Connecting);
			}
		}

		private void SendHandwave()
		{
			Logger.Info("Attempting to wave goodbye...");
			if (State == RpcState.Disconnected)
			{
				Logger.Error("State must NOT be disconnected in order to send a handwave!");
			}
			else if (!namedPipe.WriteFrame(new PipeFrame(Opcode.Close, new Handshake
			{
				Version = VERSION,
				ClientID = applicationID
			})))
			{
				Logger.Error("failed to write a handwave.");
			}
		}

		public bool AttemptConnection()
		{
			Logger.Info("Attempting a new connection");
			if (thread != null)
			{
				Logger.Error("Cannot attempt a new connection as the previous connection thread is not null!");
				return false;
			}
			if (State != 0)
			{
				Logger.Warning("Cannot attempt a new connection as the previous connection hasn't changed state yet.");
				return false;
			}
			if (aborting)
			{
				Logger.Error("Cannot attempt a new connection while aborting!");
				return false;
			}
			thread = new Thread(MainLoop);
			thread.Name = "Discord IPC Thread";
			thread.IsBackground = true;
			thread.Start();
			return true;
		}

		private void SetConnectionState(RpcState state)
		{
			Logger.Trace("Setting the connection state to {0}", state.ToString().ToSnakeCase().ToUpperInvariant());
			lock (l_states)
			{
				_state = state;
			}
		}

		public void Shutdown()
		{
			Logger.Trace("Initiated shutdown procedure");
			shutdown = true;
			lock (l_rtqueue)
			{
				_rtqueue.Clear();
				if (CLEAR_ON_SHUTDOWN)
				{
					_rtqueue.Enqueue(new PresenceCommand
					{
						PID = processID,
						Presence = null
					});
				}
				_rtqueue.Enqueue(new CloseCommand());
			}
			queueUpdatedEvent.Set();
		}

		public void Close()
		{
			if (thread == null)
			{
				Logger.Error("Cannot close as it is not available!");
				return;
			}
			if (aborting)
			{
				Logger.Error("Cannot abort as it has already been aborted");
				return;
			}
			if (ShutdownOnly)
			{
				Shutdown();
				return;
			}
			Logger.Trace("Updating Abort State...");
			aborting = true;
			queueUpdatedEvent.Set();
		}

		public void Dispose()
		{
			ShutdownOnly = false;
			Close();
		}
	}
	internal enum RpcState
	{
		Disconnected,
		Connecting,
		Connected
	}
}
namespace DiscordRPC.RPC.Payload
{
	internal class ClosePayload : IPayload
	{
		[JsonProperty("code")]
		public int Code { get; set; }

		[JsonProperty("message")]
		public string Reason { get; set; }

		[JsonConstructor]
		public ClosePayload()
		{
			Code = -1;
			Reason = "";
		}
	}
	internal enum Command
	{
		[EnumValue("DISPATCH")]
		Dispatch,
		[EnumValue("SET_ACTIVITY")]
		SetActivity,
		[EnumValue("SUBSCRIBE")]
		Subscribe,
		[EnumValue("UNSUBSCRIBE")]
		Unsubscribe,
		[EnumValue("SEND_ACTIVITY_JOIN_INVITE")]
		SendActivityJoinInvite,
		[EnumValue("CLOSE_ACTIVITY_JOIN_REQUEST")]
		CloseActivityJoinRequest,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		Authorize,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		Authenticate,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		GetGuild,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		GetGuilds,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		GetChannel,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		GetChannels,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		SetUserVoiceSettings,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		SelectVoiceChannel,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		GetSelectedVoiceChannel,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		SelectTextChannel,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		GetVoiceSettings,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		SetVoiceSettings,
		[Obsolete("This value is appart of the RPC API and is not supported by this library.", true)]
		CaptureShortcut
	}
	internal abstract class IPayload
	{
		[JsonProperty("cmd")]
		[JsonConverter(typeof(EnumSnakeCaseConverter))]
		public Command Command { get; set; }

		[JsonProperty("nonce")]
		public string Nonce { get; set; }

		protected IPayload()
		{
		}

		protected IPayload(long nonce)
		{
			Nonce = nonce.ToString();
		}

		public override string ToString()
		{
			return $"Payload || Command: {Command}, Nonce: {Nonce}";
		}
	}
	internal class ArgumentPayload : IPayload
	{
		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public JObject Arguments { get; set; }

		public ArgumentPayload()
		{
			Arguments = null;
		}

		public ArgumentPayload(long nonce)
			: base(nonce)
		{
			Arguments = null;
		}

		public ArgumentPayload(object args, long nonce)
			: base(nonce)
		{
			SetObject(args);
		}

		public void SetObject(object obj)
		{
			Arguments = JObject.FromObject(obj);
		}

		public T GetObject<T>()
		{
			return ((JToken)Arguments).ToObject<T>();
		}

		public override string ToString()
		{
			return "Argument " + base.ToString();
		}
	}
	internal class EventPayload : IPayload
	{
		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public JObject Data { get; set; }

		[JsonProperty("evt")]
		[JsonConverter(typeof(EnumSnakeCaseConverter))]
		public ServerEvent? Event { get; set; }

		public EventPayload()
		{
			Data = null;
		}

		public EventPayload(long nonce)
			: base(nonce)
		{
			Data = null;
		}

		public T GetObject<T>()
		{
			if (Data == null)
			{
				return default(T);
			}
			return ((JToken)Data).ToObject<T>();
		}

		public override string ToString()
		{
			return "Event " + base.ToString() + ", Event: " + (Event.HasValue ? Event.ToString() : "N/A");
		}
	}
	internal enum ServerEvent
	{
		[EnumValue("READY")]
		Ready,
		[EnumValue("ERROR")]
		Error,
		[EnumValue("ACTIVITY_JOIN")]
		ActivityJoin,
		[EnumValue("ACTIVITY_SPECTATE")]
		ActivitySpectate,
		[EnumValue("ACTIVITY_JOIN_REQUEST")]
		ActivityJoinRequest
	}
}
namespace DiscordRPC.RPC.Commands
{
	internal class CloseCommand : ICommand
	{
		[JsonProperty("close_reason")]
		public string value = "Unity 5.5 doesn't handle thread aborts. Can you please close me discord?";

		[JsonProperty("pid")]
		public int PID { get; set; }

		public IPayload PreparePayload(long nonce)
		{
			return new ArgumentPayload
			{
				Command = Command.Dispatch,
				Nonce = null,
				Arguments = null
			};
		}
	}
	internal interface ICommand
	{
		IPayload PreparePayload(long nonce);
	}
	internal class PresenceCommand : ICommand
	{
		[JsonProperty("pid")]
		public int PID { get; set; }

		[JsonProperty("activity")]
		public RichPresence Presence { get; set; }

		public IPayload PreparePayload(long nonce)
		{
			return new ArgumentPayload(this, nonce)
			{
				Command = Command.SetActivity
			};
		}
	}
	internal class RespondCommand : ICommand
	{
		[JsonProperty("user_id")]
		public string UserID { get; set; }

		[JsonIgnore]
		public bool Accept { get; set; }

		public IPayload PreparePayload(long nonce)
		{
			return new ArgumentPayload(this, nonce)
			{
				Command = (Accept ? Command.SendActivityJoinInvite : Command.CloseActivityJoinRequest)
			};
		}
	}
	internal class SubscribeCommand : ICommand
	{
		public ServerEvent Event { get; set; }

		public bool IsUnsubscribe { get; set; }

		public IPayload PreparePayload(long nonce)
		{
			return new EventPayload(nonce)
			{
				Command = (IsUnsubscribe ? Command.Unsubscribe : Command.Subscribe),
				Event = Event
			};
		}
	}
}
namespace DiscordRPC.Registry
{
	internal interface IUriSchemeCreator
	{
		bool RegisterUriScheme(UriSchemeRegister register);
	}
	internal class MacUriSchemeCreator : IUriSchemeCreator
	{
		private ILogger logger;

		public MacUriSchemeCreator(ILogger logger)
		{
			this.logger = logger;
		}

		public bool RegisterUriScheme(UriSchemeRegister register)
		{
			string executablePath = register.ExecutablePath;
			if (string.IsNullOrEmpty(executablePath))
			{
				logger.Error("Failed to register because the application could not be located.");
				return false;
			}
			logger.Trace("Registering Steam Command");
			string text = executablePath;
			if (register.UsingSteamApp)
			{
				text = "steam://rungameid/" + register.SteamAppID;
			}
			else
			{
				logger.Warning("This library does not fully support MacOS URI Scheme Registration.");
			}
			string text2 = "~/Library/Application Support/discord/games";
			DirectoryInfo directoryInfo = Directory.CreateDirectory(text2);
			if (!directoryInfo.Exists)
			{
				logger.Error("Failed to register because {0} does not exist", text2);
				return false;
			}
			string text3 = text2 + "/" + register.ApplicationID + ".json";
			File.WriteAllText(text3, "{ \"command\": \"" + text + "\" }");
			logger.Trace("Registered {0}, {1}", text3, text);
			return true;
		}
	}
	internal class UnixUriSchemeCreator : IUriSchemeCreator
	{
		private ILogger logger;

		public UnixUriSchemeCreator(ILogger logger)
		{
			this.logger = logger;
		}

		public bool RegisterUriScheme(UriSchemeRegister register)
		{
			string environmentVariable = Environment.GetEnvironmentVariable("HOME");
			if (string.IsNullOrEmpty(environmentVariable))
			{
				logger.Error("Failed to register because the HOME variable was not set.");
				return false;
			}
			string executablePath = register.ExecutablePath;
			if (string.IsNullOrEmpty(executablePath))
			{
				logger.Error("Failed to register because the application was not located.");
				return false;
			}
			string text = null;
			text = ((!register.UsingSteamApp) ? executablePath : ("xdg-open steam://rungameid/" + register.SteamAppID));
			string format = "[Desktop Entry]\r\nName=Game {0}\r\nExec={1} %u\r\nType=Application\r\nNoDisplay=true\r\nCategories=Discord;Games;\r\nMimeType=x-scheme-handler/discord-{2}";
			string text2 = string.Format(format, register.ApplicationID, text, register.ApplicationID);
			string text3 = "/discord-" + register.ApplicationID + ".desktop";
			string text4 = environmentVariable + "/.local/share/applications";
			DirectoryInfo directoryInfo = Directory.CreateDirectory(text4);
			if (!directoryInfo.Exists)
			{
				logger.Error("Failed to register because {0} does not exist", text4);
				return false;
			}
			File.WriteAllText(text4 + text3, text2);
			if (!RegisterMime(register.ApplicationID))
			{
				logger.Error("Failed to register because the Mime failed.");
				return false;
			}
			logger.Trace("Registered {0}, {1}, {2}", text4 + text3, text2, text);
			return true;
		}

		private bool RegisterMime(string appid)
		{
			string format = "default discord-{0}.desktop x-scheme-handler/discord-{0}";
			string arguments = string.Format(format, appid);
			Process process = Process.Start("xdg-mime", arguments);
			process.WaitForExit();
			return process.ExitCode >= 0;
		}
	}
	internal class UriSchemeRegister
	{
		private ILogger _logger;

		public string ApplicationID { get; set; }

		public string SteamAppID { get; set; }

		public bool UsingSteamApp => !string.IsNullOrEmpty(SteamAppID) && SteamAppID != "";

		public string ExecutablePath { get; set; }

		public UriSchemeRegister(ILogger logger, string applicationID, string steamAppID = null, string executable = null)
		{
			_logger = logger;
			ApplicationID = applicationID.Trim();
			SteamAppID = steamAppID?.Trim();
			ExecutablePath = executable ?? GetApplicationLocation();
		}

		public bool RegisterUriScheme()
		{
			IUriSchemeCreator uriSchemeCreator = null;
			switch (Environment.OSVersion.Platform)
			{
			case PlatformID.Win32S:
			case PlatformID.Win32Windows:
			case PlatformID.Win32NT:
			case PlatformID.WinCE:
				_logger.Trace("Creating Windows Scheme Creator");
				uriSchemeCreator = new WindowsUriSchemeCreator(_logger);
				break;
			case PlatformID.Unix:
				if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
				{
					_logger.Trace("Creating MacOSX Scheme Creator");
					uriSchemeCreator = new MacUriSchemeCreator(_logger);
				}
				else
				{
					_logger.Trace("Creating Unix Scheme Creator");
					uriSchemeCreator = new UnixUriSchemeCreator(_logger);
				}
				break;
			default:
				_logger.Error("Unkown Platform: {0}", Environment.OSVersion.Platform);
				throw new PlatformNotSupportedException("Platform does not support registration.");
			}
			if (uriSchemeCreator.RegisterUriScheme(this))
			{
				_logger.Info("URI scheme registered.");
				return true;
			}
			return false;
		}

		public static string GetApplicationLocation()
		{
			return Process.GetCurrentProcess().MainModule.FileName;
		}
	}
	internal class WindowsUriSchemeCreator : IUriSchemeCreator
	{
		private ILogger logger;

		public WindowsUriSchemeCreator(ILogger logger)
		{
			this.logger = logger;
		}

		public bool RegisterUriScheme(UriSchemeRegister register)
		{
			if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX)
			{
				throw new PlatformNotSupportedException("URI schemes can only be registered on Windows");
			}
			string executablePath = register.ExecutablePath;
			if (executablePath == null)
			{
				logger.Error("Failed to register application because the location was null.");
				return false;
			}
			string scheme = "discord-" + register.ApplicationID;
			string friendlyName = "Run game " + register.ApplicationID + " protocol";
			string defaultIcon = executablePath;
			string command = executablePath;
			if (register.UsingSteamApp)
			{
				string steamLocation = GetSteamLocation();
				if (steamLocation != null)
				{
					command = $"\"{steamLocation}\" steam://rungameid/{register.SteamAppID}";
				}
			}
			CreateUriScheme(scheme, friendlyName, defaultIcon, command);
			return true;
		}

		private void CreateUriScheme(string scheme, string friendlyName, string defaultIcon, string command)
		{
			using (RegistryKey registryKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("SOFTWARE\\Classes\\" + scheme))
			{
				registryKey.SetValue("", "URL:" + friendlyName);
				registryKey.SetValue("URL Protocol", "");
				using (RegistryKey registryKey2 = registryKey.CreateSubKey("DefaultIcon"))
				{
					registryKey2.SetValue("", defaultIcon);
				}
				using RegistryKey registryKey3 = registryKey.CreateSubKey("shell\\open\\command");
				registryKey3.SetValue("", command);
			}
			logger.Trace("Registered {0}, {1}, {2}", scheme, friendlyName, command);
		}

		public string GetSteamLocation()
		{
			using RegistryKey registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\Valve\\Steam");
			if (registryKey == null)
			{
				return null;
			}
			return registryKey.GetValue("SteamExe") as string;
		}
	}
}
namespace DiscordRPC.Message
{
	public class CloseMessage : IMessage
	{
		public override MessageType Type => MessageType.Close;

		public string Reason { get; internal set; }

		public int Code { get; internal set; }

		internal CloseMessage()
		{
		}

		internal CloseMessage(string reason)
		{
			Reason = reason;
		}
	}
	public class ConnectionEstablishedMessage : IMessage
	{
		public override MessageType Type => MessageType.ConnectionEstablished;

		public int ConnectedPipe { get; internal set; }
	}
	public class ConnectionFailedMessage : IMessage
	{
		public override MessageType Type => MessageType.ConnectionFailed;

		public int FailedPipe { get; internal set; }
	}
	public class ErrorMessage : IMessage
	{
		public override MessageType Type => MessageType.Error;

		[JsonProperty("code")]
		public ErrorCode Code { get; internal set; }

		[JsonProperty("message")]
		public string Message { get; internal set; }
	}
	public enum ErrorCode
	{
		Success = 0,
		PipeException = 1,
		ReadCorrupt = 2,
		NotImplemented = 10,
		UnkownError = 1000,
		InvalidPayload = 4000,
		InvalidCommand = 4002,
		InvalidEvent = 4004
	}
	public abstract class IMessage
	{
		private DateTime _timecreated;

		public abstract MessageType Type { get; }

		public DateTime TimeCreated => _timecreated;

		public IMessage()
		{
			_timecreated = DateTime.Now;
		}
	}
	public class JoinMessage : IMessage
	{
		public override MessageType Type => MessageType.Join;

		[JsonProperty("secret")]
		public string Secret { get; internal set; }
	}
	public class JoinRequestMessage : IMessage
	{
		public override MessageType Type => MessageType.JoinRequest;

		[JsonProperty("user")]
		public User User { get; internal set; }
	}
	public enum MessageType
	{
		Ready,
		Close,
		Error,
		PresenceUpdate,
		Subscribe,
		Unsubscribe,
		Join,
		Spectate,
		JoinRequest,
		ConnectionEstablished,
		ConnectionFailed
	}
	public class PresenceMessage : IMessage
	{
		public override MessageType Type => MessageType.PresenceUpdate;

		public BaseRichPresence Presence { get; internal set; }

		public string Name { get; internal set; }

		public string ApplicationID { get; internal set; }

		internal PresenceMessage()
			: this(null)
		{
		}

		internal PresenceMessage(RichPresenceResponse rpr)
		{
			if (rpr == null)
			{
				Presence = null;
				Name = "No Rich Presence";
				ApplicationID = "";
			}
			else
			{
				Presence = rpr;
				Name = rpr.Name;
				ApplicationID = rpr.ClientID;
			}
		}
	}
	public class ReadyMessage : IMessage
	{
		public override MessageType Type => MessageType.Ready;

		[JsonProperty("config")]
		public Configuration Configuration { get; set; }

		[JsonProperty("user")]
		public User User { get; set; }

		[JsonProperty("v")]
		public int Version { get; set; }
	}
	public class SpectateMessage : JoinMessage
	{
		public override MessageType Type => MessageType.Spectate;
	}
	public class SubscribeMessage : IMessage
	{
		public override MessageType Type => MessageType.Subscribe;

		public EventType Event { get; internal set; }

		internal SubscribeMessage(ServerEvent evt)
		{
			switch (evt)
			{
			default:
				Event = EventType.Join;
				break;
			case ServerEvent.ActivityJoinRequest:
				Event = EventType.JoinRequest;
				break;
			case ServerEvent.ActivitySpectate:
				Event = EventType.Spectate;
				break;
			}
		}
	}
	public class UnsubscribeMessage : IMessage
	{
		public override MessageType Type => MessageType.Unsubscribe;

		public EventType Event { get; internal set; }

		internal UnsubscribeMessage(ServerEvent evt)
		{
			switch (evt)
			{
			default:
				Event = EventType.Join;
				break;
			case ServerEvent.ActivityJoinRequest:
				Event = EventType.JoinRequest;
				break;
			case ServerEvent.ActivitySpectate:
				Event = EventType.Spectate;
				break;
			}
		}
	}
}
namespace DiscordRPC.Logging
{
	public class ConsoleLogger : ILogger
	{
		public LogLevel Level { get; set; }

		public bool Coloured { get; set; }

		[Obsolete("Use Coloured")]
		public bool Colored
		{
			get
			{
				return Coloured;
			}
			set
			{
				Coloured = value;
			}
		}

		public ConsoleLogger()
		{
			Level = LogLevel.Info;
			Coloured = false;
		}

		public ConsoleLogger(LogLevel level)
			: this()
		{
			Level = level;
		}

		public ConsoleLogger(LogLevel level, bool coloured)
		{
			Level = level;
			Coloured = coloured;
		}

		public void Trace(string message, params object[] args)
		{
			if (Level <= LogLevel.Trace)
			{
				if (Coloured)
				{
					Console.ForegroundColor = ConsoleColor.Gray;
				}
				string text = "TRACE: " + message;
				if (args.Length != 0)
				{
					Console.WriteLine(text, args);
				}
				else
				{
					Console.WriteLine(text);
				}
			}
		}

		public void Info(string message, params object[] args)
		{
			if (Level <= LogLevel.Info)
			{
				if (Coloured)
				{
					Console.ForegroundColor = ConsoleColor.White;
				}
				string text = "INFO: " + message;
				if (args.Length != 0)
				{
					Console.WriteLine(text, args);
				}
				else
				{
					Console.WriteLine(text);
				}
			}
		}

		public void Warning(string message, params object[] args)
		{
			if (Level <= LogLevel.Warning)
			{
				if (Coloured)
				{
					Console.ForegroundColor = ConsoleColor.Yellow;
				}
				string text = "WARN: " + message;
				if (args.Length != 0)
				{
					Console.WriteLine(text, args);
				}
				else
				{
					Console.WriteLine(text);
				}
			}
		}

		public void Error(string message, params object[] args)
		{
			if (Level <= LogLevel.Error)
			{
				if (Coloured)
				{
					Console.ForegroundColor = ConsoleColor.Red;
				}
				string text = "ERR : " + message;
				if (args.Length != 0)
				{
					Console.WriteLine(text, args);
				}
				else
				{
					Console.WriteLine(text);
				}
			}
		}
	}
	public class FileLogger : ILogger
	{
		private object filelock;

		public LogLevel Level { get; set; }

		public string File { get; set; }

		public FileLogger(string path)
			: this(path, LogLevel.Info)
		{
		}

		public FileLogger(string path, LogLevel level)
		{
			Level = level;
			File = path;
			filelock = new object();
		}

		public void Trace(string message, params object[] args)
		{
			if (Level > LogLevel.Trace)
			{
				return;
			}
			lock (filelock)
			{
				System.IO.File.AppendAllText(File, "\r\nTRCE: " + ((args.Length != 0) ? string.Format(message, args) : message));
			}
		}

		public void Info(string message, params object[] args)
		{
			if (Level > LogLevel.Info)
			{
				return;
			}
			lock (filelock)
			{
				System.IO.File.AppendAllText(File, "\r\nINFO: " + ((args.Length != 0) ? string.Format(message, args) : message));
			}
		}

		public void Warning(string message, params object[] args)
		{
			if (Level > LogLevel.Warning)
			{
				return;
			}
			lock (filelock)
			{
				System.IO.File.AppendAllText(File, "\r\nWARN: " + ((args.Length != 0) ? string.Format(message, args) : message));
			}
		}

		public void Error(string message, params object[] args)
		{
			if (Level > LogLevel.Error)
			{
				return;
			}
			lock (filelock)
			{
				System.IO.File.AppendAllText(File, "\r\nERR : " + ((args.Length != 0) ? string.Format(message, args) : message));
			}
		}
	}
	public interface ILogger
	{
		LogLevel Level { get; set; }

		void Trace(string message, params object[] args);

		void Info(string message, params object[] args);

		void Warning(string message, params object[] args);

		void Error(string message, params object[] args);
	}
	public enum LogLevel
	{
		Trace = 1,
		Info = 2,
		Warning = 3,
		Error = 4,
		None = 256
	}
	public class NullLogger : ILogger
	{
		public LogLevel Level { get; set; }

		public void Trace(string message, params object[] args)
		{
		}

		public void Info(string message, params object[] args)
		{
		}

		public void Warning(string message, params object[] args)
		{
		}

		public void Error(string message, params object[] args)
		{
		}
	}
}
namespace DiscordRPC.IO
{
	internal class Handshake
	{
		[JsonProperty("v")]
		public int Version { get; set; }

		[JsonProperty("client_id")]
		public string ClientID { get; set; }
	}
	public interface INamedPipeClient : IDisposable
	{
		ILogger Logger { get; set; }

		bool IsConnected { get; }

		int ConnectedPipe { get; }

		bool Connect(int pipe);

		bool ReadFrame(out PipeFrame frame);

		bool WriteFrame(PipeFrame frame);

		void Close();
	}
	public sealed class ManagedNamedPipeClient : INamedPipeClient, IDisposable
	{
		private const string PIPE_NAME = "discord-ipc-{0}";

		private int _connectedPipe;

		private NamedPipeClientStream _stream;

		private byte[] _buffer = new byte[PipeFrame.MAX_SIZE];

		private Queue<PipeFrame> _framequeue = new Queue<PipeFrame>();

		private object _framequeuelock = new object();

		private volatile bool _isDisposed = false;

		private volatile bool _isClosed = true;

		private object l_stream = new object();

		public ILogger Logger { get; set; }

		public bool IsConnected
		{
			get
			{
				if (_isClosed)
				{
					return false;
				}
				lock (l_stream)
				{
					return _stream != null && _stream.IsConnected;
				}
			}
		}

		public int ConnectedPipe => _connectedPipe;

		public ManagedNamedPipeClient()
		{
			_buffer = new byte[PipeFrame.MAX_SIZE];
			Logger = new NullLogger();
			_stream = null;
		}

		public bool Connect(int pipe)
		{
			Logger.Trace("ManagedNamedPipeClient.Connection({0})", pipe);
			if (_isDisposed)
			{
				throw new ObjectDisposedException("NamedPipe");
			}
			if (pipe > 9)
			{
				throw new ArgumentOutOfRangeException("pipe", "Argument cannot be greater than 9");
			}
			if (pipe < 0)
			{
				for (int i = 0; i < 10; i++)
				{
					if (AttemptConnection(i) || AttemptConnection(i, isSandbox: true))
					{
						BeginReadStream();
						return true;
					}
				}
			}
			else if (AttemptConnection(pipe) || AttemptConnection(pipe, isSandbox: true))
			{
				BeginReadStream();
				return true;
			}
			return false;
		}

		private bool AttemptConnection(int pipe, bool isSandbox = false)
		{
			if (_isDisposed)
			{
				throw new ObjectDisposedException("_stream");
			}
			string text = (isSandbox ? GetPipeSandbox() : "");
			if (isSandbox && text == null)
			{
				Logger.Trace("Skipping sandbox connection.");
				return false;
			}
			Logger.Trace("Connection Attempt {0} ({1})", pipe, text);
			string pipeName = GetPipeName(pipe, text);
			try
			{
				lock (l_stream)
				{
					Logger.Info("Attempting to connect to '{0}'", pipeName);
					_stream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
					_stream.Connect(0);
					Logger.Trace("Waiting for connection...");
					do
					{
						Thread.Sleep(10);
					}
					while (!_stream.IsConnected);
				}
				Logger.Info("Connected to '{0}'", pipeName);
				_connectedPipe = pipe;
				_isClosed = false;
			}
			catch (Exception ex)
			{
				Logger.Error("Failed connection to {0}. {1}", pipeName, ex.Message);
				Close();
			}
			Logger.Trace("Done. Result: {0}", _isClosed);
			return !_isClosed;
		}

		private void BeginReadStream()
		{
			if (_isClosed)
			{
				return;
			}
			try
			{
				lock (l_stream)
				{
					if (_stream != null && _stream.IsConnected)
					{
						Logger.Trace("Begining Read of {0} bytes", _buffer.Length);
						_stream.BeginRead(_buffer, 0, _buffer.Length, EndReadStream, _stream.IsConnected);
					}
				}
			}
			catch (ObjectDisposedException)
			{
				Logger.Warning("Attempted to start reading from a disposed pipe");
			}
			catch (InvalidOperationException)
			{
				Logger.Warning("Attempted to start reading from a closed pipe");
			}
			catch (Exception ex3)
			{
				Logger.Error("An exception occured while starting to read a stream: {0}", ex3.Message);
				Logger.Error(ex3.StackTrace);
			}
		}

		private void EndReadStream(IAsyncResult callback)
		{
			Logger.Trace("Ending Read");
			int num = 0;
			try
			{
				lock (l_stream)
				{
					if (_stream == null || !_stream.IsConnected)
					{
						return;
					}
					num = _stream.EndRead(callback);
				}
			}
			catch (IOException)
			{
				Logger.Warning("Attempted to end reading from a closed pipe");
				return;
			}
			catch (NullReferenceException)
			{
				Logger.Warning("Attempted to read from a null pipe");
				return;
			}
			catch (ObjectDisposedException)
			{
				Logger.Warning("Attemped to end reading from a disposed pipe");
				return;
			}
			catch (Exception ex4)
			{
				Logger.Error("An exception occured while ending a read of a stream: {0}", ex4.Message);
				Logger.Error(ex4.StackTrace);
				return;
			}
			Logger.Trace("Read {0} bytes", num);
			if (num > 0)
			{
				using MemoryStream stream = new MemoryStream(_buffer, 0, num);
				try
				{
					PipeFrame item = default(PipeFrame);
					if (item.ReadStream(stream))
					{
						Logger.Trace("Read a frame: {0}", item.Opcode);
						lock (_framequeuelock)
						{
							_framequeue.Enqueue(item);
						}
					}
					else
					{
						Logger.Error("Pipe failed to read from the data received by the stream.");
						Close();
					}
				}
				catch (Exception ex5)
				{
					Logger.Error("A exception has occured while trying to parse the pipe data: {0}", ex5.Message);
					Close();
				}
			}
			else if (IsUnix())
			{
				Logger.Error("Empty frame was read on {0}, aborting.", Environment.OSVersion);
				Close();
			}
			else
			{
				Logger.Warning("Empty frame was read. Please send report to Lachee.");
			}
			if (!_isClosed && IsConnected)
			{
				Logger.Trace("Starting another read");
				BeginReadStream();
			}
		}

		public bool ReadFrame(out PipeFrame frame)
		{
			if (_isDisposed)
			{
				throw new ObjectDisposedException("_stream");
			}
			lock (_framequeuelock)
			{
				if (_framequeue.Count == 0)
				{
					frame = default(PipeFrame);
					return false;
				}
				frame = _framequeue.Dequeue();
				return true;
			}
		}

		public bool WriteFrame(PipeFrame frame)
		{
			if (_isDisposed)
			{
				throw new ObjectDisposedException("_stream");
			}
			if (_isClosed || !IsConnected)
			{
				Logger.Error("Failed to write frame because the stream is closed");
				return false;
			}
			try
			{
				frame.WriteStream(_stream);
				return true;
			}
			catch (IOException ex)
			{
				Logger.Error("Failed to write frame because of a IO Exception: {0}", ex.Message);
			}
			catch (ObjectDisposedException)
			{
				Logger.Warning("Failed to write frame as the stream was already disposed");
			}
			catch (InvalidOperationException)
			{
				Logger.Warning("Failed to write frame because of a invalid operation");
			}
			return false;
		}

		public void Close()
		{
			if (_isClosed)
			{
				Logger.Warning("Tried to close a already closed pipe.");
				return;
			}
			try
			{
				lock (l_stream)
				{
					if (_stream != null)
					{
						try
						{
							_stream.Flush();
							_stream.Dispose();
						}
						catch (Exception)
						{
						}
						_stream = null;
						_isClosed = true;
					}
					else
					{
						Logger.Warning("Stream was closed, but no stream was available to begin with!");
					}
				}
			}
			catch (ObjectDisposedException)
			{
				Logger.Warning("Tried to dispose already disposed stream");
			}
			finally
			{
				_isClosed = true;
				_connectedPipe = -1;
			}
		}

		public void Dispose()
		{
			if (_isDisposed)
			{
				return;
			}
			if (!_isClosed)
			{
				Close();
			}
			lock (l_stream)
			{
				if (_stream != null)
				{
					_stream.Dispose();
					_stream = null;
				}
			}
			_isDisposed = true;
		}

		public static string GetPipeName(int pipe, string sandbox)
		{
			if (!IsUnix())
			{
				return sandbox + $"discord-ipc-{pipe}";
			}
			return Path.Combine(GetTemporaryDirectory(), sandbox + $"discord-ipc-{pipe}");
		}

		public static string GetPipeName(int pipe)
		{
			return GetPipeName(pipe, "");
		}

		public static string GetPipeSandbox()
		{
			PlatformID platform = Environment.OSVersion.Platform;
			PlatformID platformID = platform;
			if (platformID != PlatformID.Unix)
			{
				return null;
			}
			return "snap.discord/";
		}

		private static string GetTemporaryDirectory()
		{
			string text = null;
			text = text ?? Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR");
			text = text ?? Environment.GetEnvironmentVariable("TMPDIR");
			text = text ?? Environment.GetEnvironmentVariable("TMP");
			text = text ?? Environment.GetEnvironmentVariable("TEMP");
			return text ?? "/tmp";
		}

		public static bool IsUnix()
		{
			PlatformID platform = Environment.OSVersion.Platform;
			PlatformID platformID = platform;
			if (platformID != PlatformID.Unix && platformID != PlatformID.MacOSX)
			{
				return false;
			}
			return true;
		}
	}
	public enum Opcode : uint
	{
		Handshake,
		Frame,
		Close,
		Ping,
		Pong
	}
	public struct PipeFrame : IEquatable<PipeFrame>
	{
		public static readonly int MAX_SIZE = 16384;

		public Opcode Opcode { get; set; }

		public uint Length => (uint)Data.Length;

		public byte[] Data { get; set; }

		public string Message
		{
			get
			{
				return GetMessage();
			}
			set
			{
				SetMessage(value);
			}
		}

		public Encoding MessageEncoding => Encoding.UTF8;

		public PipeFrame(Opcode opcode, object data)
		{
			Opcode = opcode;
			Data = null;
			SetObject(data);
		}

		private void SetMessage(string str)
		{
			Data = MessageEncoding.GetBytes(str);
		}

		private string GetMessage()
		{
			return MessageEncoding.GetString(Data);
		}

		public void SetObject(object obj)
		{
			string message = JsonConvert.SerializeObject(obj);
			SetMessage(message);
		}

		public void SetObject(Opcode opcode, object obj)
		{
			Opcode = opcode;
			SetObject(obj);
		}

		public T GetObject<T>()
		{
			string message = GetMessage();
			return JsonConvert.DeserializeObject<T>(message);
		}

		public bool ReadStream(Stream stream)
		{
			if (!TryReadUInt32(stream, out var value))
			{
				return false;
			}
			if (!TryReadUInt32(stream, out var value2))
			{
				return false;
			}
			uint num = value2;
			using MemoryStream memoryStream = new MemoryStream();
			uint num2 = (uint)Min(2048, value2);
			byte[] array = new byte[num2];
			int count;
			while ((count = stream.Read(array, 0, Min(array.Length, num))) > 0)
			{
				num -= num2;
				memoryStream.Write(array, 0, count);
			}
			byte[] array2 = memoryStream.ToArray();
			if (array2.LongLength != value2)
			{
				return false;
			}
			Opcode = (Opcode)value;
			Data = array2;
			return true;
		}

		private int Min(int a, uint b)
		{
			if (b >= a)
			{
				return a;
			}
			return (int)b;
		}

		private bool TryReadUInt32(Stream stream, out uint value)
		{
			byte[] array = new byte[4];
			int num = stream.Read(array, 0, array.Length);
			if (num != 4)
			{
				value = 0u;
				return false;
			}
			value = BitConverter.ToUInt32(array, 0);
			return true;
		}

		public void WriteStream(Stream stream)
		{
			byte[] bytes = BitConverter.GetBytes((uint)Opcode);
			byte[] bytes2 = BitConverter.GetBytes(Length);
			byte[] array = new byte[bytes.Length + bytes2.Length + Data.Length];
			bytes.CopyTo(array, 0);
			bytes2.CopyTo(array, bytes.Length);
			Data.CopyTo(array, bytes.Length + bytes2.Length);
			stream.Write(array, 0, array.Length);
		}

		public bool Equals(PipeFrame other)
		{
			return Opcode == other.Opcode && Length == other.Length && Data == other.Data;
		}
	}
}
namespace DiscordRPC.Helper
{
	internal class BackoffDelay
	{
		private int _current;

		private int _fails;

		public int Maximum { get; private set; }

		public int Minimum { get; private set; }

		public int Current => _current;

		public int Fails => _fails;

		public Random Random { get; set; }

		private BackoffDelay()
		{
		}

		public BackoffDelay(int min, int max)
			: this(min, max, new Random())
		{
		}

		public BackoffDelay(int min, int max, Random random)
		{
			Minimum = min;
			Maximum = max;
			_current = min;
			_fails = 0;
			Random = random;
		}

		public void Reset()
		{
			_fails = 0;
			_current = Minimum;
		}

		public int NextDelay()
		{
			_fails++;
			double num = (float)(Maximum - Minimum) / 100f;
			_current = (int)Math.Floor(num * (double)_fails) + Minimum;
			return Math.Min(Math.Max(_current, Minimum), Maximum);
		}
	}
	public static class StringTools
	{
		public static string GetNullOrString(this string str)
		{
			return (str.Length == 0 || string.IsNullOrEmpty(str.Trim())) ? null : str;
		}

		public static bool WithinLength(this string str, int bytes)
		{
			return str.WithinLength(bytes, Encoding.UTF8);
		}

		public static bool WithinLength(this string str, int bytes, Encoding encoding)
		{
			return encoding.GetByteCount(str) <= bytes;
		}

		public static string ToCamelCase(this string str)
		{
			return (from s in str?.ToLowerInvariant().Split(new string[2] { "_", " " }, StringSplitOptions.RemoveEmptyEntries)
				select char.ToUpper(s[0]) + s.Substring(1, s.Length - 1)).Aggregate(string.Empty, (string s1, string s2) => s1 + s2);
		}

		public static string ToSnakeCase(this string str)
		{
			if (str == null)
			{
				return null;
			}
			string text = string.Concat(str.Select((char x, int i) => (i > 0 && char.IsUpper(x)) ? ("_" + x) : x.ToString()).ToArray());
			return text.ToUpperInvariant();
		}
	}
}
namespace DiscordRPC.Exceptions
{
	public class BadPresenceException : Exception
	{
		internal BadPresenceException(string message)
			: base(message)
		{
		}
	}
	public class InvalidConfigurationException : Exception
	{
		internal InvalidConfigurationException(string message)
			: base(message)
		{
		}
	}
	[Obsolete("Not actually used anywhere")]
	public class InvalidPipeException : Exception
	{
		internal InvalidPipeException(string message)
			: base(message)
		{
		}
	}
	public class StringOutOfRangeException : Exception
	{
		public int MaximumLength { get; private set; }

		public int MinimumLength { get; private set; }

		internal StringOutOfRangeException(string message, int min, int max)
			: base(message)
		{
			MinimumLength = min;
			MaximumLength = max;
		}

		internal StringOutOfRangeException(int minumum, int max)
			: this($"Length of string is out of range. Expected a value between {minumum} and {max}", minumum, max)
		{
		}

		internal StringOutOfRangeException(int max)
			: this($"Length of string is out of range. Expected a value with a maximum length of {max}", 0, max)
		{
		}
	}
	public class UninitializedException : Exception
	{
		internal UninitializedException(string message)
			: base(message)
		{
		}

		internal UninitializedException()
			: this("Cannot perform action because the client has not been initialized yet or has been deinitialized.")
		{
		}
	}
}
namespace DiscordRPC.Events
{
	public delegate void OnReadyEvent(object sender, ReadyMessage args);
	public delegate void OnCloseEvent(object sender, CloseMessage args);
	public delegate void OnErrorEvent(object sender, ErrorMessage args);
	public delegate void OnPresenceUpdateEvent(object sender, PresenceMessage args);
	public delegate void OnSubscribeEvent(object sender, SubscribeMessage args);
	public delegate void OnUnsubscribeEvent(object sender, UnsubscribeMessage args);
	public delegate void OnJoinEvent(object sender, JoinMessage args);
	public delegate void OnSpectateEvent(object sender, SpectateMessage args);
	public delegate void OnJoinRequestedEvent(object sender, JoinRequestMessage args);
	public delegate void OnConnectionEstablishedEvent(object sender, ConnectionEstablishedMessage args);
	public delegate void OnConnectionFailedEvent(object sender, ConnectionFailedMessage args);
	public delegate void OnRpcMessageEvent(object sender, IMessage msg);
}
namespace DiscordRPC.Converters
{
	internal class EnumSnakeCaseConverter : JsonConverter
	{
		public override bool CanConvert(Type objectType)
		{
			return objectType.IsEnum;
		}

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			if (reader.Value == null)
			{
				return null;
			}
			object obj = null;
			if (TryParseEnum(objectType, (string)reader.Value, out obj))
			{
				return obj;
			}
			return existingValue;
		}

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			Type type = value.GetType();
			string text = Enum.GetName(type, value);
			MemberInfo[] members = type.GetMembers(BindingFlags.Static | BindingFlags.Public);
			MemberInfo[] array = members;
			foreach (MemberInfo memberInfo in array)
			{
				if (memberInfo.Name.Equals(text))
				{
					object[] customAttributes = memberInfo.GetCustomAttributes(typeof(EnumValueAttribute), inherit: true);
					if (customAttributes.Length != 0)
					{
						text = ((EnumValueAttribute)customAttributes[0]).Value;
					}
				}
			}
			writer.WriteValue(text);
		}

		public bool TryParseEnum(Type enumType, string str, out object obj)
		{
			if (str == null)
			{
				obj = null;
				return false;
			}
			Type type = enumType;
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
			{
				type = type.GetGenericArguments().First();
			}
			if (!type.IsEnum)
			{
				obj = null;
				return false;
			}
			MemberInfo[] members = type.GetMembers(BindingFlags.Static | BindingFlags.Public);
			MemberInfo[] array = members;
			foreach (MemberInfo memberInfo in array)
			{
				object[] customAttributes = memberInfo.GetCustomAttributes(typeof(EnumValueAttribute), inherit: true);
				object[] array2 = customAttributes;
				foreach (object obj2 in array2)
				{
					EnumValueAttribute enumValueAttribute = (EnumValueAttribute)obj2;
					if (str.Equals(enumValueAttribute.Value))
					{
						obj = Enum.Parse(type, memberInfo.Name, ignoreCase: true);
						return true;
					}
				}
			}
			obj = null;
			return false;
		}
	}
	internal class EnumValueAttribute : Attribute
	{
		public string Value { get; set; }

		public EnumValueAttribute(string value)
		{
			Value = value;
		}
	}
}

plugins/Marioalexsan.AtlyssDiscordRichPresence.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using DiscordRPC;
using DiscordRPC.Events;
using DiscordRPC.IO;
using DiscordRPC.Logging;
using DiscordRPC.Message;
using DiscordRPC.Registry;
using HarmonyLib;
using Marioalexsan.AtlyssDiscordRichPresence.HarmonyPatches;
using Marioalexsan.AtlyssDiscordRichPresence.SoftDependencies;
using Microsoft.CodeAnalysis;
using Nessie.ATLYSS.EasySettings;
using Nessie.ATLYSS.EasySettings.UIElements;
using Steamworks;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("DiscordRPC")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Marioalexsan.AtlyssDiscordRichPresence")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyInformationalVersion("1.4.0+57d3642b402b5502e0799161be989e36636d35f7")]
[assembly: AssemblyProduct("AtlyssDiscordRichPresence")]
[assembly: AssemblyTitle("Marioalexsan.AtlyssDiscordRichPresence")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.4.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 NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
public struct ServerData
{
	public int Size;

	public int Max;

	public string Id;

	public bool AllowJoining;
}
public struct PresenceData
{
	public string State;

	public string Details;

	public string LargeImageKey;

	public string LargeImageText;

	public string SmallImageKey;

	public string SmallImageText;

	public ServerData? Multiplayer;
}
internal class ProtonUnixUriSchemeCreator : IUriSchemeCreator
{
	private readonly ILogger logger;

	public ProtonUnixUriSchemeCreator(ILogger logger)
	{
		this.logger = logger;
		base..ctor();
	}

	public bool RegisterUriScheme(UriSchemeRegister register)
	{
		string environmentVariable = Environment.GetEnvironmentVariable("WINEUSERNAME");
		if (string.IsNullOrEmpty(environmentVariable))
		{
			logger.Error("Failed to register because the WINEUSERNAME variable was not set.", Array.Empty<object>());
			return false;
		}
		string text = "/home/" + environmentVariable;
		string executablePath = register.ExecutablePath;
		if (string.IsNullOrEmpty(executablePath))
		{
			logger.Error("Failed to register because the application was not located.", Array.Empty<object>());
			return false;
		}
		string text2 = (register.UsingSteamApp ? ("xdg-open steam://rungameid/" + register.SteamAppID) : executablePath);
		string text3 = ("[Desktop Entry]\r\nName=Game " + register.ApplicationID + "\r\nExec=" + text2 + "\r\nType=Application\r\nNoDisplay=true\r\nCategories=Discord;Games;\r\nMimeType=x-scheme-handler/discord-" + register.ApplicationID).Replace("\\", "/");
		string path = "discord-" + register.ApplicationID + ".desktop";
		string text4 = "Z:/" + text + "/.local/share/applications";
		DirectoryInfo directoryInfo = Directory.CreateDirectory(text4);
		if (!directoryInfo.Exists)
		{
			logger.Error("Failed to register because {0} does not exist", new object[1] { text4 });
			return false;
		}
		File.WriteAllText(Path.Combine(text4, path), text3);
		if (!RegisterMime(text, register.ApplicationID))
		{
			logger.Error("Failed to register because the Mime failed.", Array.Empty<object>());
			return false;
		}
		logger.Trace("Registered {0}, {1}, {2}", new object[3]
		{
			Path.Combine(text4, path),
			text3,
			text2
		});
		return true;
	}

	private bool RegisterMime(string homeDir, string appid)
	{
		string text = "x-scheme-handler/discord-" + appid + "=discord-" + appid + ".desktop";
		string path = "Z:/" + homeDir + "/.config/mimeapps.list";
		string path2 = "Z:/" + homeDir + "/.config/mimeapps.list.atlyssbackup";
		if (!File.Exists(path))
		{
			logger.Error("Couldn't find .config/mimeapps.list to update.", Array.Empty<object>());
			return false;
		}
		string text2 = File.ReadAllText(path);
		if (!File.Exists(path2))
		{
			logger.Warning("Created a backup for ./config/mimeapps.list under ./config/mimeapps.list.atlyssbackup!", Array.Empty<object>());
			File.WriteAllText(path2, text2);
		}
		if (text2.Contains(text))
		{
			logger.Info("App is already registered under ./config/mimeapps.list.", Array.Empty<object>());
			return true;
		}
		int num = text2.IndexOf("[Default Applications]");
		if (num == -1)
		{
			text2 = text2 + "\n\n[Default Applications]\n" + text + "\n";
			logger.Info("Added default section and entry under ./config/mimeapps.list.", Array.Empty<object>());
		}
		else
		{
			text2 = text2.Insert(num + "[Default Applications]".Length, "\n" + text);
			logger.Info("Updated default section with entry under ./config/mimeapps.list.", Array.Empty<object>());
		}
		File.WriteAllText(path, text2);
		return true;
	}
}
namespace Marioalexsan.AtlyssDiscordRichPresence
{
	public static class Assets
	{
		public const string ATLYSS_ICON = "atlyss_icon";

		public const string ZONESELECTIONICON_SAFE = "zoneselectionicon_safe";

		public const string ZONESELECTIONICON_ARENA = "zoneselectionicon_arena";

		public const string ZONESELECTIONICON_DUNGEON = "zoneselectionicon_dungeon";

		public const string ZONESELECTIONICON_FIELD = "zoneselectionicon_field";

		public const string ATLYSS_SINGLEPLAYER = "atlyss_singleplayer";

		public const string ATLYSS_MULTIPLAYER = "atlyss_multiplayer";
	}
	[BepInPlugin("Marioalexsan.AtlyssDiscordRichPresence", "AtlyssDiscordRichPresence", "1.4.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class AtlyssDiscordRichPresence : BaseUnityPlugin
	{
		public enum JoinEnableSetting
		{
			JoiningDisabled,
			PublicOnly,
			PublicAndFriends,
			All
		}

		private enum TimerTrackerState
		{
			MainMenu,
			ExploringWorld
		}

		public const string DefaultDiscordAppId = "1309967280842735738";

		private static AtlyssDiscordRichPresence? _plugin;

		private readonly Display _display;

		private readonly GameState _state = new GameState();

		private readonly RichPresenceWrapper _richPresence;

		private readonly Harmony _harmony;

		private ulong? QueuedSteamLobbyId;

		private TimerTrackerState _timeTrackerState;

		public static AtlyssDiscordRichPresence Plugin => _plugin ?? throw new InvalidOperationException("AtlyssDiscordRichPresence hasn't been initialized yet. Either wait until initialization, or check via ChainLoader instead.");

		internal ManualLogSource Logger { get; private set; }

		public ConfigEntry<bool> ModEnabled { get; private set; }

		public ConfigEntry<JoinEnableSetting> ServerJoinSetting { get; private set; }

		public ConfigEntry<string> DiscordAppId { get; private set; }

		public ConfigEntry<RichPresenceWrapper.LogLevels> DiscordRPCLogLevel { get; private set; }

		public AtlyssDiscordRichPresence()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			_plugin = this;
			Logger = ((BaseUnityPlugin)this).Logger;
			_harmony = new Harmony("Marioalexsan.AtlyssDiscordRichPresence");
			_display = new Display(((BaseUnityPlugin)this).Config);
			ModEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enable", true, "Enable or disable this mod. While disabled, no in-game data is shown.");
			ServerJoinSetting = ((BaseUnityPlugin)this).Config.Bind<JoinEnableSetting>("General", "ServerJoinSetting", JoinEnableSetting.PublicAndFriends, "Set the server privacy levels for which Discord should allow joining.");
			DiscordRPCLogLevel = ((BaseUnityPlugin)this).Config.Bind<RichPresenceWrapper.LogLevels>("General", "DiscordRPCLogLevel", RichPresenceWrapper.LogLevels.Warning, "Log level to use for logs coming from the Discord RPC library.");
			DiscordAppId = ((BaseUnityPlugin)this).Config.Bind<string>("Advanced", "DiscordAppId", "1309967280842735738", "The Discord application ID to be used by the mod. ***Do not change this unless you know what you're doing!***");
			_richPresence = new RichPresenceWrapper(DiscordAppId.Value, Logger, DiscordRPCLogLevel.Value);
			_richPresence.OnJoin += OnJoinLobby;
			if (WineDetect.IsRunningInWine)
			{
				Logging.LogInfo("Wine detected!");
				Logging.LogInfo("Wine version: " + WineDetect.WineVersion);
				Logging.LogInfo("System name: " + WineDetect.SystemName);
				Logging.LogInfo("System version: " + WineDetect.SystemVersion);
			}
			else
			{
				Logging.LogInfo("Wine not detected!");
			}
		}

		private void OnJoinLobby(object sender, RichPresenceWrapper.JoinData e)
		{
			Logging.LogInfo("OnJoinLobby " + e.Id);
			string text = e.Id;
			if (text.StartsWith("secret_"))
			{
				string text2 = text;
				int length = "secret_".Length;
				text = text2.Substring(length, text2.Length - length);
			}
			if (!ulong.TryParse(text, out var result))
			{
				Logging.LogInfo("ID is invalid, can't join.");
			}
			else
			{
				QueuedSteamLobbyId = result;
			}
		}

		private void UpdatePresence(PresenceData data, TimerTrackerState state)
		{
			_richPresence.SetPresence(data, _timeTrackerState != state);
			_timeTrackerState = state;
		}

		private void Update()
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Invalid comparison between Unknown and I4
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)MainMenuManager._current))
			{
				return;
			}
			if (QueuedSteamLobbyId.HasValue)
			{
				ulong value = QueuedSteamLobbyId.Value;
				QueuedSteamLobbyId = null;
				SteamLobby._current.Init_LobbyJoinRequest(new CSteamID(value));
			}
			if ((int)MainMenuManager._current._mainMenuCondition != 4)
			{
				UpdateMainMenuPresence(MainMenuManager._current);
			}
			else
			{
				if (Object.op_Implicit((Object)(object)AtlyssNetworkManager._current) && !AtlyssNetworkManager._current._soloMode && (!AtlyssNetworkManager._current._steamworksMode || SteamManager.Initialized) && Object.op_Implicit((Object)(object)Player._mainPlayer))
				{
					_state.InMultiplayer = true;
					_state.Players = Object.FindObjectsOfType<Player>().Length;
					_state.MaxPlayers = ServerInfoObject._current._maxConnections;
					_state.ServerName = ServerInfoObject._current._serverName;
					_state.ServerJoinId = SteamLobby._current._currentLobbyID.ToString();
				}
				else
				{
					_state.InMultiplayer = false;
					_state.Players = 1;
					_state.MaxPlayers = 1;
					_state.ServerJoinId = "";
				}
				UpdateWorldAreaPresence(Player._mainPlayer, null);
				CheckCombatState();
			}
			_richPresence.Tick();
		}

		private void Awake()
		{
			InitializeConfiguration();
			_harmony.PatchAll();
			_richPresence.Enabled = ModEnabled.Value;
		}

		private void InitializeConfiguration()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			if (!EasySettings.IsAvailable)
			{
				return;
			}
			EasySettings.OnApplySettings.AddListener((UnityAction)delegate
			{
				try
				{
					((BaseUnityPlugin)this).Config.Save();
					_richPresence.LogLevel = DiscordRPCLogLevel.Value;
					_richPresence.Enabled = ModEnabled.Value;
				}
				catch (Exception ex)
				{
					Logging.LogError("AtlyssDiscordRichPresence crashed in OnApplySettings! Please report this error to the mod developer:");
					Logging.LogError(ex.ToString());
				}
			});
			EasySettings.OnInitialized.AddListener((UnityAction)delegate
			{
				EasySettings.AddHeader("Atlyss Discord Rich Presence");
				EasySettings.AddToggle("Enabled", ModEnabled);
				EasySettings.AddDropdown<JoinEnableSetting>("Enable server joining in Discord", ServerJoinSetting);
				EasySettings.AddDropdown<RichPresenceWrapper.LogLevels>("DiscordRPC log level", DiscordRPCLogLevel);
				EasySettings.AddDropdown<Display.DisplayPresets>("Rich Presence display preset", _display.DisplayPreset);
			});
		}

		private void OnDestroy()
		{
			_richPresence.Dispose();
		}

		internal void CheckCombatState()
		{
			_state.InArenaCombat = false;
			_state.InBossCombat = false;
			_state.InPostBoss = false;
			_state.BossName = "";
			if (Object.op_Implicit((Object)(object)Player._mainPlayer) && Object.op_Implicit((Object)(object)Player._mainPlayer._playerMapInstance))
			{
				if (Object.op_Implicit((Object)(object)Player._mainPlayer._playerMapInstance._patternInstance))
				{
					PatternInstanceManager patternInstance = Player._mainPlayer._playerMapInstance._patternInstance;
					bool inArenaCombat = false;
					for (int i = 0; i < patternInstance._setInstanceCreepArenas.Count; i++)
					{
						CreepArena val = patternInstance._setInstanceCreepArenas[i];
						if (val._arenaEnabled && val._creepSpawnerObject._playersWithinSpawnerRadius.Contains(Player._mainPlayer))
						{
							inArenaCombat = true;
							break;
						}
					}
					bool inBossCombat = patternInstance._isBossEngaged && Object.op_Implicit((Object)(object)patternInstance._bossSpawner) && patternInstance._bossSpawner._playersWithinSpawnerRadius.Contains(Player._mainPlayer);
					bool isBossDefeated = patternInstance._isBossDefeated;
					_state.InArenaCombat = inArenaCombat;
					_state.InBossCombat = inBossCombat;
					_state.InPostBoss = isBossDefeated;
					if (Object.op_Implicit((Object)(object)patternInstance._bossSpawner) && patternInstance._bossSpawner._spawnedCreeps.Count > 0)
					{
						_state.BossName = patternInstance._bossSpawner._spawnedCreeps[0].Network_creepDisplayName;
					}
				}
				else
				{
					Creep val2 = null;
					for (int j = 0; j < TrackedAggroCreeps.List.Count; j++)
					{
						Creep val3 = TrackedAggroCreeps.List[j];
						if ((Object)(object)val3 == (Object)null)
						{
							TrackedAggroCreeps.List.RemoveAt(j--);
						}
						else if (val3._scriptCreep._playMapInstanceActionMusic && Object.op_Implicit((Object)(object)val3.Network_aggroedEntity) && ((Object)(object)val2 == (Object)null || val3._creepLevel > val2._creepLevel))
						{
							val2 = val3;
						}
					}
					if ((Object)(object)val2 != (Object)null)
					{
						_state.InBossCombat = true;
						_state.BossName = val2._creepDisplayName;
					}
				}
			}
			UpdateWorldAreaPresence(null, null);
		}

		internal void Player_OnPlayerMapInstanceChange(Player self, MapInstance _new)
		{
			if ((Object)(object)self == (Object)(object)Player._mainPlayer)
			{
				_state.InArenaCombat = false;
				_state.InBossCombat = false;
				UpdateWorldAreaPresence(self, _new);
			}
		}

		private void UpdateMainMenuPresence(MainMenuManager manager)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)manager._mainMenuCondition == 2)
			{
				CharacterCreationManager characterCreationManager = manager._characterCreationManager;
				if (Object.op_Implicit((Object)(object)characterCreationManager))
				{
					InputField characterNameInputField = characterCreationManager._characterNameInputField;
					string text = ((characterNameInputField != null) ? characterNameInputField.text : null);
					if (string.IsNullOrEmpty(text))
					{
						text = "";
					}
					_state.CharacterCreationName = text;
					int currentRaceSelected = characterCreationManager._currentRaceSelected;
					if (0 <= currentRaceSelected && currentRaceSelected < characterCreationManager._raceDisplayModels.Length)
					{
						_state.CharacterCreationRace = characterCreationManager._raceDisplayModels[currentRaceSelected]?._scriptablePlayerRace?._raceName ?? "";
					}
					else
					{
						_state.CharacterCreationRace = "";
					}
					UpdatePresence(new PresenceData
					{
						Details = _display.GetText(Display.Texts.CharacterCreation, _state),
						State = _display.GetText(Display.Texts.CharacterCreationDetails, _state),
						LargeImageKey = "atlyss_icon",
						LargeImageText = "ATLYSS"
					}, TimerTrackerState.MainMenu);
				}
			}
			else
			{
				UpdatePresence(new PresenceData
				{
					Details = _display.GetText(Display.Texts.MainMenu, _state),
					LargeImageKey = "atlyss_icon",
					LargeImageText = "ATLYSS"
				}, TimerTrackerState.MainMenu);
			}
		}

		private void UpdateWorldAreaPresence(Player? player, MapInstance? area)
		{
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player != (Object)null)
			{
				_state.UpdateData(player);
			}
			if ((Object)(object)area != (Object)null)
			{
				_state.UpdateData(area);
			}
			string text = _display.GetText(Display.Texts.Exploring, _state);
			if (_state.IsIdle)
			{
				text = _display.GetText(Display.Texts.Idle, _state);
			}
			if (_state.InPostBoss)
			{
				text = _display.GetText(Display.Texts.DungeonBossEnd, _state);
			}
			else if (_state.InBossCombat)
			{
				text = _display.GetText(Display.Texts.FightingBoss, _state);
			}
			else if (_state.InArenaCombat)
			{
				text = _display.GetText(Display.Texts.FightingInArena, _state);
			}
			string text2 = _display.GetText(Display.Texts.PlayerAlive, _state);
			if (_state.HealthPercentage <= 0)
			{
				text2 = _display.GetText(Display.Texts.PlayerDead, _state);
			}
			UpdatePresence(new PresenceData
			{
				Details = text,
				State = text2,
				LargeImageKey = ((!_state.InMultiplayer) ? "atlyss_singleplayer" : "atlyss_multiplayer"),
				LargeImageText = ((!_state.InMultiplayer) ? _display.GetText(Display.Texts.Singleplayer, _state) : _display.GetText(Display.Texts.Multiplayer, _state)),
				SmallImageKey = MapAreaToIcon(_state.WorldAreaType),
				SmallImageText = _state.WorldArea,
				Multiplayer = ((!_state.InMultiplayer) ? null : new ServerData?(new ServerData
				{
					Id = _state.ServerJoinId,
					Size = _state.Players,
					Max = _state.MaxPlayers,
					AllowJoining = CanJoinMultiplayer()
				}))
			}, TimerTrackerState.ExploringWorld);
		}

		private bool CanJoinMultiplayer()
		{
			int value = LobbyListManager._current._lobbyTypeDropdown.value;
			if (1 == 0)
			{
			}
			bool result = value switch
			{
				0 => ServerJoinSetting.Value >= JoinEnableSetting.PublicOnly, 
				1 => ServerJoinSetting.Value >= JoinEnableSetting.PublicAndFriends, 
				2 => ServerJoinSetting.Value >= JoinEnableSetting.All, 
				_ => false, 
			};
			if (1 == 0)
			{
			}
			return result;
		}

		private static string MapAreaToIcon(ZoneType area)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected I4, but got Unknown
			if (1 == 0)
			{
			}
			string result = (int)area switch
			{
				0 => "zoneselectionicon_safe", 
				1 => "zoneselectionicon_field", 
				2 => "zoneselectionicon_dungeon", 
				3 => "zoneselectionicon_arena", 
				_ => "zoneselectionicon_field", 
			};
			if (1 == 0)
			{
			}
			return result;
		}
	}
	public class DiscordLogSourceLogger : ILogger
	{
		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private ManualLogSource <source>P;

		public LogLevel Level { get; set; }

		public DiscordLogSourceLogger(ManualLogSource source, LogLevel level)
		{
			//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)
			<source>P = source;
			Level = level;
			base..ctor();
		}

		public void Error(string message, params object[] args)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)Level <= 4)
			{
				<source>P.LogError((object)("[DiscordRPC:Error] " + string.Format(message, args)));
			}
		}

		public void Info(string message, params object[] args)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)Level <= 2)
			{
				<source>P.LogInfo((object)("[DiscordRPC:Info] " + string.Format(message, args)));
			}
		}

		public void Trace(string message, params object[] args)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)Level <= 1)
			{
				<source>P.LogDebug((object)("[DiscordRPC:Trace] " + string.Format(message, args)));
			}
		}

		public void Warning(string message, params object[] args)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)Level <= 3)
			{
				<source>P.LogWarning((object)("[DiscordRPC:Warning] " + string.Format(message, args)));
			}
		}
	}
	public class Display
	{
		public enum DisplayPresets
		{
			Custom,
			Default,
			Detailed,
			DetailedPercentages,
			Pon,
			Emojis
		}

		public enum Texts
		{
			PlayerAlive,
			PlayerDead,
			MainMenu,
			CharacterCreation,
			CharacterCreationDetails,
			Exploring,
			Idle,
			FightingInArena,
			FightingBoss,
			DungeonBossEnd,
			Singleplayer,
			Multiplayer,
			RaceUnknown,
			RaceImp,
			RacePoon,
			RaceKubold,
			RaceByrdle,
			RaceChang,
			ClassUnknown,
			ClassNovice,
			ClassFighter,
			ClassMystic,
			ClassBandit,
			ClassTierBerserker,
			ClassTierPaladin,
			ClassTierMagus,
			ClassTierBishop,
			ClassTierRogue,
			ClassTierEngineer
		}

		private readonly Dictionary<Texts, ConfigEntry<string>> _customPresetData = new Dictionary<Texts, ConfigEntry<string>>();

		public ConfigEntry<DisplayPresets> DisplayPreset { get; }

		public Display(ConfigFile config)
		{
			ConfigFile config2 = config;
			base..ctor();
			Display display = this;
			DisplayPreset = config2.Bind<DisplayPresets>("General", "DisplayPreset", DisplayPresets.Custom, "Preset to use for texts. \"Custom\" will use the custom texts defined in the config.");
			RegisterCustomPresetText(Texts.PlayerAlive, "Text to display for player stats while alive.");
			RegisterCustomPresetText(Texts.PlayerDead, "Text to display for player stats while dead.");
			RegisterCustomPresetText(Texts.MainMenu, "Text to display while you're in the main menu.");
			RegisterCustomPresetText(Texts.CharacterCreation, "Text to display while you're in the character creation screen.");
			RegisterCustomPresetText(Texts.CharacterCreationDetails, "Text to display about the current character you're creating in the creation screen.");
			RegisterCustomPresetText(Texts.Exploring, "Text to display while exploring the world.");
			RegisterCustomPresetText(Texts.Idle, "Text to display while being idle in the world.");
			RegisterCustomPresetText(Texts.FightingInArena, "Text to display while an arena is active.");
			RegisterCustomPresetText(Texts.FightingBoss, "Text to display while a boss is active.");
			RegisterCustomPresetText(Texts.DungeonBossEnd, "Text to display during the post-boss state of a dungeon.");
			RegisterCustomPresetText(Texts.Singleplayer, "Text to display while in singleplayer.");
			RegisterCustomPresetText(Texts.Multiplayer, "Text to display while in multiplayer.");
			RegisterCustomPresetText(Texts.RaceImp, "Text to use when displaying PLAYERRACE (for Imps).");
			RegisterCustomPresetText(Texts.RacePoon, "Text to use when displaying PLAYERRACE (for Poons).");
			RegisterCustomPresetText(Texts.RaceKubold, "Text to use when displaying PLAYERRACE (for Kubolds).");
			RegisterCustomPresetText(Texts.RaceByrdle, "Text to use when displaying PLAYERRACE (for Byrdles).");
			RegisterCustomPresetText(Texts.RaceChang, "Text to use when displaying PLAYERRACE (for Changs).");
			RegisterCustomPresetText(Texts.ClassNovice, "Text to use when displaying PLAYERCLASS (for Novices).");
			RegisterCustomPresetText(Texts.ClassFighter, "Text to use when displaying PLAYERCLASS (for Fighters).");
			RegisterCustomPresetText(Texts.ClassMystic, "Text to use when displaying PLAYERCLASS (for Mystics).");
			RegisterCustomPresetText(Texts.ClassBandit, "Text to use when displaying PLAYERCLASS (for Bandits).");
			RegisterCustomPresetText(Texts.ClassTierBerserker, "Text to use when displaying PLAYERCLASS (for Berserkers - Fighter tier).");
			RegisterCustomPresetText(Texts.ClassTierPaladin, "Text to use when displaying PLAYERCLASS (for Paladins - Fighter tier).");
			RegisterCustomPresetText(Texts.ClassTierMagus, "Text to use when displaying PLAYERCLASS (for Magi - Mystic tier).");
			RegisterCustomPresetText(Texts.ClassTierBishop, "Text to use when displaying PLAYERCLASS (for Bishops - Mystic tier).");
			RegisterCustomPresetText(Texts.ClassTierRogue, "Text to use when displaying PLAYERCLASS (for Rogues - Bandit tier).");
			RegisterCustomPresetText(Texts.ClassTierEngineer, "Text to use when displaying PLAYERCLASS (for Engineers - Bandit tier).");
			void RegisterCustomPresetText(Texts text, string description)
			{
				_customPresetData[text] = config2.Bind<string>("Display", text.ToString(), GetDefaultPresetText(text), description);
			}
		}

		private static string EscapeVars(string input)
		{
			return input.Replace("@", "@0").Replace("{", "@1").Replace("}", "@2");
		}

		private static string EscapeText(string input)
		{
			return input.Replace("@", "@0");
		}

		private static string Unescape(string input)
		{
			return input.Replace("@2", "}").Replace("@1", "{").Replace("@0", "@");
		}

		public string ReplaceVars(string input, GameState state)
		{
			input = EscapeText(input);
			foreach (KeyValuePair<string, Func<string>> state2 in state.GetStates())
			{
				state2.Deconstruct(out var key, out var value);
				string text = key;
				Func<string> func = value;
				input = input.Replace("{" + text + "}", EscapeVars(GetVariable(text, func())));
			}
			input = Unescape(input);
			return input;
		}

		public string GetText(Texts text, GameState state)
		{
			return ReplaceVars(GetRawText(text), state);
		}

		private string GetVariable(string variable, string value)
		{
			if (1 == 0)
			{
			}
			string result = variable switch
			{
				"PLAYERCLASS" => GetMappedText(value), 
				"PLAYERRACE" => GetMappedText(value), 
				"CHARCREATERACE" => GetMappedText(value), 
				"PLAYERRACEANDCLASS" => string.Join(" ", value.Split(" ").Select(GetMappedText)), 
				_ => value, 
			};
			if (1 == 0)
			{
			}
			return result;
		}

		private string GetMappedText(string str)
		{
			string text = str.ToLower();
			if (1 == 0)
			{
			}
			string result = text switch
			{
				"imp" => GetRawText(Texts.RaceImp), 
				"poon" => GetRawText(Texts.RacePoon), 
				"kubold" => GetRawText(Texts.RaceKubold), 
				"byrdle" => GetRawText(Texts.RaceByrdle), 
				"chang" => GetRawText(Texts.RaceChang), 
				"novice" => GetRawText(Texts.ClassNovice), 
				"fighter" => GetRawText(Texts.ClassFighter), 
				"mystic" => GetRawText(Texts.ClassMystic), 
				"bandit" => GetRawText(Texts.ClassBandit), 
				"berserker" => GetRawText(Texts.ClassTierBerserker), 
				"paladin" => GetRawText(Texts.ClassTierPaladin), 
				"magus" => GetRawText(Texts.ClassTierMagus), 
				"bishop" => GetRawText(Texts.ClassTierBishop), 
				"rogue" => GetRawText(Texts.ClassTierRogue), 
				"engineer" => GetRawText(Texts.ClassTierEngineer), 
				_ => str, 
			};
			if (1 == 0)
			{
			}
			return result;
		}

		private string GetRawText(Texts text)
		{
			DisplayPresets value = DisplayPreset.Value;
			if (1 == 0)
			{
			}
			string result = value switch
			{
				DisplayPresets.Custom => GetCustomPresetText(text), 
				DisplayPresets.Default => GetDefaultPresetText(text), 
				DisplayPresets.Detailed => GetDetailedPresetText(text), 
				DisplayPresets.DetailedPercentages => GetDetailedPercentagesPresetText(text), 
				DisplayPresets.Pon => GetPonPresetText(text), 
				DisplayPresets.Emojis => GetEmojisPresetText(text), 
				_ => "[Unknown Preset]", 
			};
			if (1 == 0)
			{
			}
			return result;
		}

		private string GetCustomPresetText(Texts text)
		{
			if (_customPresetData.TryGetValue(text, out ConfigEntry<string> value))
			{
				return value.Value;
			}
			return GetDefaultPresetText(text);
		}

		private string GetDefaultPresetText(Texts text)
		{
			if (1 == 0)
			{
			}
			string result = text switch
			{
				Texts.PlayerAlive => "Lv{LVL} {PLAYERRACEANDCLASS} ({HP}/{MAXHP} HP)", 
				Texts.PlayerDead => "Lv{LVL} {PLAYERRACEANDCLASS} (Fainted)", 
				Texts.MainMenu => "In Main Menu", 
				Texts.CharacterCreation => "In Character Creation", 
				Texts.CharacterCreationDetails => "Creating {CHARCREATERACE} named \"{CHARCREATENAME}\"", 
				Texts.Exploring => "{PLAYERNAME} exploring {WORLDAREA}", 
				Texts.Idle => "{PLAYERNAME} idle in {WORLDAREA}", 
				Texts.FightingInArena => "{PLAYERNAME} fighting in {WORLDAREA}", 
				Texts.FightingBoss => "{PLAYERNAME} fighting {BOSSNAME} in {WORLDAREA}", 
				Texts.DungeonBossEnd => "{PLAYERNAME} getting boss loot in {WORLDAREA}", 
				Texts.Singleplayer => "Singleplayer", 
				Texts.Multiplayer => "Multiplayer on {SERVERNAME} ({PLAYERS}/{MAXPLAYERS})", 
				Texts.RaceUnknown => "[Unknown Race]", 
				Texts.RaceImp => "Imp", 
				Texts.RacePoon => "Poon", 
				Texts.RaceKubold => "Kubold", 
				Texts.RaceByrdle => "Byrdle", 
				Texts.RaceChang => "Chang", 
				Texts.ClassUnknown => "[Unknown Class]", 
				Texts.ClassNovice => "Novice", 
				Texts.ClassFighter => "Fighter", 
				Texts.ClassMystic => "Mystic", 
				Texts.ClassBandit => "Bandit", 
				Texts.ClassTierBerserker => "Berserker", 
				Texts.ClassTierPaladin => "Paladin", 
				Texts.ClassTierMagus => "Magus", 
				Texts.ClassTierBishop => "Bishop", 
				Texts.ClassTierRogue => "Rogue", 
				Texts.ClassTierEngineer => "Engineer", 
				_ => "[No Text]", 
			};
			if (1 == 0)
			{
			}
			return result;
		}

		private string GetDetailedPresetText(Texts text)
		{
			if (1 == 0)
			{
			}
			string result = text switch
			{
				Texts.PlayerAlive => "Lv{LVL} {PLAYERRACEANDCLASS} ({EXP}/{EXPNEXT} EXP) ({HP}/{MAXHP} HP) ({MP}/{MAXMP} MP)", 
				Texts.PlayerDead => "Lv{LVL} {PLAYERRACEANDCLASS} (Fainted) in {WORLDAREA}", 
				_ => GetDefaultPresetText(text), 
			};
			if (1 == 0)
			{
			}
			return result;
		}

		private string GetDetailedPercentagesPresetText(Texts text)
		{
			if (1 == 0)
			{
			}
			string result = text switch
			{
				Texts.PlayerAlive => "Lv{LVL} {PLAYERRACEANDCLASS} ({EXPPCT}%) ({HPPCT}%) ({MPPCT}%)", 
				Texts.PlayerDead => "Lv{LVL} {PLAYERRACEANDCLASS} (Fainted) in {WORLDAREA}", 
				_ => GetDefaultPresetText(text), 
			};
			if (1 == 0)
			{
			}
			return result;
		}

		private string GetPonPresetText(Texts text)
		{
			if (1 == 0)
			{
			}
			string result = text switch
			{
				Texts.RaceImp => "Inp", 
				Texts.RacePoon => "Pon", 
				Texts.RaceKubold => "Cubol", 
				Texts.RaceByrdle => "Birb", 
				Texts.RaceChang => "Tang", 
				_ => GetDefaultPresetText(text), 
			};
			if (1 == 0)
			{
			}
			return result;
		}

		private string GetEmojisPresetText(Texts text)
		{
			if (1 == 0)
			{
			}
			string result = text switch
			{
				Texts.PlayerAlive => "{PLAYERRACE}{PLAYERCLASS} \ud83c\udfc6{LVL} ❤\ufe0f{HP} ✨{MP}⚡{SP}", 
				Texts.PlayerDead => "{PLAYERRACE}{PLAYERCLASS} \ud83c\udfc6{LVL} \ud83d\udc80", 
				Texts.MainMenu => "\ud83d\udcd6 Main Menu", 
				Texts.CharacterCreation => "\ud83d\udcd6 Character Creation", 
				Texts.CharacterCreationDetails => "\ud83d\udcd6 Creating {CHARCREATERACE} \"{CHARCREATENAME}\"", 
				Texts.Exploring => "{PLAYERNAME} \ud83c\udf0e{WORLDAREA}", 
				Texts.Idle => "{PLAYERNAME} \ud83c\udf0e{WORLDAREA} \ud83d\udca4", 
				Texts.FightingInArena => "{PLAYERNAME} \ud83c\udf0e{WORLDAREA} ⚔\ufe0f", 
				Texts.FightingBoss => "{PLAYERNAME} \ud83c\udf0e{WORLDAREA} ⚔\ufe0f\ud83d\udc7f {BOSSNAME}", 
				Texts.DungeonBossEnd => "{PLAYERNAME} \ud83c\udf0e{WORLDAREA} ⚔\ufe0f\ud83d\udc7f\ud83d\udc51", 
				Texts.Singleplayer => "\ud83d\udc64Solo", 
				Texts.Multiplayer => "\ud83d\udc65{SERVERNAME} ({PLAYERS}/{MAXPLAYERS})", 
				Texts.RaceUnknown => GetDefaultPresetText(text), 
				Texts.RaceImp => "\ud83d\udc7f", 
				Texts.RacePoon => "\ud83d\udc30", 
				Texts.RaceKubold => "\ud83d\udc32", 
				Texts.RaceByrdle => "\ud83d\udc26", 
				Texts.RaceChang => "\ud83d\udc3f\ufe0f", 
				Texts.ClassUnknown => GetDefaultPresetText(text), 
				Texts.ClassNovice => "\ud83c\udf3f", 
				Texts.ClassFighter => "\ud83e\ude93", 
				Texts.ClassMystic => "\ud83c\udf00", 
				Texts.ClassBandit => "\ud83d\udc51", 
				Texts.ClassTierBerserker => "\ud83d\udc17", 
				Texts.ClassTierPaladin => "\ud83d\udee1\ufe0f", 
				Texts.ClassTierMagus => "\ud83e\ude84", 
				Texts.ClassTierBishop => "♗", 
				Texts.ClassTierRogue => "\ud83e\udd77", 
				Texts.ClassTierEngineer => "\ud83d\udd27", 
				_ => GetDefaultPresetText(text), 
			};
			if (1 == 0)
			{
			}
			return result;
		}
	}
	public class GameState
	{
		private readonly Dictionary<string, Func<string>> _keys;

		public int Health { get; set; }

		public int Mana { get; set; }

		public int Stamina { get; set; }

		public int MaxHealth { get; set; }

		public int MaxMana { get; set; }

		public int MaxStamina { get; set; }

		public int HealthPercentage => (MaxHealth != 0) ? (Health * 100 / MaxHealth) : 0;

		public int ManaPercentage => (MaxMana != 0) ? (Mana * 100 / MaxMana) : 0;

		public int StaminaPercentage => (MaxStamina != 0) ? (Stamina * 100 / MaxStamina) : 0;

		public int Level { get; set; }

		public int Experience { get; set; }

		public int ExperienceForNextLevel { get; set; }

		public int ExperiencePercentage => (ExperienceForNextLevel != 0) ? (Experience * 100 / ExperienceForNextLevel) : 0;

		public string PlayerName { get; set; } = "";


		public string PlayerRace { get; set; } = "";


		public string PlayerClass { get; set; } = "";


		public string WorldArea { get; set; } = "";


		public string BossName { get; set; } = "";


		public Vector3 Position { get; set; }

		public Vector3 LastSignificantPosition { get; set; }

		public DateTime LastSignificantPositionUpdate { get; set; } = DateTime.Now;


		public bool IsIdle => DateTime.Now - LastSignificantPositionUpdate > TimeSpan.FromSeconds(10.0);

		public string ServerName { get; set; } = "";


		public string CharacterCreationName { get; set; } = "";


		public string CharacterCreationRace { get; set; } = "";


		public bool InArenaCombat { get; set; }

		public bool InBossCombat { get; set; }

		public bool InPostBoss { get; set; }

		public ZoneType WorldAreaType { get; set; } = (ZoneType)0;


		public bool InMultiplayer { get; set; }

		public int Players { get; set; }

		public int MaxPlayers { get; set; }

		public string ServerJoinId { get; set; } = "";


		public IEnumerable<KeyValuePair<string, Func<string>>> GetStates()
		{
			return _keys.AsEnumerable();
		}

		public GameState()
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			_keys = new Dictionary<string, Func<string>>
			{
				["HP"] = () => $"{Health}",
				["MAXHP"] = () => $"{MaxHealth}",
				["HPPCT"] = () => $"{HealthPercentage}",
				["MP"] = () => $"{Mana}",
				["MAXMP"] = () => $"{MaxMana}",
				["MPPCT"] = () => $"{ManaPercentage}",
				["SP"] = () => $"{Stamina}",
				["MAXSP"] = () => $"{MaxStamina}",
				["SPPCT"] = () => $"{StaminaPercentage}",
				["LVL"] = () => $"{Level}",
				["EXP"] = () => $"{Experience}",
				["EXPNEXT"] = () => $"{ExperienceForNextLevel}",
				["EXPPCT"] = () => $"{ExperiencePercentage}",
				["PLAYERNAME"] = () => PlayerName ?? "",
				["PLAYERRACE"] = () => PlayerRace ?? "",
				["PLAYERCLASS"] = () => PlayerClass ?? "",
				["PLAYERRACEANDCLASS"] = () => (PlayerRace + " " + PlayerClass).Trim(),
				["WORLDAREA"] = () => WorldArea ?? "",
				["BOSSNAME"] = () => BossName ?? "",
				["SERVERNAME"] = () => ServerName ?? "",
				["PLAYERS"] = () => $"{Players}",
				["MAXPLAYERS"] = () => $"{MaxPlayers}",
				["CHARCREATENAME"] = () => CharacterCreationName ?? "",
				["CHARCREATERACE"] = () => CharacterCreationRace ?? ""
			};
		}

		public void UpdateData(MapInstance area)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			WorldArea = area._mapName;
			WorldAreaType = area._zoneType;
		}

		public void UpdateData(Player player)
		{
			//IL_0053: 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_008b: 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_0119: 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_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player == (Object)null)
			{
				return;
			}
			Health = player._statusEntity.Network_currentHealth;
			Mana = player._statusEntity.Network_currentMana;
			Stamina = player._statusEntity.Network_currentStamina;
			MaxHealth = player._statusEntity._pStats.Network_statStruct._maxHealth;
			MaxMana = player._statusEntity._pStats.Network_statStruct._maxMana;
			MaxStamina = player._statusEntity._pStats.Network_statStruct._maxStamina;
			Level = player._statusEntity._pStats.Network_currentLevel;
			Experience = player._statusEntity._pStats.Network_currentExp;
			ExperienceForNextLevel = player._statusEntity._pStats.Network_statStruct._experience;
			PlayerName = player.Network_nickname;
			PlayerRace = player._pVisual._playerAppearanceStruct._setRaceTag ?? "";
			Position = ((Component)player).transform.position;
			if (Vector3.Distance(Position, LastSignificantPosition) > 5f)
			{
				LastSignificantPosition = Position;
				LastSignificantPositionUpdate = DateTime.Now;
			}
			if (Object.op_Implicit((Object)(object)player._pStats._class))
			{
				int network_syncClassTier = player._pStats.Network_syncClassTier;
				if (network_syncClassTier > 0)
				{
					if (network_syncClassTier <= player._pStats._class._playerClassTiers.Length)
					{
						PlayerClass = player._pStats._class._playerClassTiers[network_syncClassTier - 1]._classTierName ?? "";
					}
					else
					{
						PlayerClass = "";
					}
				}
				else
				{
					PlayerClass = player._pStats._class._className ?? "";
				}
			}
			else
			{
				PlayerClass = GameManager._current._statLogics._emptyClassName ?? "";
			}
		}
	}
	internal static class Logging
	{
		private static ManualLogSource InternalLogger => AtlyssDiscordRichPresence.Plugin.Logger;

		public static void LogFatal(object data, ConfigEntry<bool>? toggle = null)
		{
			Log(data, (LogLevel)1, toggle);
		}

		public static void LogError(object data, ConfigEntry<bool>? toggle = null)
		{
			Log(data, (LogLevel)2, toggle);
		}

		public static void LogWarning(object data, ConfigEntry<bool>? toggle = null)
		{
			Log(data, (LogLevel)4, toggle);
		}

		public static void LogMessage(object data, ConfigEntry<bool>? toggle = null)
		{
			Log(data, (LogLevel)8, toggle);
		}

		public static void LogInfo(object data, ConfigEntry<bool>? toggle = null)
		{
			Log(data, (LogLevel)16, toggle);
		}

		public static void LogDebug(object data, ConfigEntry<bool>? toggle = null)
		{
			Log(data, (LogLevel)32, toggle);
		}

		private static void Log(object data, LogLevel level = 16, ConfigEntry<bool>? toggle = null)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			if (toggle == null || toggle.Value)
			{
				ManualLogSource internalLogger = InternalLogger;
				if (internalLogger != null)
				{
					internalLogger.Log(level, data);
				}
			}
		}
	}
	public class RichPresenceWrapper : IDisposable
	{
		public enum LogLevels
		{
			Trace,
			Info,
			Warning,
			Error,
			None
		}

		public struct JoinData
		{
			public string Id;
		}

		private const string AtlyssSteamAppId = "2768430";

		private readonly DiscordRpcClient _client;

		private readonly DiscordLogSourceLogger _logger;

		private readonly RichPresence _presence = new RichPresence
		{
			Assets = new Assets(),
			Party = new Party(),
			Timestamps = new Timestamps(),
			Secrets = new Secrets()
		};

		private DateTime _lastUpdate;

		private PresenceData _presenceData;

		private bool _shouldSendPresence = false;

		private bool _enabled;

		public TimeSpan RateLimit { get; set; } = TimeSpan.FromSeconds(3.0);


		public bool Enabled
		{
			get
			{
				return _enabled;
			}
			set
			{
				if (_enabled != value)
				{
					Logging.LogInfo("Presence sending is now " + (value ? "enabled" : "disabled") + ".");
				}
				_enabled = value;
				_shouldSendPresence = true;
			}
		}

		public LogLevels LogLevel
		{
			get
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000b: 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_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Expected I4, but got Unknown
				//IL_002a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Invalid comparison between Unknown and I4
				LogLevel level = _logger.Level;
				if (1 == 0)
				{
				}
				LogLevels result = (level - 1) switch
				{
					0 => LogLevels.Trace, 
					1 => LogLevels.Info, 
					2 => LogLevels.Warning, 
					3 => LogLevels.Error, 
					_ => ((int)level != 256) ? LogLevels.Info : LogLevels.None, 
				};
				if (1 == 0)
				{
				}
				return result;
			}
			set
			{
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: 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)
				//IL_0036: 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_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_0042: Unknown result type (might be due to invalid IL or missing references)
				//IL_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_0077: Unknown result type (might be due to invalid IL or missing references)
				//IL_005e: Unknown result type (might be due to invalid IL or missing references)
				if (1 == 0)
				{
				}
				LogLevel val = (LogLevel)(value switch
				{
					LogLevels.Trace => 1, 
					LogLevels.Info => 2, 
					LogLevels.Warning => 3, 
					LogLevels.Error => 4, 
					LogLevels.None => 256, 
					_ => 2, 
				});
				if (1 == 0)
				{
				}
				LogLevel val2 = val;
				if (_logger.Level != val2)
				{
					Logging.LogInfo($"DiscordRPC log level has been set to {val2}.");
				}
				_logger.Level = val2;
			}
		}

		public event EventHandler<JoinData>? OnAskToJoin;

		public event EventHandler<JoinData>? OnJoin;

		public RichPresenceWrapper(string discordAppId, ManualLogSource logSource, LogLevels logLevel)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			//IL_0012: 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)
			//IL_001d: Expected O, but got Unknown
			//IL_001e: 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_002a: 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)
			//IL_0035: Expected O, but got Unknown
			//IL_003b: Expected O, but got Unknown
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Expected O, but got Unknown
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected O, but got Unknown
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Expected O, but got Unknown
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Expected O, but got Unknown
			_logger = new DiscordLogSourceLogger(logSource, (LogLevel)256);
			LogLevel = logLevel;
			_lastUpdate = DateTime.UtcNow;
			_client = new DiscordRpcClient(discordAppId, -1, (ILogger)(object)_logger, true, (INamedPipeClient)null);
			_client.OnReady += (OnReadyEvent)delegate(object sender, ReadyMessage e)
			{
				_logger.Info("DiscordRpcClient initialized for user " + e.User.Username + ".");
				_lastUpdate = DateTime.UtcNow;
				((BaseRichPresence)_presence).Timestamps.Start = DateTime.UtcNow;
				SetPresence(_presenceData);
			};
			_client.OnClose += (OnCloseEvent)delegate
			{
				_logger.Info("DiscordRpcClient deinitialized.");
			};
			_client.OnJoin += (OnJoinEvent)delegate(object sender, JoinMessage e)
			{
				_logger.Info("Got a join event.");
				this.OnJoin?.Invoke(sender, new JoinData
				{
					Id = e.Secret
				});
			};
			_client.OnJoinRequested += (OnJoinRequestedEvent)delegate
			{
				_logger.Info("Got a join request event.");
			};
			RegisterGameLaunchURI();
			_client.SetSubscription((EventType)6);
			_client.Initialize();
		}

		private void RegisterGameLaunchURI()
		{
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Expected O, but got Unknown
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Expected O, but got Unknown
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected O, but got Unknown
			string text = Path.Combine(Paths.BepInExAssemblyDirectory, "BepInEx.Preloader.dll");
			if (WineDetect.IsRunningInWine && WineDetect.SystemName == "Linux")
			{
				Logging.LogInfo("Setting up Discord launch options (Linux w/Proton).");
				string environmentVariable = Environment.GetEnvironmentVariable("STEAM_BASE_FOLDER");
				if (string.IsNullOrEmpty(environmentVariable))
				{
					Logging.LogWarning("Couldn't find Steam install, won't register launch parameters.");
					return;
				}
				string text2 = Path.Combine(environmentVariable, "steam.sh");
				ProtonUnixUriSchemeCreator protonUnixUriSchemeCreator = new ProtonUnixUriSchemeCreator((ILogger)(object)_logger);
				string text3 = text2 + " -applaunch 2768430 --doorstop-enable true --doorstop-target \"" + text + "\"";
				UriSchemeRegister register = new UriSchemeRegister((ILogger)(object)_logger, _client.ApplicationID, (string)null, text3);
				_client.HasRegisteredUriScheme = protonUnixUriSchemeCreator.RegisterUriScheme(register);
			}
			else
			{
				Logging.LogInfo("Setting up Discord launch options (Windows).");
				WindowsUriSchemeCreator val = new WindowsUriSchemeCreator((ILogger)(object)_logger);
				string text4 = "\"" + Paths.ExecutablePath + "\" -applaunch 2768430 --doorstop-enable true --doorstop-target \"" + text + "\"";
				UriSchemeRegister val2 = new UriSchemeRegister((ILogger)(object)_logger, _client.ApplicationID, (string)null, text4);
				_client.HasRegisteredUriScheme = val.RegisterUriScheme(val2);
			}
		}

		public void SetPresence(PresenceData data, bool resetTimer = false)
		{
			((BaseRichPresence)_presence).State = data.State;
			((BaseRichPresence)_presence).Details = data.Details;
			((BaseRichPresence)_presence).Assets.LargeImageKey = data.LargeImageKey;
			((BaseRichPresence)_presence).Assets.LargeImageText = data.LargeImageText;
			((BaseRichPresence)_presence).Assets.SmallImageKey = data.SmallImageKey;
			((BaseRichPresence)_presence).Assets.SmallImageText = data.SmallImageText;
			if (resetTimer)
			{
				((BaseRichPresence)_presence).Timestamps.Start = DateTime.UtcNow;
			}
			if (data.Multiplayer.HasValue)
			{
				string id = data.Multiplayer.Value.Id;
				using SHA256 sHA = SHA256.Create();
				string text = BitConverter.ToString(sHA.ComputeHash(Encoding.UTF32.GetBytes(id))).Replace("-", "");
				((BaseRichPresence)_presence).Party.ID = "party_" + text;
				((BaseRichPresence)_presence).Party.Size = data.Multiplayer.Value.Size;
				((BaseRichPresence)_presence).Party.Max = data.Multiplayer.Value.Max;
				((BaseRichPresence)_presence).Party.Privacy = (PrivacySetting)1;
				((BaseRichPresence)_presence).Secrets.JoinSecret = (data.Multiplayer.Value.AllowJoining ? ("secret_" + id) : "");
			}
			else
			{
				((BaseRichPresence)_presence).Party.ID = "";
				((BaseRichPresence)_presence).Secrets.JoinSecret = "";
			}
			_presenceData = data;
			_shouldSendPresence = true;
		}

		public void Tick()
		{
			if (_shouldSendPresence && _lastUpdate + RateLimit <= DateTime.UtcNow)
			{
				_lastUpdate = DateTime.UtcNow;
				_shouldSendPresence = false;
				_client.SetPresence(Enabled ? _presence : null);
			}
		}

		public void Dispose()
		{
			_client.Dispose();
		}
	}
	public static class States
	{
		public const string HP = "HP";

		public const string MAXHP = "MAXHP";

		public const string HPPCT = "HPPCT";

		public const string MP = "MP";

		public const string MAXMP = "MAXMP";

		public const string MPPCT = "MPPCT";

		public const string SP = "SP";

		public const string MAXSP = "MAXSP";

		public const string SPPCT = "SPPCT";

		public const string LVL = "LVL";

		public const string EXP = "EXP";

		public const string EXPNEXT = "EXPNEXT";

		public const string EXPPCT = "EXPPCT";

		public const string PLAYERNAME = "PLAYERNAME";

		public const string PLAYERRACE = "PLAYERRACE";

		public const string PLAYERCLASS = "PLAYERCLASS";

		public const string PLAYERRACEANDCLASS = "PLAYERRACEANDCLASS";

		public const string WORLDAREA = "WORLDAREA";

		public const string BOSSNAME = "BOSSNAME";

		public const string SERVERNAME = "SERVERNAME";

		public const string PLAYERS = "PLAYERS";

		public const string MAXPLAYERS = "MAXPLAYERS";

		public const string CHARCREATENAME = "CHARCREATENAME";

		public const string CHARCREATERACE = "CHARCREATERACE";
	}
	public static class WineDetect
	{
		[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private delegate IntPtr WineGetVersion();

		[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private delegate void WineGetHostVersion(out string sysName, out string version);

		private static bool _checkDone = false;

		private static bool _isRunningInWine = false;

		private static string _systemName = "";

		private static string _systemVersion = "";

		private static string _wineVersion = "";

		public static bool IsRunningInWine
		{
			get
			{
				Check();
				return _isRunningInWine;
			}
		}

		public static string SystemName
		{
			get
			{
				Check();
				return _systemName;
			}
		}

		public static string SystemVersion
		{
			get
			{
				Check();
				return _systemVersion;
			}
		}

		public static string WineVersion
		{
			get
			{
				Check();
				return _wineVersion;
			}
		}

		[DllImport("Kernel32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
		public static extern IntPtr GetModuleHandleA(string moduleName);

		[DllImport("Kernel32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
		public static extern IntPtr GetProcAddress(IntPtr module, string procName);

		public static void Check()
		{
			if (_checkDone)
			{
				return;
			}
			_checkDone = true;
			IntPtr moduleHandleA = GetModuleHandleA("ntdll.dll");
			if (!(moduleHandleA == IntPtr.Zero))
			{
				IntPtr procAddress = GetProcAddress(moduleHandleA, "wine_get_version");
				IntPtr procAddress2 = GetProcAddress(moduleHandleA, "wine_get_host_version");
				if (!(procAddress == IntPtr.Zero) && !(procAddress2 == IntPtr.Zero))
				{
					IntPtr ptr = Marshal.GetDelegateForFunctionPointer<WineGetVersion>(procAddress)();
					string wineVersion = Marshal.PtrToStringAnsi(ptr);
					Marshal.GetDelegateForFunctionPointer<WineGetHostVersion>(procAddress2)(out var sysName, out var version);
					_isRunningInWine = true;
					_systemName = sysName;
					_systemVersion = version;
					_wineVersion = wineVersion;
				}
			}
		}
	}
	internal static class ModInfo
	{
		public const string GUID = "Marioalexsan.AtlyssDiscordRichPresence";

		public const string NAME = "AtlyssDiscordRichPresence";

		public const string VERSION = "1.4.0";
	}
}
namespace Marioalexsan.AtlyssDiscordRichPresence.SoftDependencies
{
	public static class EasySettings
	{
		private const MethodImplOptions SoftDepend = MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization;

		public const string ModID = "EasySettings";

		public static readonly Version ExpectedVersion = new Version("1.1.8");

		private static BaseUnityPlugin? _plugin;

		private static bool _initialized;

		public static bool IsAvailable
		{
			get
			{
				if (!_initialized)
				{
					_plugin = (Chainloader.PluginInfos.TryGetValue("EasySettings", out var value) ? value.Instance : null);
					_initialized = true;
					if ((Object)(object)_plugin == (Object)null)
					{
						Logging.LogWarning("Soft dependency EasySettings was not found.");
					}
					else if (_plugin.Info.Metadata.Version != ExpectedVersion)
					{
						Logging.LogWarning(string.Format("Soft dependency {0} has a different version than expected (have: {1}, expect: {2}).", "EasySettings", _plugin.Info.Metadata.Version, ExpectedVersion));
					}
				}
				return (Object)(object)_plugin != (Object)null;
			}
		}

		public static UnityEvent OnInitialized
		{
			[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
			get
			{
				return Settings.OnInitialized;
			}
		}

		public static UnityEvent OnCancelSettings
		{
			[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
			get
			{
				return Settings.OnCancelSettings;
			}
		}

		public static UnityEvent OnApplySettings
		{
			[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
			get
			{
				return Settings.OnApplySettings;
			}
		}

		public static UnityEvent OnCloseSettings
		{
			[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
			get
			{
				return Settings.OnCloseSettings;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static GameObject AddSpace()
		{
			return ((Component)((BaseAtlyssElement)Settings.ModTab.AddSpace()).Root).gameObject;
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static GameObject AddHeader(string label)
		{
			return ((Component)((BaseAtlyssElement)Settings.ModTab.AddHeader(label)).Root).gameObject;
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static GameObject AddButton(string buttonLabel, UnityAction onClick)
		{
			return ((Component)((BaseAtlyssElement)Settings.ModTab.AddButton(buttonLabel, onClick)).Root).gameObject;
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static GameObject AddToggle(string label, ConfigEntry<bool> config)
		{
			return ((Component)((BaseAtlyssElement)Settings.ModTab.AddToggle(label, config)).Root).gameObject;
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static GameObject AddSlider(string label, ConfigEntry<float> config, bool wholeNumbers = false)
		{
			return ((Component)((BaseAtlyssElement)Settings.ModTab.AddSlider(label, config, wholeNumbers)).Root).gameObject;
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static GameObject AddAdvancedSlider(string label, ConfigEntry<float> config, bool wholeNumbers = false)
		{
			return ((Component)((BaseAtlyssElement)Settings.ModTab.AddAdvancedSlider(label, config, wholeNumbers)).Root).gameObject;
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static GameObject AddDropdown<T>(string label, ConfigEntry<T> config) where T : Enum
		{
			return ((Component)((BaseAtlyssElement)Settings.ModTab.AddDropdown<T>(label, config)).Root).gameObject;
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static GameObject AddKeyButton(string label, ConfigEntry<KeyCode> config)
		{
			return ((Component)((BaseAtlyssElement)Settings.ModTab.AddKeyButton(label, config)).Root).gameObject;
		}
	}
}
namespace Marioalexsan.AtlyssDiscordRichPresence.HarmonyPatches
{
	[HarmonyPatch]
	internal static class Creep_Handle_AggroedNetObj
	{
		private static MethodInfo TargetMethod()
		{
			return AccessTools.GetDeclaredMethods(typeof(Creep)).First((MethodInfo x) => x.Name.Contains("Handle_AggroedNetObj"));
		}

		private static void Prefix(Creep __instance)
		{
			if (Object.op_Implicit((Object)(object)__instance))
			{
				TrackedAggroCreeps.List.Add(__instance);
			}
		}
	}
	public static class TrackedAggroCreeps
	{
		public static List<Creep> List { get; } = new List<Creep>();

	}
	[HarmonyPatch(typeof(Player), "OnPlayerMapInstanceChange")]
	internal static class Player_OnPlayerMapInstanceChange
	{
		private static void Postfix(Player __instance, MapInstance _new)
		{
			AtlyssDiscordRichPresence.Plugin.Player_OnPlayerMapInstanceChange(__instance, _new);
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}

plugins/Microsoft.Win32.Registry.dll

Decompiled a day ago
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using FxResources.Microsoft.Win32.Registry;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyTitle("Microsoft.Win32.Registry")]
[assembly: AssemblyDescription("Microsoft.Win32.Registry")]
[assembly: AssemblyDefaultAlias("Microsoft.Win32.Registry")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: AssemblyCopyright("© Microsoft Corporation.  All rights reserved.")]
[assembly: AssemblyFileVersion("4.6.26515.06")]
[assembly: AssemblyInformationalVersion("4.6.26515.06 @BuiltBy: dlab-DDVSOWINAGE059 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/30ab651fcb4354552bd4891619a0bdd81e0ebdbf")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.1.1.0")]
[module: UnverifiableCode]
internal static class Interop
{
	internal class Advapi32
	{
		internal class RegistryOptions
		{
			internal const int REG_OPTION_NON_VOLATILE = 0;

			internal const int REG_OPTION_VOLATILE = 1;

			internal const int REG_OPTION_CREATE_LINK = 2;

			internal const int REG_OPTION_BACKUP_RESTORE = 4;
		}

		internal class RegistryView
		{
			internal const int KEY_WOW64_64KEY = 256;

			internal const int KEY_WOW64_32KEY = 512;
		}

		internal class RegistryOperations
		{
			internal const int KEY_QUERY_VALUE = 1;

			internal const int KEY_SET_VALUE = 2;

			internal const int KEY_CREATE_SUB_KEY = 4;

			internal const int KEY_ENUMERATE_SUB_KEYS = 8;

			internal const int KEY_NOTIFY = 16;

			internal const int KEY_CREATE_LINK = 32;

			internal const int KEY_READ = 131097;

			internal const int KEY_WRITE = 131078;

			internal const int SYNCHRONIZE = 1048576;

			internal const int READ_CONTROL = 131072;

			internal const int STANDARD_RIGHTS_READ = 131072;

			internal const int STANDARD_RIGHTS_WRITE = 131072;
		}

		internal class RegistryValues
		{
			internal const int REG_NONE = 0;

			internal const int REG_SZ = 1;

			internal const int REG_EXPAND_SZ = 2;

			internal const int REG_BINARY = 3;

			internal const int REG_DWORD = 4;

			internal const int REG_DWORD_LITTLE_ENDIAN = 4;

			internal const int REG_DWORD_BIG_ENDIAN = 5;

			internal const int REG_LINK = 6;

			internal const int REG_MULTI_SZ = 7;

			internal const int REG_QWORD = 11;
		}

		[DllImport("advapi32.dll")]
		internal static extern int RegCloseKey(IntPtr hKey);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegConnectRegistryW")]
		internal static extern int RegConnectRegistry(string machineName, SafeRegistryHandle key, out SafeRegistryHandle result);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegCreateKeyExW")]
		internal static extern int RegCreateKeyEx(SafeRegistryHandle hKey, string lpSubKey, int Reserved, string lpClass, int dwOptions, int samDesired, ref Kernel32.SECURITY_ATTRIBUTES secAttrs, out SafeRegistryHandle hkResult, out int lpdwDisposition);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegDeleteKeyExW")]
		internal static extern int RegDeleteKeyEx(SafeRegistryHandle hKey, string lpSubKey, int samDesired, int Reserved);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegDeleteValueW")]
		internal static extern int RegDeleteValue(SafeRegistryHandle hKey, string lpValueName);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegEnumKeyExW")]
		internal static extern int RegEnumKeyEx(SafeRegistryHandle hKey, int dwIndex, char[] lpName, ref int lpcbName, int[] lpReserved, [Out] StringBuilder lpClass, int[] lpcbClass, long[] lpftLastWriteTime);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegEnumValueW")]
		internal static extern int RegEnumValue(SafeRegistryHandle hKey, int dwIndex, char[] lpValueName, ref int lpcbValueName, IntPtr lpReserved_MustBeZero, int[] lpType, byte[] lpData, int[] lpcbData);

		[DllImport("advapi32.dll")]
		internal static extern int RegFlushKey(SafeRegistryHandle hKey);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegOpenKeyExW")]
		internal static extern int RegOpenKeyEx(SafeRegistryHandle hKey, string lpSubKey, int ulOptions, int samDesired, out SafeRegistryHandle hkResult);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegOpenKeyExW")]
		internal static extern int RegOpenKeyEx(IntPtr hKey, string lpSubKey, int ulOptions, int samDesired, out SafeRegistryHandle hkResult);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegQueryInfoKeyW")]
		internal static extern int RegQueryInfoKey(SafeRegistryHandle hKey, [Out] StringBuilder lpClass, int[] lpcbClass, IntPtr lpReserved_MustBeZero, ref int lpcSubKeys, int[] lpcbMaxSubKeyLen, int[] lpcbMaxClassLen, ref int lpcValues, int[] lpcbMaxValueNameLen, int[] lpcbMaxValueLen, int[] lpcbSecurityDescriptor, int[] lpftLastWriteTime);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW")]
		internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName, int[] lpReserved, ref int lpType, [Out] byte[] lpData, ref int lpcbData);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW")]
		internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName, int[] lpReserved, ref int lpType, ref int lpData, ref int lpcbData);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW")]
		internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName, int[] lpReserved, ref int lpType, ref long lpData, ref int lpcbData);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW")]
		internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName, int[] lpReserved, ref int lpType, [Out] char[] lpData, ref int lpcbData);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW")]
		internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName, int[] lpReserved, ref int lpType, [Out] StringBuilder lpData, ref int lpcbData);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegSetValueExW")]
		internal static extern int RegSetValueEx(SafeRegistryHandle hKey, string lpValueName, int Reserved, RegistryValueKind dwType, byte[] lpData, int cbData);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegSetValueExW")]
		internal static extern int RegSetValueEx(SafeRegistryHandle hKey, string lpValueName, int Reserved, RegistryValueKind dwType, char[] lpData, int cbData);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegSetValueExW")]
		internal static extern int RegSetValueEx(SafeRegistryHandle hKey, string lpValueName, int Reserved, RegistryValueKind dwType, ref int lpData, int cbData);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegSetValueExW")]
		internal static extern int RegSetValueEx(SafeRegistryHandle hKey, string lpValueName, int Reserved, RegistryValueKind dwType, ref long lpData, int cbData);

		[DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegSetValueExW")]
		internal static extern int RegSetValueEx(SafeRegistryHandle hKey, string lpValueName, int Reserved, RegistryValueKind dwType, string lpData, int cbData);
	}

	internal static class Libraries
	{
		internal const string Advapi32 = "advapi32.dll";

		internal const string BCrypt = "BCrypt.dll";

		internal const string CoreComm_L1_1_1 = "api-ms-win-core-comm-l1-1-1.dll";

		internal const string Crypt32 = "crypt32.dll";

		internal const string Error_L1 = "api-ms-win-core-winrt-error-l1-1-0.dll";

		internal const string HttpApi = "httpapi.dll";

		internal const string IpHlpApi = "iphlpapi.dll";

		internal const string Kernel32 = "kernel32.dll";

		internal const string Memory_L1_3 = "api-ms-win-core-memory-l1-1-3.dll";

		internal const string Mswsock = "mswsock.dll";

		internal const string NCrypt = "ncrypt.dll";

		internal const string NtDll = "ntdll.dll";

		internal const string Odbc32 = "odbc32.dll";

		internal const string OleAut32 = "oleaut32.dll";

		internal const string PerfCounter = "perfcounter.dll";

		internal const string RoBuffer = "api-ms-win-core-winrt-robuffer-l1-1-0.dll";

		internal const string Secur32 = "secur32.dll";

		internal const string Shell32 = "shell32.dll";

		internal const string SspiCli = "sspicli.dll";

		internal const string User32 = "user32.dll";

		internal const string Version = "version.dll";

		internal const string WebSocket = "websocket.dll";

		internal const string WinHttp = "winhttp.dll";

		internal const string Ws2_32 = "ws2_32.dll";

		internal const string Wtsapi32 = "wtsapi32.dll";

		internal const string CompressionNative = "clrcompression.dll";
	}

	internal class Errors
	{
		internal const int ERROR_SUCCESS = 0;

		internal const int ERROR_INVALID_FUNCTION = 1;

		internal const int ERROR_FILE_NOT_FOUND = 2;

		internal const int ERROR_PATH_NOT_FOUND = 3;

		internal const int ERROR_ACCESS_DENIED = 5;

		internal const int ERROR_INVALID_HANDLE = 6;

		internal const int ERROR_NOT_ENOUGH_MEMORY = 8;

		internal const int ERROR_INVALID_DATA = 13;

		internal const int ERROR_INVALID_DRIVE = 15;

		internal const int ERROR_NO_MORE_FILES = 18;

		internal const int ERROR_NOT_READY = 21;

		internal const int ERROR_BAD_COMMAND = 22;

		internal const int ERROR_BAD_LENGTH = 24;

		internal const int ERROR_SHARING_VIOLATION = 32;

		internal const int ERROR_LOCK_VIOLATION = 33;

		internal const int ERROR_HANDLE_EOF = 38;

		internal const int ERROR_FILE_EXISTS = 80;

		internal const int ERROR_INVALID_PARAMETER = 87;

		internal const int ERROR_BROKEN_PIPE = 109;

		internal const int ERROR_SEM_TIMEOUT = 121;

		internal const int ERROR_CALL_NOT_IMPLEMENTED = 120;

		internal const int ERROR_INSUFFICIENT_BUFFER = 122;

		internal const int ERROR_INVALID_NAME = 123;

		internal const int ERROR_NEGATIVE_SEEK = 131;

		internal const int ERROR_DIR_NOT_EMPTY = 145;

		internal const int ERROR_BAD_PATHNAME = 161;

		internal const int ERROR_LOCK_FAILED = 167;

		internal const int ERROR_BUSY = 170;

		internal const int ERROR_ALREADY_EXISTS = 183;

		internal const int ERROR_BAD_EXE_FORMAT = 193;

		internal const int ERROR_ENVVAR_NOT_FOUND = 203;

		internal const int ERROR_FILENAME_EXCED_RANGE = 206;

		internal const int ERROR_EXE_MACHINE_TYPE_MISMATCH = 216;

		internal const int ERROR_PIPE_BUSY = 231;

		internal const int ERROR_NO_DATA = 232;

		internal const int ERROR_PIPE_NOT_CONNECTED = 233;

		internal const int ERROR_MORE_DATA = 234;

		internal const int ERROR_NO_MORE_ITEMS = 259;

		internal const int ERROR_PARTIAL_COPY = 299;

		internal const int ERROR_ARITHMETIC_OVERFLOW = 534;

		internal const int ERROR_PIPE_CONNECTED = 535;

		internal const int ERROR_PIPE_LISTENING = 536;

		internal const int ERROR_OPERATION_ABORTED = 995;

		internal const int ERROR_IO_INCOMPLETE = 996;

		internal const int ERROR_IO_PENDING = 997;

		internal const int ERROR_NO_TOKEN = 1008;

		internal const int ERROR_DLL_INIT_FAILED = 1114;

		internal const int ERROR_COUNTER_TIMEOUT = 1121;

		internal const int ERROR_NO_ASSOCIATION = 1155;

		internal const int ERROR_DDE_FAIL = 1156;

		internal const int ERROR_DLL_NOT_FOUND = 1157;

		internal const int ERROR_NOT_FOUND = 1168;

		internal const int ERROR_NON_ACCOUNT_SID = 1257;

		internal const int ERROR_NOT_ALL_ASSIGNED = 1300;

		internal const int ERROR_UNKNOWN_REVISION = 1305;

		internal const int ERROR_INVALID_OWNER = 1307;

		internal const int ERROR_INVALID_PRIMARY_GROUP = 1308;

		internal const int ERROR_NO_SUCH_PRIVILEGE = 1313;

		internal const int ERROR_PRIVILEGE_NOT_HELD = 1314;

		internal const int ERROR_INVALID_ACL = 1336;

		internal const int ERROR_INVALID_SECURITY_DESCR = 1338;

		internal const int ERROR_INVALID_SID = 1337;

		internal const int ERROR_BAD_IMPERSONATION_LEVEL = 1346;

		internal const int ERROR_CANT_OPEN_ANONYMOUS = 1347;

		internal const int ERROR_NO_SECURITY_ON_OBJECT = 1350;

		internal const int ERROR_CLASS_ALREADY_EXISTS = 1410;

		internal const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 1789;

		internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 1815;

		internal const int EFail = -2147467259;

		internal const int E_FILENOTFOUND = -2147024894;
	}

	internal class Kernel32
	{
		internal struct SECURITY_ATTRIBUTES
		{
			internal uint nLength;

			internal IntPtr lpSecurityDescriptor;

			internal BOOL bInheritHandle;
		}

		private const int FORMAT_MESSAGE_IGNORE_INSERTS = 512;

		private const int FORMAT_MESSAGE_FROM_HMODULE = 2048;

		private const int FORMAT_MESSAGE_FROM_SYSTEM = 4096;

		private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192;

		private const int ERROR_INSUFFICIENT_BUFFER = 122;

		private const int InitialBufferSize = 256;

		private const int BufferSizeIncreaseFactor = 4;

		private const int MaxAllowedBufferSize = 66560;

		[DllImport("kernel32.dll", BestFitMapping = true, CharSet = CharSet.Unicode, EntryPoint = "FormatMessageW", SetLastError = true)]
		private unsafe static extern int FormatMessage(int dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId, char* lpBuffer, int nSize, IntPtr[] arguments);

		internal static string GetMessage(int errorCode)
		{
			return GetMessage(IntPtr.Zero, errorCode);
		}

		internal static string GetMessage(IntPtr moduleHandle, int errorCode)
		{
			Span<char> buffer = stackalloc char[256];
			do
			{
				if (TryGetErrorMessage(moduleHandle, errorCode, buffer, out var errorMsg))
				{
					return errorMsg;
				}
				buffer = new char[buffer.Length * 4];
			}
			while (buffer.Length < 66560);
			return $"Unknown error (0x{errorCode:x})";
		}

		private unsafe static bool TryGetErrorMessage(IntPtr moduleHandle, int errorCode, Span<char> buffer, out string errorMsg)
		{
			int num = 12800;
			if (moduleHandle != IntPtr.Zero)
			{
				num |= 0x800;
			}
			int num2;
			fixed (char* lpBuffer = &MemoryMarshal.GetReference(buffer))
			{
				num2 = FormatMessage(num, moduleHandle, (uint)errorCode, 0, lpBuffer, buffer.Length, null);
			}
			if (num2 != 0)
			{
				int num3;
				for (num3 = num2; num3 > 0; num3--)
				{
					char c = buffer[num3 - 1];
					if (c > ' ' && c != '.')
					{
						break;
					}
				}
				errorMsg = buffer.Slice(0, num3).ToString();
			}
			else
			{
				if (Marshal.GetLastWin32Error() == 122)
				{
					errorMsg = "";
					return false;
				}
				errorMsg = $"Unknown error (0x{errorCode:x})";
			}
			return true;
		}
	}

	internal enum BOOL
	{
		FALSE,
		TRUE
	}
}
namespace FxResources.Microsoft.Win32.Registry
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static ResourceManager s_resourceManager;

		private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType));

		internal static Type ResourceType { get; } = typeof(SR);


		internal static string AccessControl_InvalidHandle => GetResourceString("AccessControl_InvalidHandle", null);

		internal static string Arg_RegSubKeyAbsent => GetResourceString("Arg_RegSubKeyAbsent", null);

		internal static string Arg_RegKeyDelHive => GetResourceString("Arg_RegKeyDelHive", null);

		internal static string Arg_RegKeyNoRemoteConnect => GetResourceString("Arg_RegKeyNoRemoteConnect", null);

		internal static string Arg_RegKeyOutOfRange => GetResourceString("Arg_RegKeyOutOfRange", null);

		internal static string Arg_RegKeyNotFound => GetResourceString("Arg_RegKeyNotFound", null);

		internal static string Arg_RegKeyStrLenBug => GetResourceString("Arg_RegKeyStrLenBug", null);

		internal static string Arg_RegValStrLenBug => GetResourceString("Arg_RegValStrLenBug", null);

		internal static string Arg_RegBadKeyKind => GetResourceString("Arg_RegBadKeyKind", null);

		internal static string Arg_RegGetOverflowBug => GetResourceString("Arg_RegGetOverflowBug", null);

		internal static string Arg_RegSetMismatchedKind => GetResourceString("Arg_RegSetMismatchedKind", null);

		internal static string Arg_RegSetBadArrType => GetResourceString("Arg_RegSetBadArrType", null);

		internal static string Arg_RegSetStrArrNull => GetResourceString("Arg_RegSetStrArrNull", null);

		internal static string Arg_RegInvalidKeyName => GetResourceString("Arg_RegInvalidKeyName", null);

		internal static string Arg_DllInitFailure => GetResourceString("Arg_DllInitFailure", null);

		internal static string Arg_EnumIllegalVal => GetResourceString("Arg_EnumIllegalVal", null);

		internal static string Arg_RegSubKeyValueAbsent => GetResourceString("Arg_RegSubKeyValueAbsent", null);

		internal static string Argument_InvalidRegistryOptionsCheck => GetResourceString("Argument_InvalidRegistryOptionsCheck", null);

		internal static string Argument_InvalidRegistryViewCheck => GetResourceString("Argument_InvalidRegistryViewCheck", null);

		internal static string Argument_InvalidRegistryKeyPermissionCheck => GetResourceString("Argument_InvalidRegistryKeyPermissionCheck", null);

		internal static string InvalidOperation_RegRemoveSubKey => GetResourceString("InvalidOperation_RegRemoveSubKey", null);

		internal static string ObjectDisposed_RegKeyClosed => GetResourceString("ObjectDisposed_RegKeyClosed", null);

		internal static string PlatformNotSupported_Registry => GetResourceString("PlatformNotSupported_Registry", null);

		internal static string Security_RegistryPermission => GetResourceString("Security_RegistryPermission", null);

		internal static string UnauthorizedAccess_RegistryKeyGeneric_Key => GetResourceString("UnauthorizedAccess_RegistryKeyGeneric_Key", null);

		internal static string UnauthorizedAccess_RegistryNoWrite => GetResourceString("UnauthorizedAccess_RegistryNoWrite", null);

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static bool UsingResourceKeys()
		{
			return false;
		}

		internal static string GetResourceString(string resourceKey, string defaultString)
		{
			string text = null;
			try
			{
				text = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal))
			{
				return defaultString;
			}
			return text;
		}

		internal static string Format(string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + string.Join(", ", args);
				}
				return string.Format(resourceFormat, args);
			}
			return resourceFormat;
		}

		internal static string Format(string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(resourceFormat, p1);
		}

		internal static string Format(string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(resourceFormat, p1, p2);
		}

		internal static string Format(string resourceFormat, object p1, object p2, object p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(resourceFormat, p1, p2, p3);
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.All)]
	internal class __BlockReflectionAttribute : Attribute
	{
	}
}
namespace System.Security.AccessControl
{
	[Flags]
	public enum RegistryRights
	{
		QueryValues = 1,
		SetValue = 2,
		CreateSubKey = 4,
		EnumerateSubKeys = 8,
		Notify = 0x10,
		CreateLink = 0x20,
		ExecuteKey = 0x20019,
		ReadKey = 0x20019,
		WriteKey = 0x20006,
		Delete = 0x10000,
		ReadPermissions = 0x20000,
		ChangePermissions = 0x40000,
		TakeOwnership = 0x80000,
		FullControl = 0xF003F
	}
	public sealed class RegistryAccessRule : AccessRule
	{
		public RegistryRights RegistryRights => (RegistryRights)base.AccessMask;

		public RegistryAccessRule(IdentityReference identity, RegistryRights registryRights, AccessControlType type)
			: this(identity, (int)registryRights, isInherited: false, InheritanceFlags.None, PropagationFlags.None, type)
		{
		}

		public RegistryAccessRule(string identity, RegistryRights registryRights, AccessControlType type)
			: this(new NTAccount(identity), (int)registryRights, isInherited: false, InheritanceFlags.None, PropagationFlags.None, type)
		{
		}

		public RegistryAccessRule(IdentityReference identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
			: this(identity, (int)registryRights, isInherited: false, inheritanceFlags, propagationFlags, type)
		{
		}

		public RegistryAccessRule(string identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
			: this(new NTAccount(identity), (int)registryRights, isInherited: false, inheritanceFlags, propagationFlags, type)
		{
		}

		internal RegistryAccessRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
			: base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type)
		{
		}
	}
	public sealed class RegistryAuditRule : AuditRule
	{
		public RegistryRights RegistryRights => (RegistryRights)base.AccessMask;

		public RegistryAuditRule(IdentityReference identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
			: this(identity, (int)registryRights, isInherited: false, inheritanceFlags, propagationFlags, flags)
		{
		}

		public RegistryAuditRule(string identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
			: this(new NTAccount(identity), (int)registryRights, isInherited: false, inheritanceFlags, propagationFlags, flags)
		{
		}

		internal RegistryAuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
			: base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags)
		{
		}
	}
	public sealed class RegistrySecurity : NativeObjectSecurity
	{
		public override Type AccessRightType => typeof(RegistryRights);

		public override Type AccessRuleType => typeof(RegistryAccessRule);

		public override Type AuditRuleType => typeof(RegistryAuditRule);

		public RegistrySecurity()
			: base(isContainer: true, ResourceType.RegistryKey)
		{
		}

		internal RegistrySecurity(SafeRegistryHandle hKey, string name, AccessControlSections includeSections)
			: base(isContainer: true, ResourceType.RegistryKey, hKey, includeSections, _HandleErrorCode, null)
		{
		}

		private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context)
		{
			return _HandleErrorCodeCore(errorCode, name, handle, context);
		}

		public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
		{
			return new RegistryAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type);
		}

		public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
		{
			return new RegistryAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags);
		}

		internal AccessControlSections GetAccessControlSectionsFromChanges()
		{
			AccessControlSections accessControlSections = AccessControlSections.None;
			if (base.AccessRulesModified)
			{
				accessControlSections = AccessControlSections.Access;
			}
			if (base.AuditRulesModified)
			{
				accessControlSections |= AccessControlSections.Audit;
			}
			if (base.OwnerModified)
			{
				accessControlSections |= AccessControlSections.Owner;
			}
			if (base.GroupModified)
			{
				accessControlSections |= AccessControlSections.Group;
			}
			return accessControlSections;
		}

		internal void Persist(SafeRegistryHandle hKey, string keyName)
		{
			WriteLock();
			try
			{
				AccessControlSections accessControlSectionsFromChanges = GetAccessControlSectionsFromChanges();
				if (accessControlSectionsFromChanges != 0)
				{
					Persist(hKey, accessControlSectionsFromChanges);
					bool flag2 = (base.AccessRulesModified = false);
					bool flag4 = (base.AuditRulesModified = flag2);
					bool ownerModified = (base.GroupModified = flag4);
					base.OwnerModified = ownerModified;
				}
			}
			finally
			{
				WriteUnlock();
			}
		}

		public void AddAccessRule(RegistryAccessRule rule)
		{
			AddAccessRule((AccessRule)rule);
		}

		public void SetAccessRule(RegistryAccessRule rule)
		{
			SetAccessRule((AccessRule)rule);
		}

		public void ResetAccessRule(RegistryAccessRule rule)
		{
			ResetAccessRule((AccessRule)rule);
		}

		public bool RemoveAccessRule(RegistryAccessRule rule)
		{
			return RemoveAccessRule((AccessRule)rule);
		}

		public void RemoveAccessRuleAll(RegistryAccessRule rule)
		{
			RemoveAccessRuleAll((AccessRule)rule);
		}

		public void RemoveAccessRuleSpecific(RegistryAccessRule rule)
		{
			RemoveAccessRuleSpecific((AccessRule)rule);
		}

		public void AddAuditRule(RegistryAuditRule rule)
		{
			AddAuditRule((AuditRule)rule);
		}

		public void SetAuditRule(RegistryAuditRule rule)
		{
			SetAuditRule((AuditRule)rule);
		}

		public bool RemoveAuditRule(RegistryAuditRule rule)
		{
			return RemoveAuditRule((AuditRule)rule);
		}

		public void RemoveAuditRuleAll(RegistryAuditRule rule)
		{
			RemoveAuditRuleAll((AuditRule)rule);
		}

		public void RemoveAuditRuleSpecific(RegistryAuditRule rule)
		{
			RemoveAuditRuleSpecific((AuditRule)rule);
		}

		private static Exception _HandleErrorCodeCore(int errorCode, string name, SafeHandle handle, object context)
		{
			Exception result = null;
			switch (errorCode)
			{
			case 2:
				result = new IOException(System.SR.Format(System.SR.Arg_RegKeyNotFound, errorCode));
				break;
			case 123:
				result = new ArgumentException(System.SR.Format(System.SR.Arg_RegInvalidKeyName, "name"));
				break;
			case 6:
				result = new ArgumentException(System.SR.AccessControl_InvalidHandle);
				break;
			}
			return result;
		}
	}
}
namespace Microsoft.Win32
{
	public static class Registry
	{
		public static readonly RegistryKey CurrentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default);

		public static readonly RegistryKey LocalMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default);

		public static readonly RegistryKey ClassesRoot = RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Default);

		public static readonly RegistryKey Users = RegistryKey.OpenBaseKey(RegistryHive.Users, RegistryView.Default);

		public static readonly RegistryKey PerformanceData = RegistryKey.OpenBaseKey(RegistryHive.PerformanceData, RegistryView.Default);

		public static readonly RegistryKey CurrentConfig = RegistryKey.OpenBaseKey(RegistryHive.CurrentConfig, RegistryView.Default);

		public static object GetValue(string keyName, string valueName, object defaultValue)
		{
			string subKeyName;
			RegistryKey baseKeyFromKeyName = GetBaseKeyFromKeyName(keyName, out subKeyName);
			using RegistryKey registryKey = baseKeyFromKeyName.OpenSubKey(subKeyName);
			return registryKey?.GetValue(valueName, defaultValue);
		}

		public static void SetValue(string keyName, string valueName, object value)
		{
			SetValue(keyName, valueName, value, RegistryValueKind.Unknown);
		}

		public static void SetValue(string keyName, string valueName, object value, RegistryValueKind valueKind)
		{
			string subKeyName;
			RegistryKey baseKeyFromKeyName = GetBaseKeyFromKeyName(keyName, out subKeyName);
			using RegistryKey registryKey = baseKeyFromKeyName.CreateSubKey(subKeyName);
			registryKey.SetValue(valueName, value, valueKind);
		}

		private static RegistryKey GetBaseKeyFromKeyName(string keyName, out string subKeyName)
		{
			if (keyName == null)
			{
				throw new ArgumentNullException("keyName");
			}
			int num = keyName.IndexOf('\\');
			int num2 = ((num != -1) ? num : keyName.Length);
			RegistryKey registryKey = null;
			switch (num2)
			{
			case 10:
				registryKey = Users;
				break;
			case 17:
				registryKey = ((char.ToUpperInvariant(keyName[6]) == 'L') ? ClassesRoot : CurrentUser);
				break;
			case 18:
				registryKey = LocalMachine;
				break;
			case 19:
				registryKey = CurrentConfig;
				break;
			case 21:
				registryKey = PerformanceData;
				break;
			}
			if (registryKey != null && keyName.StartsWith(registryKey.Name, StringComparison.OrdinalIgnoreCase))
			{
				subKeyName = ((num == -1 || num == keyName.Length) ? string.Empty : keyName.Substring(num + 1, keyName.Length - num - 1));
				return registryKey;
			}
			throw new ArgumentException(System.SR.Format(System.SR.Arg_RegInvalidKeyName, "keyName"), "keyName");
		}
	}
	public sealed class RegistryKey : MarshalByRefObject, IDisposable
	{
		[Flags]
		private enum StateFlags
		{
			Dirty = 1,
			SystemKey = 2,
			WriteAccess = 4,
			PerfData = 8
		}

		private static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(int.MinValue);

		private static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(-2147483647);

		private static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(-2147483646);

		private static readonly IntPtr HKEY_USERS = new IntPtr(-2147483645);

		private static readonly IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(-2147483644);

		private static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(-2147483643);

		private static readonly string[] s_hkeyNames = new string[6] { "HKEY_CLASSES_ROOT", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_PERFORMANCE_DATA", "HKEY_CURRENT_CONFIG" };

		private const int MaxKeyLength = 255;

		private const int MaxValueLength = 16383;

		private volatile SafeRegistryHandle _hkey;

		private volatile string _keyName;

		private volatile bool _remoteKey;

		private volatile StateFlags _state;

		private volatile RegistryKeyPermissionCheck _checkMode;

		private volatile RegistryView _regView;

		public int SubKeyCount => InternalSubKeyCount();

		public RegistryView View
		{
			get
			{
				EnsureNotDisposed();
				return _regView;
			}
		}

		public SafeRegistryHandle Handle
		{
			get
			{
				EnsureNotDisposed();
				if (!IsSystemKey())
				{
					return _hkey;
				}
				return SystemKeyHandle;
			}
		}

		public int ValueCount => InternalValueCount();

		public string Name
		{
			get
			{
				EnsureNotDisposed();
				return _keyName;
			}
		}

		private SafeRegistryHandle SystemKeyHandle
		{
			get
			{
				int errorCode = 6;
				IntPtr hKey = (IntPtr)0;
				switch (_keyName)
				{
				case "HKEY_CLASSES_ROOT":
					hKey = HKEY_CLASSES_ROOT;
					break;
				case "HKEY_CURRENT_USER":
					hKey = HKEY_CURRENT_USER;
					break;
				case "HKEY_LOCAL_MACHINE":
					hKey = HKEY_LOCAL_MACHINE;
					break;
				case "HKEY_USERS":
					hKey = HKEY_USERS;
					break;
				case "HKEY_PERFORMANCE_DATA":
					hKey = HKEY_PERFORMANCE_DATA;
					break;
				case "HKEY_CURRENT_CONFIG":
					hKey = HKEY_CURRENT_CONFIG;
					break;
				default:
					Win32Error(errorCode, null);
					break;
				}
				errorCode = global::Interop.Advapi32.RegOpenKeyEx(hKey, null, 0, GetRegistryKeyAccess(IsWritable()) | (int)_regView, out var hkResult);
				if (errorCode == 0 && !hkResult.IsInvalid)
				{
					return hkResult;
				}
				Win32Error(errorCode, null);
				throw new IOException(global::Interop.Kernel32.GetMessage(errorCode), errorCode);
			}
		}

		private RegistryKey(SafeRegistryHandle hkey, bool writable, RegistryView view)
			: this(hkey, writable, systemkey: false, remoteKey: false, isPerfData: false, view)
		{
		}

		private RegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, bool remoteKey, bool isPerfData, RegistryView view)
		{
			ValidateKeyView(view);
			_hkey = hkey;
			_keyName = "";
			_remoteKey = remoteKey;
			_regView = view;
			if (systemkey)
			{
				_state |= StateFlags.SystemKey;
			}
			if (writable)
			{
				_state |= StateFlags.WriteAccess;
			}
			if (isPerfData)
			{
				_state |= StateFlags.PerfData;
			}
		}

		public void Flush()
		{
			FlushCore();
		}

		public void Close()
		{
			Dispose();
		}

		public void Dispose()
		{
			if (_hkey == null)
			{
				return;
			}
			if (!IsSystemKey())
			{
				try
				{
					_hkey.Dispose();
					return;
				}
				catch (IOException)
				{
					return;
				}
				finally
				{
					_hkey = null;
				}
			}
			if (IsPerfDataKey())
			{
				ClosePerfDataKey();
			}
		}

		public RegistryKey CreateSubKey(string subkey)
		{
			return CreateSubKey(subkey, _checkMode);
		}

		public RegistryKey CreateSubKey(string subkey, bool writable)
		{
			return CreateSubKeyInternal(subkey, (!writable) ? RegistryKeyPermissionCheck.ReadSubTree : RegistryKeyPermissionCheck.ReadWriteSubTree, null, RegistryOptions.None);
		}

		public RegistryKey CreateSubKey(string subkey, bool writable, RegistryOptions options)
		{
			return CreateSubKeyInternal(subkey, (!writable) ? RegistryKeyPermissionCheck.ReadSubTree : RegistryKeyPermissionCheck.ReadWriteSubTree, null, options);
		}

		public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck)
		{
			return CreateSubKeyInternal(subkey, permissionCheck, null, RegistryOptions.None);
		}

		public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions)
		{
			return CreateSubKeyInternal(subkey, permissionCheck, null, registryOptions);
		}

		public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions, RegistrySecurity registrySecurity)
		{
			return CreateSubKeyInternal(subkey, permissionCheck, registrySecurity, registryOptions);
		}

		public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistrySecurity registrySecurity)
		{
			return CreateSubKeyInternal(subkey, permissionCheck, registrySecurity, RegistryOptions.None);
		}

		private RegistryKey CreateSubKeyInternal(string subkey, RegistryKeyPermissionCheck permissionCheck, object registrySecurityObj, RegistryOptions registryOptions)
		{
			ValidateKeyOptions(registryOptions);
			ValidateKeyName(subkey);
			ValidateKeyMode(permissionCheck);
			EnsureWriteable();
			subkey = FixupName(subkey);
			if (!_remoteKey)
			{
				RegistryKey registryKey = InternalOpenSubKeyWithoutSecurityChecks(subkey, permissionCheck != RegistryKeyPermissionCheck.ReadSubTree);
				if (registryKey != null)
				{
					registryKey._checkMode = permissionCheck;
					return registryKey;
				}
			}
			return CreateSubKeyInternalCore(subkey, permissionCheck, registrySecurityObj, registryOptions);
		}

		public void DeleteSubKey(string subkey)
		{
			DeleteSubKey(subkey, throwOnMissingSubKey: true);
		}

		public void DeleteSubKey(string subkey, bool throwOnMissingSubKey)
		{
			ValidateKeyName(subkey);
			EnsureWriteable();
			subkey = FixupName(subkey);
			RegistryKey registryKey = InternalOpenSubKeyWithoutSecurityChecks(subkey, writable: false);
			if (registryKey != null)
			{
				using (registryKey)
				{
					if (registryKey.InternalSubKeyCount() > 0)
					{
						ThrowHelper.ThrowInvalidOperationException(System.SR.InvalidOperation_RegRemoveSubKey);
					}
				}
				DeleteSubKeyCore(subkey, throwOnMissingSubKey);
			}
			else if (throwOnMissingSubKey)
			{
				ThrowHelper.ThrowArgumentException(System.SR.Arg_RegSubKeyAbsent);
			}
		}

		public void DeleteSubKeyTree(string subkey)
		{
			DeleteSubKeyTree(subkey, throwOnMissingSubKey: true);
		}

		public void DeleteSubKeyTree(string subkey, bool throwOnMissingSubKey)
		{
			ValidateKeyName(subkey);
			if (subkey.Length == 0 && IsSystemKey())
			{
				ThrowHelper.ThrowArgumentException(System.SR.Arg_RegKeyDelHive);
			}
			EnsureWriteable();
			subkey = FixupName(subkey);
			RegistryKey registryKey = InternalOpenSubKeyWithoutSecurityChecks(subkey, writable: true);
			if (registryKey != null)
			{
				using (registryKey)
				{
					if (registryKey.InternalSubKeyCount() > 0)
					{
						string[] array = registryKey.InternalGetSubKeyNames();
						for (int i = 0; i < array.Length; i++)
						{
							registryKey.DeleteSubKeyTreeInternal(array[i]);
						}
					}
				}
				DeleteSubKeyTreeCore(subkey);
			}
			else if (throwOnMissingSubKey)
			{
				ThrowHelper.ThrowArgumentException(System.SR.Arg_RegSubKeyAbsent);
			}
		}

		private void DeleteSubKeyTreeInternal(string subkey)
		{
			RegistryKey registryKey = InternalOpenSubKeyWithoutSecurityChecks(subkey, writable: true);
			if (registryKey != null)
			{
				using (registryKey)
				{
					if (registryKey.InternalSubKeyCount() > 0)
					{
						string[] array = registryKey.InternalGetSubKeyNames();
						for (int i = 0; i < array.Length; i++)
						{
							registryKey.DeleteSubKeyTreeInternal(array[i]);
						}
					}
				}
				DeleteSubKeyTreeCore(subkey);
			}
			else
			{
				ThrowHelper.ThrowArgumentException(System.SR.Arg_RegSubKeyAbsent);
			}
		}

		public void DeleteValue(string name)
		{
			DeleteValue(name, throwOnMissingValue: true);
		}

		public void DeleteValue(string name, bool throwOnMissingValue)
		{
			EnsureWriteable();
			DeleteValueCore(name, throwOnMissingValue);
		}

		public static RegistryKey OpenBaseKey(RegistryHive hKey, RegistryView view)
		{
			ValidateKeyView(view);
			return OpenBaseKeyCore(hKey, view);
		}

		public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, string machineName)
		{
			return OpenRemoteBaseKey(hKey, machineName, RegistryView.Default);
		}

		public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, string machineName, RegistryView view)
		{
			if (machineName == null)
			{
				throw new ArgumentNullException("machineName");
			}
			ValidateKeyView(view);
			return OpenRemoteBaseKeyCore(hKey, machineName, view);
		}

		public RegistryKey OpenSubKey(string name)
		{
			return OpenSubKey(name, writable: false);
		}

		public RegistryKey OpenSubKey(string name, bool writable)
		{
			ValidateKeyName(name);
			EnsureNotDisposed();
			name = FixupName(name);
			return InternalOpenSubKeyCore(name, writable, throwOnPermissionFailure: true);
		}

		public RegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck)
		{
			ValidateKeyMode(permissionCheck);
			return InternalOpenSubKey(name, permissionCheck, GetRegistryKeyAccess(permissionCheck));
		}

		public RegistryKey OpenSubKey(string name, RegistryRights rights)
		{
			return InternalOpenSubKey(name, _checkMode, (int)rights);
		}

		public RegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights)
		{
			return InternalOpenSubKey(name, permissionCheck, (int)rights);
		}

		private RegistryKey InternalOpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck, int rights)
		{
			ValidateKeyName(name);
			ValidateKeyMode(permissionCheck);
			ValidateKeyRights(rights);
			EnsureNotDisposed();
			name = FixupName(name);
			return InternalOpenSubKeyCore(name, permissionCheck, rights, throwOnPermissionFailure: true);
		}

		internal RegistryKey InternalOpenSubKeyWithoutSecurityChecks(string name, bool writable)
		{
			ValidateKeyName(name);
			EnsureNotDisposed();
			return InternalOpenSubKeyWithoutSecurityChecksCore(name, writable);
		}

		public RegistrySecurity GetAccessControl()
		{
			return GetAccessControl(AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
		}

		public RegistrySecurity GetAccessControl(AccessControlSections includeSections)
		{
			EnsureNotDisposed();
			return new RegistrySecurity(Handle, Name, includeSections);
		}

		public void SetAccessControl(RegistrySecurity registrySecurity)
		{
			EnsureWriteable();
			if (registrySecurity == null)
			{
				throw new ArgumentNullException("registrySecurity");
			}
			registrySecurity.Persist(Handle, Name);
		}

		public static RegistryKey FromHandle(SafeRegistryHandle handle)
		{
			return FromHandle(handle, RegistryView.Default);
		}

		public static RegistryKey FromHandle(SafeRegistryHandle handle, RegistryView view)
		{
			if (handle == null)
			{
				throw new ArgumentNullException("handle");
			}
			ValidateKeyView(view);
			return new RegistryKey(handle, writable: true, view);
		}

		private int InternalSubKeyCount()
		{
			EnsureNotDisposed();
			return InternalSubKeyCountCore();
		}

		public string[] GetSubKeyNames()
		{
			return InternalGetSubKeyNames();
		}

		private string[] InternalGetSubKeyNames()
		{
			EnsureNotDisposed();
			int num = InternalSubKeyCount();
			if (num <= 0)
			{
				return Array.Empty<string>();
			}
			return InternalGetSubKeyNamesCore(num);
		}

		private int InternalValueCount()
		{
			EnsureNotDisposed();
			return InternalValueCountCore();
		}

		public string[] GetValueNames()
		{
			EnsureNotDisposed();
			int num = InternalValueCount();
			if (num <= 0)
			{
				return Array.Empty<string>();
			}
			return GetValueNamesCore(num);
		}

		public object GetValue(string name)
		{
			return InternalGetValue(name, null, doNotExpand: false, checkSecurity: true);
		}

		public object GetValue(string name, object defaultValue)
		{
			return InternalGetValue(name, defaultValue, doNotExpand: false, checkSecurity: true);
		}

		public object GetValue(string name, object defaultValue, RegistryValueOptions options)
		{
			if (options < RegistryValueOptions.None || options > RegistryValueOptions.DoNotExpandEnvironmentNames)
			{
				throw new ArgumentException(System.SR.Format(System.SR.Arg_EnumIllegalVal, (int)options), "options");
			}
			bool doNotExpand = options == RegistryValueOptions.DoNotExpandEnvironmentNames;
			return InternalGetValue(name, defaultValue, doNotExpand, checkSecurity: true);
		}

		private object InternalGetValue(string name, object defaultValue, bool doNotExpand, bool checkSecurity)
		{
			if (checkSecurity)
			{
				EnsureNotDisposed();
			}
			return InternalGetValueCore(name, defaultValue, doNotExpand);
		}

		public RegistryValueKind GetValueKind(string name)
		{
			EnsureNotDisposed();
			return GetValueKindCore(name);
		}

		public void SetValue(string name, object value)
		{
			SetValue(name, value, RegistryValueKind.Unknown);
		}

		public void SetValue(string name, object value, RegistryValueKind valueKind)
		{
			if (value == null)
			{
				ThrowHelper.ThrowArgumentNullException("value");
			}
			if (name != null && name.Length > 16383)
			{
				throw new ArgumentException(System.SR.Arg_RegValStrLenBug, "name");
			}
			if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind))
			{
				throw new ArgumentException(System.SR.Arg_RegBadKeyKind, "valueKind");
			}
			EnsureWriteable();
			if (valueKind == RegistryValueKind.Unknown)
			{
				valueKind = CalculateValueKind(value);
			}
			SetValueCore(name, value, valueKind);
		}

		private RegistryValueKind CalculateValueKind(object value)
		{
			if (value is int)
			{
				return RegistryValueKind.DWord;
			}
			if (value is Array)
			{
				if (value is byte[])
				{
					return RegistryValueKind.Binary;
				}
				if (value is string[])
				{
					return RegistryValueKind.MultiString;
				}
				throw new ArgumentException(System.SR.Format(System.SR.Arg_RegSetBadArrType, value.GetType().Name));
			}
			return RegistryValueKind.String;
		}

		public override string ToString()
		{
			EnsureNotDisposed();
			return _keyName;
		}

		private static string FixupName(string name)
		{
			if (name.IndexOf('\\') == -1)
			{
				return name;
			}
			StringBuilder stringBuilder = new StringBuilder(name);
			FixupPath(stringBuilder);
			int num = stringBuilder.Length - 1;
			if (num >= 0 && stringBuilder[num] == '\\')
			{
				stringBuilder.Length = num;
			}
			return stringBuilder.ToString();
		}

		private static void FixupPath(StringBuilder path)
		{
			int length = path.Length;
			bool flag = false;
			char c = '\uffff';
			int i;
			for (i = 1; i < length - 1; i++)
			{
				if (path[i] == '\\')
				{
					i++;
					while (i < length && path[i] == '\\')
					{
						path[i] = c;
						i++;
						flag = true;
					}
				}
			}
			if (!flag)
			{
				return;
			}
			i = 0;
			int num = 0;
			while (i < length)
			{
				if (path[i] == c)
				{
					i++;
					continue;
				}
				path[num] = path[i];
				i++;
				num++;
			}
			path.Length += num - i;
		}

		private void EnsureNotDisposed()
		{
			if (_hkey == null)
			{
				ThrowHelper.ThrowObjectDisposedException(_keyName, System.SR.ObjectDisposed_RegKeyClosed);
			}
		}

		private void EnsureWriteable()
		{
			EnsureNotDisposed();
			if (!IsWritable())
			{
				ThrowHelper.ThrowUnauthorizedAccessException(System.SR.UnauthorizedAccess_RegistryNoWrite);
			}
		}

		private RegistryKeyPermissionCheck GetSubKeyPermissionCheck(bool subkeyWritable)
		{
			if (_checkMode == RegistryKeyPermissionCheck.Default)
			{
				return _checkMode;
			}
			if (subkeyWritable)
			{
				return RegistryKeyPermissionCheck.ReadWriteSubTree;
			}
			return RegistryKeyPermissionCheck.ReadSubTree;
		}

		private static void ValidateKeyName(string name)
		{
			if (name == null)
			{
				ThrowHelper.ThrowArgumentNullException("name");
			}
			int num = name.IndexOf("\\", StringComparison.OrdinalIgnoreCase);
			int num2 = 0;
			while (num != -1)
			{
				if (num - num2 > 255)
				{
					ThrowHelper.ThrowArgumentException(System.SR.Arg_RegKeyStrLenBug, "name");
				}
				num2 = num + 1;
				num = name.IndexOf("\\", num2, StringComparison.OrdinalIgnoreCase);
			}
			if (name.Length - num2 > 255)
			{
				ThrowHelper.ThrowArgumentException(System.SR.Arg_RegKeyStrLenBug, "name");
			}
		}

		private static void ValidateKeyMode(RegistryKeyPermissionCheck mode)
		{
			if (mode < RegistryKeyPermissionCheck.Default || mode > RegistryKeyPermissionCheck.ReadWriteSubTree)
			{
				ThrowHelper.ThrowArgumentException(System.SR.Argument_InvalidRegistryKeyPermissionCheck, "mode");
			}
		}

		private static void ValidateKeyOptions(RegistryOptions options)
		{
			if (options < RegistryOptions.None || options > RegistryOptions.Volatile)
			{
				ThrowHelper.ThrowArgumentException(System.SR.Argument_InvalidRegistryOptionsCheck, "options");
			}
		}

		private static void ValidateKeyView(RegistryView view)
		{
			if (view != 0 && view != RegistryView.Registry32 && view != RegistryView.Registry64)
			{
				ThrowHelper.ThrowArgumentException(System.SR.Argument_InvalidRegistryViewCheck, "view");
			}
		}

		private static void ValidateKeyRights(int rights)
		{
			if (((uint)rights & 0xFFF0FFC0u) != 0)
			{
				ThrowHelper.ThrowSecurityException(System.SR.Security_RegistryPermission);
			}
		}

		private bool IsDirty()
		{
			return (_state & StateFlags.Dirty) != 0;
		}

		private bool IsSystemKey()
		{
			return (_state & StateFlags.SystemKey) != 0;
		}

		private bool IsWritable()
		{
			return (_state & StateFlags.WriteAccess) != 0;
		}

		private bool IsPerfDataKey()
		{
			return (_state & StateFlags.PerfData) != 0;
		}

		private void SetDirty()
		{
			_state |= StateFlags.Dirty;
		}

		private void ClosePerfDataKey()
		{
			global::Interop.Advapi32.RegCloseKey(HKEY_PERFORMANCE_DATA);
		}

		private void FlushCore()
		{
			if (_hkey != null && IsDirty())
			{
				global::Interop.Advapi32.RegFlushKey(_hkey);
			}
		}

		private RegistryKey CreateSubKeyInternalCore(string subkey, RegistryKeyPermissionCheck permissionCheck, object registrySecurityObj, RegistryOptions registryOptions)
		{
			global::Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(global::Interop.Kernel32.SECURITY_ATTRIBUTES);
			int lpdwDisposition = 0;
			SafeRegistryHandle hkResult = null;
			int num = global::Interop.Advapi32.RegCreateKeyEx(_hkey, subkey, 0, null, (int)registryOptions, GetRegistryKeyAccess(permissionCheck != RegistryKeyPermissionCheck.ReadSubTree) | (int)_regView, ref secAttrs, out hkResult, out lpdwDisposition);
			if (num == 0 && !hkResult.IsInvalid)
			{
				RegistryKey registryKey = new RegistryKey(hkResult, permissionCheck != RegistryKeyPermissionCheck.ReadSubTree, systemkey: false, _remoteKey, isPerfData: false, _regView);
				registryKey._checkMode = permissionCheck;
				if (subkey.Length == 0)
				{
					registryKey._keyName = _keyName;
				}
				else
				{
					registryKey._keyName = _keyName + "\\" + subkey;
				}
				return registryKey;
			}
			if (num != 0)
			{
				Win32Error(num, _keyName + "\\" + subkey);
			}
			return null;
		}

		private void DeleteSubKeyCore(string subkey, bool throwOnMissingSubKey)
		{
			int num = global::Interop.Advapi32.RegDeleteKeyEx(_hkey, subkey, (int)_regView, 0);
			switch (num)
			{
			case 2:
				if (throwOnMissingSubKey)
				{
					ThrowHelper.ThrowArgumentException(System.SR.Arg_RegSubKeyAbsent);
				}
				break;
			default:
				Win32Error(num, null);
				break;
			case 0:
				break;
			}
		}

		private void DeleteSubKeyTreeCore(string subkey)
		{
			int num = global::Interop.Advapi32.RegDeleteKeyEx(_hkey, subkey, (int)_regView, 0);
			if (num != 0)
			{
				Win32Error(num, null);
			}
		}

		private void DeleteValueCore(string name, bool throwOnMissingValue)
		{
			int num = global::Interop.Advapi32.RegDeleteValue(_hkey, name);
			if (num == 2 || num == 206)
			{
				if (throwOnMissingValue)
				{
					ThrowHelper.ThrowArgumentException(System.SR.Arg_RegSubKeyValueAbsent);
				}
				else
				{
					num = 0;
				}
			}
		}

		private static RegistryKey OpenBaseKeyCore(RegistryHive hKeyHive, RegistryView view)
		{
			IntPtr intPtr = (IntPtr)(int)hKeyHive;
			int num = (int)intPtr & 0xFFFFFFF;
			bool flag = intPtr == HKEY_PERFORMANCE_DATA;
			SafeRegistryHandle hkey = new SafeRegistryHandle(intPtr, flag);
			RegistryKey registryKey = new RegistryKey(hkey, writable: true, systemkey: true, remoteKey: false, flag, view);
			registryKey._checkMode = RegistryKeyPermissionCheck.Default;
			registryKey._keyName = s_hkeyNames[num];
			return registryKey;
		}

		private static RegistryKey OpenRemoteBaseKeyCore(RegistryHive hKey, string machineName, RegistryView view)
		{
			int num = (int)(hKey & (RegistryHive)268435455);
			if (num < 0 || num >= s_hkeyNames.Length || ((ulong)hKey & 0xFFFFFFF0uL) != 2147483648u)
			{
				throw new ArgumentException(System.SR.Arg_RegKeyOutOfRange);
			}
			SafeRegistryHandle result = null;
			int num2 = global::Interop.Advapi32.RegConnectRegistry(machineName, new SafeRegistryHandle(new IntPtr((int)hKey), ownsHandle: false), out result);
			switch (num2)
			{
			case 1114:
				throw new ArgumentException(System.SR.Arg_DllInitFailure);
			default:
				Win32ErrorStatic(num2, null);
				break;
			case 0:
				break;
			}
			if (result.IsInvalid)
			{
				throw new ArgumentException(System.SR.Format(System.SR.Arg_RegKeyNoRemoteConnect, machineName));
			}
			RegistryKey registryKey = new RegistryKey(result, writable: true, systemkey: false, remoteKey: true, (IntPtr)(int)hKey == HKEY_PERFORMANCE_DATA, view);
			registryKey._checkMode = RegistryKeyPermissionCheck.Default;
			registryKey._keyName = s_hkeyNames[num];
			return registryKey;
		}

		private RegistryKey InternalOpenSubKeyCore(string name, RegistryKeyPermissionCheck permissionCheck, int rights, bool throwOnPermissionFailure)
		{
			SafeRegistryHandle hkResult = null;
			int num = global::Interop.Advapi32.RegOpenKeyEx(_hkey, name, 0, rights | (int)_regView, out hkResult);
			if (num == 0 && !hkResult.IsInvalid)
			{
				RegistryKey registryKey = new RegistryKey(hkResult, permissionCheck == RegistryKeyPermissionCheck.ReadWriteSubTree, systemkey: false, _remoteKey, isPerfData: false, _regView);
				registryKey._keyName = _keyName + "\\" + name;
				registryKey._checkMode = permissionCheck;
				return registryKey;
			}
			if (throwOnPermissionFailure && (num == 5 || num == 1346))
			{
				ThrowHelper.ThrowSecurityException(System.SR.Security_RegistryPermission);
			}
			return null;
		}

		private RegistryKey InternalOpenSubKeyCore(string name, bool writable, bool throwOnPermissionFailure)
		{
			SafeRegistryHandle hkResult = null;
			int num = global::Interop.Advapi32.RegOpenKeyEx(_hkey, name, 0, GetRegistryKeyAccess(writable) | (int)_regView, out hkResult);
			if (num == 0 && !hkResult.IsInvalid)
			{
				RegistryKey registryKey = new RegistryKey(hkResult, writable, systemkey: false, _remoteKey, isPerfData: false, _regView);
				registryKey._checkMode = GetSubKeyPermissionCheck(writable);
				registryKey._keyName = _keyName + "\\" + name;
				return registryKey;
			}
			if (throwOnPermissionFailure && (num == 5 || num == 1346))
			{
				ThrowHelper.ThrowSecurityException(System.SR.Security_RegistryPermission);
			}
			return null;
		}

		internal RegistryKey InternalOpenSubKeyWithoutSecurityChecksCore(string name, bool writable)
		{
			SafeRegistryHandle hkResult = null;
			if (global::Interop.Advapi32.RegOpenKeyEx(_hkey, name, 0, GetRegistryKeyAccess(writable) | (int)_regView, out hkResult) == 0 && !hkResult.IsInvalid)
			{
				RegistryKey registryKey = new RegistryKey(hkResult, writable, systemkey: false, _remoteKey, isPerfData: false, _regView);
				registryKey._keyName = _keyName + "\\" + name;
				return registryKey;
			}
			return null;
		}

		private int InternalSubKeyCountCore()
		{
			int lpcSubKeys = 0;
			int lpcValues = 0;
			int num = global::Interop.Advapi32.RegQueryInfoKey(_hkey, null, null, IntPtr.Zero, ref lpcSubKeys, null, null, ref lpcValues, null, null, null, null);
			if (num != 0)
			{
				Win32Error(num, null);
			}
			return lpcSubKeys;
		}

		private string[] InternalGetSubKeyNamesCore(int subkeys)
		{
			List<string> list = new List<string>(subkeys);
			char[] array = ArrayPool<char>.Shared.Rent(256);
			try
			{
				int lpcbName = array.Length;
				int num;
				while ((num = global::Interop.Advapi32.RegEnumKeyEx(_hkey, list.Count, array, ref lpcbName, null, null, null, null)) != 259)
				{
					if (num == 0)
					{
						list.Add(new string(array, 0, lpcbName));
						lpcbName = array.Length;
					}
					else
					{
						Win32Error(num, null);
					}
				}
			}
			finally
			{
				ArrayPool<char>.Shared.Return(array);
			}
			return list.ToArray();
		}

		private int InternalValueCountCore()
		{
			int lpcValues = 0;
			int lpcSubKeys = 0;
			int num = global::Interop.Advapi32.RegQueryInfoKey(_hkey, null, null, IntPtr.Zero, ref lpcSubKeys, null, null, ref lpcValues, null, null, null, null);
			if (num != 0)
			{
				Win32Error(num, null);
			}
			return lpcValues;
		}

		private unsafe string[] GetValueNamesCore(int values)
		{
			List<string> list = new List<string>(values);
			char[] array = ArrayPool<char>.Shared.Rent(100);
			try
			{
				int lpcbValueName = array.Length;
				int num;
				while ((num = global::Interop.Advapi32.RegEnumValue(_hkey, list.Count, array, ref lpcbValueName, IntPtr.Zero, null, null, null)) != 259)
				{
					switch (num)
					{
					case 0:
						list.Add(new string(array, 0, lpcbValueName));
						break;
					case 234:
						if (IsPerfDataKey())
						{
							fixed (char* value = &array[0])
							{
								list.Add(new string(value));
							}
						}
						else
						{
							char[] array2 = array;
							int num2 = array2.Length;
							array = null;
							ArrayPool<char>.Shared.Return(array2);
							array = ArrayPool<char>.Shared.Rent(checked(num2 * 2));
						}
						break;
					default:
						Win32Error(num, null);
						break;
					}
					lpcbValueName = array.Length;
				}
			}
			finally
			{
				if (array != null)
				{
					ArrayPool<char>.Shared.Return(array);
				}
			}
			return list.ToArray();
		}

		private object InternalGetValueCore(string name, object defaultValue, bool doNotExpand)
		{
			object obj = defaultValue;
			int lpType = 0;
			int lpcbData = 0;
			int num = global::Interop.Advapi32.RegQueryValueEx(_hkey, name, (int[])null, ref lpType, (byte[])null, ref lpcbData);
			if (num != 0)
			{
				if (IsPerfDataKey())
				{
					int num2 = 65000;
					int lpcbData2 = num2;
					byte[] array = new byte[num2];
					int num3;
					while (234 == (num3 = global::Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref lpType, array, ref lpcbData2)))
					{
						if (num2 == int.MaxValue)
						{
							Win32Error(num3, name);
						}
						else
						{
							num2 = ((num2 <= 1073741823) ? (num2 * 2) : int.MaxValue);
						}
						lpcbData2 = num2;
						array = new byte[num2];
					}
					if (num3 != 0)
					{
						Win32Error(num3, name);
					}
					return array;
				}
				if (num != 234)
				{
					return obj;
				}
			}
			if (lpcbData < 0)
			{
				lpcbData = 0;
			}
			switch (lpType)
			{
			case 0:
			case 3:
			case 5:
			{
				byte[] array4 = new byte[lpcbData];
				num = global::Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref lpType, array4, ref lpcbData);
				obj = array4;
				break;
			}
			case 11:
				if (lpcbData <= 8)
				{
					long lpData = 0L;
					num = global::Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref lpType, ref lpData, ref lpcbData);
					obj = lpData;
					break;
				}
				goto case 0;
			case 4:
				if (lpcbData <= 4)
				{
					int lpData2 = 0;
					num = global::Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref lpType, ref lpData2, ref lpcbData);
					obj = lpData2;
					break;
				}
				goto case 11;
			case 1:
			{
				if (lpcbData % 2 == 1)
				{
					try
					{
						lpcbData = checked(lpcbData + 1);
					}
					catch (OverflowException innerException2)
					{
						throw new IOException(System.SR.Arg_RegGetOverflowBug, innerException2);
					}
				}
				char[] array5 = new char[lpcbData / 2];
				num = global::Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref lpType, array5, ref lpcbData);
				obj = ((array5.Length == 0 || array5[^1] != 0) ? new string(array5) : new string(array5, 0, array5.Length - 1));
				break;
			}
			case 2:
			{
				if (lpcbData % 2 == 1)
				{
					try
					{
						lpcbData = checked(lpcbData + 1);
					}
					catch (OverflowException innerException3)
					{
						throw new IOException(System.SR.Arg_RegGetOverflowBug, innerException3);
					}
				}
				char[] array6 = new char[lpcbData / 2];
				num = global::Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref lpType, array6, ref lpcbData);
				obj = ((array6.Length == 0 || array6[^1] != 0) ? new string(array6) : new string(array6, 0, array6.Length - 1));
				if (!doNotExpand)
				{
					obj = Environment.ExpandEnvironmentVariables((string)obj);
				}
				break;
			}
			case 7:
			{
				if (lpcbData % 2 == 1)
				{
					try
					{
						lpcbData = checked(lpcbData + 1);
					}
					catch (OverflowException innerException)
					{
						throw new IOException(System.SR.Arg_RegGetOverflowBug, innerException);
					}
				}
				char[] array2 = new char[lpcbData / 2];
				num = global::Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref lpType, array2, ref lpcbData);
				if (array2.Length != 0 && array2[^1] != 0)
				{
					Array.Resize(ref array2, array2.Length + 1);
				}
				string[] array3 = Array.Empty<string>();
				int num4 = 0;
				int num5 = 0;
				int num6 = array2.Length;
				while (num == 0 && num5 < num6)
				{
					int i;
					for (i = num5; i < num6 && array2[i] != 0; i++)
					{
					}
					string text = null;
					if (i < num6)
					{
						if (i - num5 > 0)
						{
							text = new string(array2, num5, i - num5);
						}
						else if (i != num6 - 1)
						{
							text = string.Empty;
						}
					}
					else
					{
						text = new string(array2, num5, num6 - num5);
					}
					num5 = i + 1;
					if (text != null)
					{
						if (array3.Length == num4)
						{
							Array.Resize(ref array3, (num4 > 0) ? (num4 * 2) : 4);
						}
						array3[num4++] = text;
					}
				}
				Array.Resize(ref array3, num4);
				obj = array3;
				break;
			}
			}
			return obj;
		}

		private RegistryValueKind GetValueKindCore(string name)
		{
			int lpType = 0;
			int lpcbData = 0;
			int num = global::Interop.Advapi32.RegQueryValueEx(_hkey, name, (int[])null, ref lpType, (byte[])null, ref lpcbData);
			if (num != 0)
			{
				Win32Error(num, null);
			}
			if (lpType != 0)
			{
				if (Enum.IsDefined(typeof(RegistryValueKind), lpType))
				{
					return (RegistryValueKind)lpType;
				}
				return RegistryValueKind.Unknown;
			}
			return RegistryValueKind.None;
		}

		private void SetValueCore(string name, object value, RegistryValueKind valueKind)
		{
			int num = 0;
			try
			{
				switch (valueKind)
				{
				case RegistryValueKind.String:
				case RegistryValueKind.ExpandString:
				{
					string text = value.ToString();
					num = global::Interop.Advapi32.RegSetValueEx(_hkey, name, 0, valueKind, text, checked(text.Length * 2 + 2));
					break;
				}
				case RegistryValueKind.MultiString:
				{
					string[] array2 = (string[])((string[])value).Clone();
					int num2 = 1;
					for (int i = 0; i < array2.Length; i++)
					{
						if (array2[i] == null)
						{
							ThrowHelper.ThrowArgumentException(System.SR.Arg_RegSetStrArrNull);
						}
						num2 = checked(num2 + (array2[i].Length + 1));
					}
					int cbData = checked(num2 * 2);
					char[] array3 = new char[num2];
					int num3 = 0;
					for (int j = 0; j < array2.Length; j++)
					{
						int length = array2[j].Length;
						array2[j].CopyTo(0, array3, num3, length);
						num3 += length + 1;
					}
					num = global::Interop.Advapi32.RegSetValueEx(_hkey, name, 0, RegistryValueKind.MultiString, array3, cbData);
					break;
				}
				case RegistryValueKind.None:
				case RegistryValueKind.Binary:
				{
					byte[] array = (byte[])value;
					num = global::Interop.Advapi32.RegSetValueEx(_hkey, name, 0, (valueKind != RegistryValueKind.None) ? RegistryValueKind.Binary : RegistryValueKind.Unknown, array, array.Length);
					break;
				}
				case RegistryValueKind.DWord:
				{
					int lpData2 = Convert.ToInt32(value, CultureInfo.InvariantCulture);
					num = global::Interop.Advapi32.RegSetValueEx(_hkey, name, 0, RegistryValueKind.DWord, ref lpData2, 4);
					break;
				}
				case RegistryValueKind.QWord:
				{
					long lpData = Convert.ToInt64(value, CultureInfo.InvariantCulture);
					num = global::Interop.Advapi32.RegSetValueEx(_hkey, name, 0, RegistryValueKind.QWord, ref lpData, 8);
					break;
				}
				case RegistryValueKind.Unknown:
				case (RegistryValueKind)5:
				case (RegistryValueKind)6:
				case (RegistryValueKind)8:
				case (RegistryValueKind)9:
				case (RegistryValueKind)10:
					break;
				}
			}
			catch (Exception ex) when (ex is OverflowException || ex is InvalidOperationException || ex is FormatException || ex is InvalidCastException)
			{
				ThrowHelper.ThrowArgumentException(System.SR.Arg_RegSetMismatchedKind);
			}
			if (num == 0)
			{
				SetDirty();
			}
			else
			{
				Win32Error(num, null);
			}
		}

		private void Win32Error(int errorCode, string str)
		{
			switch (errorCode)
			{
			case 5:
				throw (str != null) ? new UnauthorizedAccessException(System.SR.Format(System.SR.UnauthorizedAccess_RegistryKeyGeneric_Key, str)) : new UnauthorizedAccessException();
			case 6:
				if (!IsPerfDataKey())
				{
					_hkey.SetHandleAsInvalid();
					_hkey = null;
				}
				break;
			case 2:
				throw new IOException(System.SR.Arg_RegKeyNotFound, errorCode);
			}
			throw new IOException(global::Interop.Kernel32.GetMessage(errorCode), errorCode);
		}

		private static void Win32ErrorStatic(int errorCode, string str)
		{
			if (errorCode == 5)
			{
				throw (str != null) ? new UnauthorizedAccessException(System.SR.Format(System.SR.UnauthorizedAccess_RegistryKeyGeneric_Key, str)) : new UnauthorizedAccessException();
			}
			throw new IOException(global::Interop.Kernel32.GetMessage(errorCode), errorCode);
		}

		private static int GetRegistryKeyAccess(bool isWritable)
		{
			if (!isWritable)
			{
				return 131097;
			}
			return 131103;
		}

		private static int GetRegistryKeyAccess(RegistryKeyPermissionCheck mode)
		{
			int result = 0;
			switch (mode)
			{
			case RegistryKeyPermissionCheck.Default:
			case RegistryKeyPermissionCheck.ReadSubTree:
				result = 131097;
				break;
			case RegistryKeyPermissionCheck.ReadWriteSubTree:
				result = 131103;
				break;
			}
			return result;
		}
	}
	[Flags]
	public enum RegistryKeyPermissionCheck
	{
		Default = 0,
		ReadSubTree = 1,
		ReadWriteSubTree = 2
	}
	public enum RegistryHive
	{
		ClassesRoot = int.MinValue,
		CurrentUser,
		LocalMachine,
		Users,
		PerformanceData,
		CurrentConfig
	}
	[Flags]
	public enum RegistryOptions
	{
		None = 0,
		Volatile = 1
	}
	public enum RegistryValueKind
	{
		String = 1,
		ExpandString = 2,
		Binary = 3,
		DWord = 4,
		MultiString = 7,
		QWord = 11,
		Unknown = 0,
		None = -1
	}
	[Flags]
	public enum RegistryValueOptions
	{
		None = 0,
		DoNotExpandEnvironmentNames = 1
	}
	public enum RegistryView
	{
		Default = 0,
		Registry64 = 0x100,
		Registry32 = 0x200
	}
	internal static class ThrowHelper
	{
		internal static void ThrowArgumentException(string msg)
		{
			throw new ArgumentException(msg);
		}

		internal static void ThrowArgumentException(string msg, string argument)
		{
			throw new ArgumentException(msg, argument);
		}

		internal static void ThrowArgumentNullException(string argument)
		{
			throw new ArgumentNullException(argument);
		}

		internal static void ThrowInvalidOperationException(string msg)
		{
			throw new InvalidOperationException(msg);
		}

		internal static void ThrowSecurityException(string msg)
		{
			throw new SecurityException(msg);
		}

		internal static void ThrowUnauthorizedAccessException(string msg)
		{
			throw new UnauthorizedAccessException(msg);
		}

		internal static void ThrowObjectDisposedException(string objectName, string msg)
		{
			throw new ObjectDisposedException(objectName, msg);
		}
	}
}
namespace Microsoft.Win32.SafeHandles
{
	public sealed class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid
	{
		internal SafeRegistryHandle()
			: base(ownsHandle: true)
		{
		}

		public SafeRegistryHandle(IntPtr preexistingHandle, bool ownsHandle)
			: base(ownsHandle)
		{
			SetHandle(preexistingHandle);
		}

		protected override bool ReleaseHandle()
		{
			return global::Interop.Advapi32.RegCloseKey(handle) == 0;
		}
	}
}

plugins/System.Buffers.dll

Decompiled a day ago
using System;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using FxResources.System.Buffers;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyTitle("System.Buffers")]
[assembly: AssemblyDescription("System.Buffers")]
[assembly: AssemblyDefaultAlias("System.Buffers")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: AssemblyCopyright("© Microsoft Corporation.  All rights reserved.")]
[assembly: AssemblyFileVersion("4.6.25519.03")]
[assembly: AssemblyInformationalVersion("4.6.25519.03 built by: dlab-DDVSOWINAGE013. Commit Hash: 8321c729934c0f8be754953439b88e6e1c120c24")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.2.0")]
[module: UnverifiableCode]
namespace FxResources.System.Buffers
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static ResourceManager s_resourceManager;

		private const string s_resourcesName = "FxResources.System.Buffers.SR";

		private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType));

		internal static string ArgumentException_BufferNotFromPool => GetResourceString("ArgumentException_BufferNotFromPool", null);

		internal static Type ResourceType => typeof(SR);

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static bool UsingResourceKeys()
		{
			return false;
		}

		internal static string GetResourceString(string resourceKey, string defaultString)
		{
			string text = null;
			try
			{
				text = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal))
			{
				return defaultString;
			}
			return text;
		}

		internal static string Format(string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + string.Join(", ", args);
				}
				return string.Format(resourceFormat, args);
			}
			return resourceFormat;
		}

		internal static string Format(string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(resourceFormat, p1);
		}

		internal static string Format(string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(resourceFormat, p1, p2);
		}

		internal static string Format(string resourceFormat, object p1, object p2, object p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(resourceFormat, p1, p2, p3);
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.All)]
	internal class __BlockReflectionAttribute : Attribute
	{
	}
}
namespace System.Buffers
{
	public abstract class ArrayPool<T>
	{
		private static ArrayPool<T> s_sharedInstance;

		public static ArrayPool<T> Shared
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				return Volatile.Read(ref s_sharedInstance) ?? EnsureSharedCreated();
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static ArrayPool<T> EnsureSharedCreated()
		{
			Interlocked.CompareExchange(ref s_sharedInstance, Create(), null);
			return s_sharedInstance;
		}

		public static ArrayPool<T> Create()
		{
			return new DefaultArrayPool<T>();
		}

		public static ArrayPool<T> Create(int maxArrayLength, int maxArraysPerBucket)
		{
			return new DefaultArrayPool<T>(maxArrayLength, maxArraysPerBucket);
		}

		public abstract T[] Rent(int minimumLength);

		public abstract void Return(T[] array, bool clearArray = false);
	}
	[EventSource(Name = "System.Buffers.ArrayPoolEventSource")]
	internal sealed class ArrayPoolEventSource : EventSource
	{
		internal enum BufferAllocatedReason
		{
			Pooled,
			OverMaximumSize,
			PoolExhausted
		}

		internal static readonly System.Buffers.ArrayPoolEventSource Log = new System.Buffers.ArrayPoolEventSource();

		[Event(1, Level = EventLevel.Verbose)]
		internal unsafe void BufferRented(int bufferId, int bufferSize, int poolId, int bucketId)
		{
			EventData* ptr = stackalloc EventData[4];
			ptr->Size = 4;
			ptr->DataPointer = (IntPtr)(&bufferId);
			ptr[1].Size = 4;
			ptr[1].DataPointer = (IntPtr)(&bufferSize);
			ptr[2].Size = 4;
			ptr[2].DataPointer = (IntPtr)(&poolId);
			ptr[3].Size = 4;
			ptr[3].DataPointer = (IntPtr)(&bucketId);
			WriteEventCore(1, 4, ptr);
		}

		[Event(2, Level = EventLevel.Informational)]
		internal unsafe void BufferAllocated(int bufferId, int bufferSize, int poolId, int bucketId, BufferAllocatedReason reason)
		{
			EventData* ptr = stackalloc EventData[5];
			ptr->Size = 4;
			ptr->DataPointer = (IntPtr)(&bufferId);
			ptr[1].Size = 4;
			ptr[1].DataPointer = (IntPtr)(&bufferSize);
			ptr[2].Size = 4;
			ptr[2].DataPointer = (IntPtr)(&poolId);
			ptr[3].Size = 4;
			ptr[3].DataPointer = (IntPtr)(&bucketId);
			ptr[4].Size = 4;
			ptr[4].DataPointer = (IntPtr)(&reason);
			WriteEventCore(2, 5, ptr);
		}

		[Event(3, Level = EventLevel.Verbose)]
		internal void BufferReturned(int bufferId, int bufferSize, int poolId)
		{
			WriteEvent(3, bufferId, bufferSize, poolId);
		}
	}
	internal sealed class DefaultArrayPool<T> : ArrayPool<T>
	{
		private sealed class Bucket
		{
			internal readonly int _bufferLength;

			private readonly T[][] _buffers;

			private readonly int _poolId;

			private SpinLock _lock;

			private int _index;

			internal int Id => GetHashCode();

			internal Bucket(int bufferLength, int numberOfBuffers, int poolId)
			{
				_lock = new SpinLock(Debugger.IsAttached);
				_buffers = new T[numberOfBuffers][];
				_bufferLength = bufferLength;
				_poolId = poolId;
			}

			internal T[] Rent()
			{
				T[][] buffers = _buffers;
				T[] array = null;
				bool lockTaken = false;
				bool flag = false;
				try
				{
					_lock.Enter(ref lockTaken);
					if (_index < buffers.Length)
					{
						array = buffers[_index];
						buffers[_index++] = null;
						flag = array == null;
					}
				}
				finally
				{
					if (lockTaken)
					{
						_lock.Exit(useMemoryBarrier: false);
					}
				}
				if (flag)
				{
					array = new T[_bufferLength];
					System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log;
					if (log.IsEnabled())
					{
						log.BufferAllocated(array.GetHashCode(), _bufferLength, _poolId, Id, System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.Pooled);
					}
				}
				return array;
			}

			internal void Return(T[] array)
			{
				if (array.Length != _bufferLength)
				{
					throw new ArgumentException(System.SR.ArgumentException_BufferNotFromPool, "array");
				}
				bool lockTaken = false;
				try
				{
					_lock.Enter(ref lockTaken);
					if (_index != 0)
					{
						_buffers[--_index] = array;
					}
				}
				finally
				{
					if (lockTaken)
					{
						_lock.Exit(useMemoryBarrier: false);
					}
				}
			}
		}

		private const int DefaultMaxArrayLength = 1048576;

		private const int DefaultMaxNumberOfArraysPerBucket = 50;

		private static T[] s_emptyArray;

		private readonly Bucket[] _buckets;

		private int Id => GetHashCode();

		internal DefaultArrayPool()
			: this(1048576, 50)
		{
		}

		internal DefaultArrayPool(int maxArrayLength, int maxArraysPerBucket)
		{
			if (maxArrayLength <= 0)
			{
				throw new ArgumentOutOfRangeException("maxArrayLength");
			}
			if (maxArraysPerBucket <= 0)
			{
				throw new ArgumentOutOfRangeException("maxArraysPerBucket");
			}
			if (maxArrayLength > 1073741824)
			{
				maxArrayLength = 1073741824;
			}
			else if (maxArrayLength < 16)
			{
				maxArrayLength = 16;
			}
			int id = Id;
			int num = System.Buffers.Utilities.SelectBucketIndex(maxArrayLength);
			Bucket[] array = new Bucket[num + 1];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = new Bucket(System.Buffers.Utilities.GetMaxSizeForBucket(i), maxArraysPerBucket, id);
			}
			_buckets = array;
		}

		public override T[] Rent(int minimumLength)
		{
			if (minimumLength < 0)
			{
				throw new ArgumentOutOfRangeException("minimumLength");
			}
			if (minimumLength == 0)
			{
				return s_emptyArray ?? (s_emptyArray = new T[0]);
			}
			System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log;
			T[] array = null;
			int num = System.Buffers.Utilities.SelectBucketIndex(minimumLength);
			if (num < _buckets.Length)
			{
				int num2 = num;
				do
				{
					array = _buckets[num2].Rent();
					if (array != null)
					{
						if (log.IsEnabled())
						{
							log.BufferRented(array.GetHashCode(), array.Length, Id, _buckets[num2].Id);
						}
						return array;
					}
				}
				while (++num2 < _buckets.Length && num2 != num + 2);
				array = new T[_buckets[num]._bufferLength];
			}
			else
			{
				array = new T[minimumLength];
			}
			if (log.IsEnabled())
			{
				int hashCode = array.GetHashCode();
				int bucketId = -1;
				log.BufferRented(hashCode, array.Length, Id, bucketId);
				log.BufferAllocated(hashCode, array.Length, Id, bucketId, (num >= _buckets.Length) ? System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.OverMaximumSize : System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.PoolExhausted);
			}
			return array;
		}

		public override void Return(T[] array, bool clearArray = false)
		{
			if (array == null)
			{
				throw new ArgumentNullException("array");
			}
			if (array.Length == 0)
			{
				return;
			}
			int num = System.Buffers.Utilities.SelectBucketIndex(array.Length);
			if (num < _buckets.Length)
			{
				if (clearArray)
				{
					Array.Clear(array, 0, array.Length);
				}
				_buckets[num].Return(array);
			}
			System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log;
			if (log.IsEnabled())
			{
				log.BufferReturned(array.GetHashCode(), array.Length, Id);
			}
		}
	}
	internal static class Utilities
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static int SelectBucketIndex(int bufferSize)
		{
			uint num = (uint)(bufferSize - 1) >> 4;
			int num2 = 0;
			if (num > 65535)
			{
				num >>= 16;
				num2 = 16;
			}
			if (num > 255)
			{
				num >>= 8;
				num2 += 8;
			}
			if (num > 15)
			{
				num >>= 4;
				num2 += 4;
			}
			if (num > 3)
			{
				num >>= 2;
				num2 += 2;
			}
			if (num > 1)
			{
				num >>= 1;
				num2++;
			}
			return num2 + (int)num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static int GetMaxSizeForBucket(int binIndex)
		{
			return 16 << binIndex;
		}
	}
}

plugins/System.Memory.dll

Decompiled a day ago
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Numerics;
using System.Numerics.Hashing;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using FxResources.System.Memory;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyTitle("System.Memory")]
[assembly: AssemblyDescription("System.Memory")]
[assembly: AssemblyDefaultAlias("System.Memory")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: AssemblyCopyright("© Microsoft Corporation.  All rights reserved.")]
[assembly: AssemblyFileVersion("4.6.26515.06")]
[assembly: AssemblyInformationalVersion("4.6.26515.06 @BuiltBy: dlab-DDVSOWINAGE059 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/30ab651fcb4354552bd4891619a0bdd81e0ebdbf")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.1.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 IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsByRefLikeAttribute : Attribute
	{
	}
}
namespace FxResources.System.Memory
{
	internal static class SR
	{
	}
}
namespace System
{
	public readonly struct SequencePosition : IEquatable<SequencePosition>
	{
		private readonly object _object;

		private readonly int _integer;

		public SequencePosition(object @object, int integer)
		{
			_object = @object;
			_integer = integer;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public object GetObject()
		{
			return _object;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public int GetInteger()
		{
			return _integer;
		}

		public bool Equals(SequencePosition other)
		{
			if (_integer == other._integer)
			{
				return object.Equals(_object, other._object);
			}
			return false;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object obj)
		{
			if (obj is SequencePosition other)
			{
				return Equals(other);
			}
			return false;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			return HashHelpers.Combine(_object?.GetHashCode() ?? 0, _integer);
		}
	}
	internal static class ThrowHelper
	{
		internal static void ThrowArgumentNullException(System.ExceptionArgument argument)
		{
			throw CreateArgumentNullException(argument);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentNullException(System.ExceptionArgument argument)
		{
			return new ArgumentNullException(argument.ToString());
		}

		internal static void ThrowArrayTypeMismatchException()
		{
			throw CreateArrayTypeMismatchException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArrayTypeMismatchException()
		{
			return new ArrayTypeMismatchException();
		}

		internal static void ThrowArgumentException_InvalidTypeWithPointersNotSupported(Type type)
		{
			throw CreateArgumentException_InvalidTypeWithPointersNotSupported(type);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentException_InvalidTypeWithPointersNotSupported(Type type)
		{
			return new ArgumentException(System.SR.Format(System.SR.Argument_InvalidTypeWithPointersNotSupported, type));
		}

		internal static void ThrowArgumentException_DestinationTooShort()
		{
			throw CreateArgumentException_DestinationTooShort();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentException_DestinationTooShort()
		{
			return new ArgumentException(System.SR.Argument_DestinationTooShort);
		}

		internal static void ThrowIndexOutOfRangeException()
		{
			throw CreateIndexOutOfRangeException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateIndexOutOfRangeException()
		{
			return new IndexOutOfRangeException();
		}

		internal static void ThrowArgumentOutOfRangeException()
		{
			throw CreateArgumentOutOfRangeException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException()
		{
			return new ArgumentOutOfRangeException();
		}

		internal static void ThrowArgumentOutOfRangeException(System.ExceptionArgument argument)
		{
			throw CreateArgumentOutOfRangeException(argument);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException(System.ExceptionArgument argument)
		{
			return new ArgumentOutOfRangeException(argument.ToString());
		}

		internal static void ThrowArgumentOutOfRangeException_PrecisionTooLarge()
		{
			throw CreateArgumentOutOfRangeException_PrecisionTooLarge();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException_PrecisionTooLarge()
		{
			return new ArgumentOutOfRangeException("precision", System.SR.Format(System.SR.Argument_PrecisionTooLarge, (byte)99));
		}

		internal static void ThrowArgumentOutOfRangeException_SymbolDoesNotFit()
		{
			throw CreateArgumentOutOfRangeException_SymbolDoesNotFit();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException_SymbolDoesNotFit()
		{
			return new ArgumentOutOfRangeException("symbol", System.SR.Argument_BadFormatSpecifier);
		}

		internal static void ThrowInvalidOperationException()
		{
			throw CreateInvalidOperationException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateInvalidOperationException()
		{
			return new InvalidOperationException();
		}

		internal static void ThrowInvalidOperationException_OutstandingReferences()
		{
			throw CreateInvalidOperationException_OutstandingReferences();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateInvalidOperationException_OutstandingReferences()
		{
			return new InvalidOperationException(System.SR.OutstandingReferences);
		}

		internal static void ThrowInvalidOperationException_UnexpectedSegmentType()
		{
			throw CreateInvalidOperationException_UnexpectedSegmentType();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateInvalidOperationException_UnexpectedSegmentType()
		{
			return new InvalidOperationException(System.SR.UnexpectedSegmentType);
		}

		internal static void ThrowInvalidOperationException_EndPositionNotReached()
		{
			throw CreateInvalidOperationException_EndPositionNotReached();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateInvalidOperationException_EndPositionNotReached()
		{
			return new InvalidOperationException(System.SR.EndPositionNotReached);
		}

		internal static void ThrowArgumentOutOfRangeException_PositionOutOfRange()
		{
			throw CreateArgumentOutOfRangeException_PositionOutOfRange();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException_PositionOutOfRange()
		{
			return new ArgumentOutOfRangeException("position");
		}

		internal static void ThrowArgumentOutOfRangeException_OffsetOutOfRange()
		{
			throw CreateArgumentOutOfRangeException_OffsetOutOfRange();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException_OffsetOutOfRange()
		{
			return new ArgumentOutOfRangeException("offset");
		}

		internal static void ThrowObjectDisposedException_ArrayMemoryPoolBuffer()
		{
			throw CreateObjectDisposedException_ArrayMemoryPoolBuffer();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateObjectDisposedException_ArrayMemoryPoolBuffer()
		{
			return new ObjectDisposedException("ArrayMemoryPoolBuffer");
		}

		internal static void ThrowFormatException_BadFormatSpecifier()
		{
			throw CreateFormatException_BadFormatSpecifier();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateFormatException_BadFormatSpecifier()
		{
			return new FormatException(System.SR.Argument_BadFormatSpecifier);
		}

		internal static void ThrowArgumentException_OverlapAlignmentMismatch()
		{
			throw CreateArgumentException_OverlapAlignmentMismatch();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentException_OverlapAlignmentMismatch()
		{
			return new ArgumentException(System.SR.Argument_OverlapAlignmentMismatch);
		}

		internal static void ThrowNotSupportedException()
		{
			throw CreateThrowNotSupportedException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateThrowNotSupportedException()
		{
			return new NotSupportedException();
		}

		public static bool TryFormatThrowFormatException(out int bytesWritten)
		{
			bytesWritten = 0;
			ThrowFormatException_BadFormatSpecifier();
			return false;
		}

		public static bool TryParseThrowFormatException<T>(out T value, out int bytesConsumed)
		{
			value = default(T);
			bytesConsumed = 0;
			ThrowFormatException_BadFormatSpecifier();
			return false;
		}

		public static void ThrowArgumentValidationException<T>(ReadOnlySequenceSegment<T> startSegment, int startIndex, ReadOnlySequenceSegment<T> endSegment)
		{
			throw CreateArgumentValidationException(startSegment, startIndex, endSegment);
		}

		private static Exception CreateArgumentValidationException<T>(ReadOnlySequenceSegment<T> startSegment, int startIndex, ReadOnlySequenceSegment<T> endSegment)
		{
			if (startSegment == null)
			{
				return CreateArgumentNullException(System.ExceptionArgument.startSegment);
			}
			if (endSegment == null)
			{
				return CreateArgumentNullException(System.ExceptionArgument.endSegment);
			}
			if (startSegment != endSegment && startSegment.RunningIndex > endSegment.RunningIndex)
			{
				return CreateArgumentOutOfRangeException(System.ExceptionArgument.endSegment);
			}
			if ((uint)startSegment.Memory.Length < (uint)startIndex)
			{
				return CreateArgumentOutOfRangeException(System.ExceptionArgument.startIndex);
			}
			return CreateArgumentOutOfRangeException(System.ExceptionArgument.endIndex);
		}

		public static void ThrowArgumentValidationException(Array array, int start)
		{
			throw CreateArgumentValidationException(array, start);
		}

		private static Exception CreateArgumentValidationException(Array array, int start)
		{
			if (array == null)
			{
				return CreateArgumentNullException(System.ExceptionArgument.array);
			}
			if ((uint)start > (uint)array.Length)
			{
				return CreateArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return CreateArgumentOutOfRangeException(System.ExceptionArgument.length);
		}

		public static void ThrowStartOrEndArgumentValidationException(long start)
		{
			throw CreateStartOrEndArgumentValidationException(start);
		}

		private static Exception CreateStartOrEndArgumentValidationException(long start)
		{
			if (start < 0)
			{
				return CreateArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return CreateArgumentOutOfRangeException(System.ExceptionArgument.length);
		}
	}
	internal enum ExceptionArgument
	{
		length,
		start,
		minimumBufferSize,
		elementIndex,
		comparable,
		comparer,
		destination,
		offset,
		startSegment,
		endSegment,
		startIndex,
		endIndex,
		array,
		culture,
		manager
	}
	internal static class DecimalDecCalc
	{
		private static uint D32DivMod1E9(uint hi32, ref uint lo32)
		{
			ulong num = ((ulong)hi32 << 32) | lo32;
			lo32 = (uint)(num / 1000000000);
			return (uint)(num % 1000000000);
		}

		internal static uint DecDivMod1E9(ref MutableDecimal value)
		{
			return D32DivMod1E9(D32DivMod1E9(D32DivMod1E9(0u, ref value.High), ref value.Mid), ref value.Low);
		}

		internal static void DecAddInt32(ref MutableDecimal value, uint i)
		{
			if (D32AddCarry(ref value.Low, i) && D32AddCarry(ref value.Mid, 1u))
			{
				D32AddCarry(ref value.High, 1u);
			}
		}

		private static bool D32AddCarry(ref uint value, uint i)
		{
			uint num = value;
			uint num2 = (value = num + i);
			if (num2 >= num)
			{
				return num2 < i;
			}
			return true;
		}

		internal static void DecMul10(ref MutableDecimal value)
		{
			MutableDecimal d = value;
			DecShiftLeft(ref value);
			DecShiftLeft(ref value);
			DecAdd(ref value, d);
			DecShiftLeft(ref value);
		}

		private static void DecShiftLeft(ref MutableDecimal value)
		{
			uint num = (((value.Low & 0x80000000u) != 0) ? 1u : 0u);
			uint num2 = (((value.Mid & 0x80000000u) != 0) ? 1u : 0u);
			value.Low <<= 1;
			value.Mid = (value.Mid << 1) | num;
			value.High = (value.High << 1) | num2;
		}

		private static void DecAdd(ref MutableDecimal value, MutableDecimal d)
		{
			if (D32AddCarry(ref value.Low, d.Low) && D32AddCarry(ref value.Mid, 1u))
			{
				D32AddCarry(ref value.High, 1u);
			}
			if (D32AddCarry(ref value.Mid, d.Mid))
			{
				D32AddCarry(ref value.High, 1u);
			}
			D32AddCarry(ref value.High, d.High);
		}
	}
	internal static class Number
	{
		private static class DoubleHelper
		{
			public unsafe static uint Exponent(double d)
			{
				return (*(uint*)((byte*)(&d) + 4) >> 20) & 0x7FFu;
			}

			public unsafe static ulong Mantissa(double d)
			{
				return *(uint*)(&d) | ((ulong)(uint)(*(int*)((byte*)(&d) + 4) & 0xFFFFF) << 32);
			}

			public unsafe static bool Sign(double d)
			{
				return *(uint*)((byte*)(&d) + 4) >> 31 != 0;
			}
		}

		internal const int DECIMAL_PRECISION = 29;

		private static readonly ulong[] s_rgval64Power10 = new ulong[30]
		{
			11529215046068469760uL, 14411518807585587200uL, 18014398509481984000uL, 11258999068426240000uL, 14073748835532800000uL, 17592186044416000000uL, 10995116277760000000uL, 13743895347200000000uL, 17179869184000000000uL, 10737418240000000000uL,
			13421772800000000000uL, 16777216000000000000uL, 10485760000000000000uL, 13107200000000000000uL, 16384000000000000000uL, 14757395258967641293uL, 11805916207174113035uL, 9444732965739290428uL, 15111572745182864686uL, 12089258196146291749uL,
			9671406556917033399uL, 15474250491067253438uL, 12379400392853802751uL, 9903520314283042201uL, 15845632502852867522uL, 12676506002282294018uL, 10141204801825835215uL, 16225927682921336344uL, 12980742146337069075uL, 10384593717069655260uL
		};

		private static readonly sbyte[] s_rgexp64Power10 = new sbyte[15]
		{
			4, 7, 10, 14, 17, 20, 24, 27, 30, 34,
			37, 40, 44, 47, 50
		};

		private static readonly ulong[] s_rgval64Power10By16 = new ulong[42]
		{
			10240000000000000000uL, 11368683772161602974uL, 12621774483536188886uL, 14012984643248170708uL, 15557538194652854266uL, 17272337110188889248uL, 9588073174409622172uL, 10644899600020376798uL, 11818212630765741798uL, 13120851772591970216uL,
			14567071740625403792uL, 16172698447808779622uL, 17955302187076837696uL, 9967194951097567532uL, 11065809325636130658uL, 12285516299433008778uL, 13639663065038175358uL, 15143067982934716296uL, 16812182738118149112uL, 9332636185032188787uL,
			10361307573072618722uL, 16615349947311448416uL, 14965776766268445891uL, 13479973333575319909uL, 12141680576410806707uL, 10936253623915059637uL, 9850501549098619819uL, 17745086042373215136uL, 15983352577617880260uL, 14396524142538228461uL,
			12967236152753103031uL, 11679847981112819795uL, 10520271803096747049uL, 9475818434452569218uL, 17070116948172427008uL, 15375394465392026135uL, 13848924157002783096uL, 12474001934591998882uL, 11235582092889474480uL, 10120112665365530972uL,
			18230774251475056952uL, 16420821625123739930uL
		};

		private static readonly short[] s_rgexp64Power10By16 = new short[21]
		{
			54, 107, 160, 213, 266, 319, 373, 426, 479, 532,
			585, 638, 691, 745, 798, 851, 904, 957, 1010, 1064,
			1117
		};

		public static void RoundNumber(ref NumberBuffer number, int pos)
		{
			Span<byte> digits = number.Digits;
			int i;
			for (i = 0; i < pos && digits[i] != 0; i++)
			{
			}
			if (i == pos && digits[i] >= 53)
			{
				while (i > 0 && digits[i - 1] == 57)
				{
					i--;
				}
				if (i > 0)
				{
					digits[i - 1]++;
				}
				else
				{
					number.Scale++;
					digits[0] = 49;
					i = 1;
				}
			}
			else
			{
				while (i > 0 && digits[i - 1] == 48)
				{
					i--;
				}
			}
			if (i == 0)
			{
				number.Scale = 0;
				number.IsNegative = false;
			}
			digits[i] = 0;
		}

		internal static bool NumberBufferToDouble(ref NumberBuffer number, out double value)
		{
			double num = NumberToDouble(ref number);
			uint num2 = DoubleHelper.Exponent(num);
			ulong num3 = DoubleHelper.Mantissa(num);
			switch (num2)
			{
			case 2047u:
				value = 0.0;
				return false;
			case 0u:
				if (num3 == 0L)
				{
					num = 0.0;
				}
				break;
			}
			value = num;
			return true;
		}

		public unsafe static bool NumberBufferToDecimal(ref NumberBuffer number, ref decimal value)
		{
			MutableDecimal source = default(MutableDecimal);
			byte* ptr = number.UnsafeDigits;
			int num = number.Scale;
			if (*ptr == 0)
			{
				if (num > 0)
				{
					num = 0;
				}
			}
			else
			{
				if (num > 29)
				{
					return false;
				}
				while ((num > 0 || (*ptr != 0 && num > -28)) && (source.High < 429496729 || (source.High == 429496729 && (source.Mid < 2576980377u || (source.Mid == 2576980377u && (source.Low < 2576980377u || (source.Low == 2576980377u && *ptr <= 53)))))))
				{
					DecimalDecCalc.DecMul10(ref source);
					if (*ptr != 0)
					{
						DecimalDecCalc.DecAddInt32(ref source, (uint)(*(ptr++) - 48));
					}
					num--;
				}
				if (*(ptr++) >= 53)
				{
					bool flag = true;
					if (*(ptr - 1) == 53 && *(ptr - 2) % 2 == 0)
					{
						int num2 = 20;
						while (*ptr == 48 && num2 != 0)
						{
							ptr++;
							num2--;
						}
						if (*ptr == 0 || num2 == 0)
						{
							flag = false;
						}
					}
					if (flag)
					{
						DecimalDecCalc.DecAddInt32(ref source, 1u);
						if ((source.High | source.Mid | source.Low) == 0)
						{
							source.High = 429496729u;
							source.Mid = 2576980377u;
							source.Low = 2576980378u;
							num++;
						}
					}
				}
			}
			if (num > 0)
			{
				return false;
			}
			if (num <= -29)
			{
				source.High = 0u;
				source.Low = 0u;
				source.Mid = 0u;
				source.Scale = 28;
			}
			else
			{
				source.Scale = -num;
			}
			source.IsNegative = number.IsNegative;
			value = Unsafe.As<MutableDecimal, decimal>(ref source);
			return true;
		}

		public static void DecimalToNumber(decimal value, ref NumberBuffer number)
		{
			ref MutableDecimal reference = ref Unsafe.As<decimal, MutableDecimal>(ref value);
			Span<byte> digits = number.Digits;
			number.IsNegative = reference.IsNegative;
			int num = 29;
			while ((reference.Mid != 0) | (reference.High != 0))
			{
				uint num2 = DecimalDecCalc.DecDivMod1E9(ref reference);
				for (int i = 0; i < 9; i++)
				{
					digits[--num] = (byte)(num2 % 10 + 48);
					num2 /= 10;
				}
			}
			for (uint num3 = reference.Low; num3 != 0; num3 /= 10)
			{
				digits[--num] = (byte)(num3 % 10 + 48);
			}
			int num4 = 29 - num;
			number.Scale = num4 - reference.Scale;
			Span<byte> digits2 = number.Digits;
			int index = 0;
			while (--num4 >= 0)
			{
				digits2[index++] = digits[num++];
			}
			digits2[index] = 0;
		}

		private static uint DigitsToInt(ReadOnlySpan<byte> digits, int count)
		{
			uint value;
			int bytesConsumed;
			bool flag = Utf8Parser.TryParse(digits.Slice(0, count), out value, out bytesConsumed, 'D');
			return value;
		}

		private static ulong Mul32x32To64(uint a, uint b)
		{
			return (ulong)a * (ulong)b;
		}

		private static ulong Mul64Lossy(ulong a, ulong b, ref int pexp)
		{
			ulong num = Mul32x32To64((uint)(a >> 32), (uint)(b >> 32)) + (Mul32x32To64((uint)(a >> 32), (uint)b) >> 32) + (Mul32x32To64((uint)a, (uint)(b >> 32)) >> 32);
			if ((num & 0x8000000000000000uL) == 0L)
			{
				num <<= 1;
				pexp--;
			}
			return num;
		}

		private static int abs(int value)
		{
			if (value < 0)
			{
				return -value;
			}
			return value;
		}

		private unsafe static double NumberToDouble(ref NumberBuffer number)
		{
			ReadOnlySpan<byte> digits = number.Digits;
			int i = 0;
			int numDigits = number.NumDigits;
			int num = numDigits;
			for (; digits[i] == 48; i++)
			{
				num--;
			}
			if (num == 0)
			{
				return 0.0;
			}
			int num2 = Math.Min(num, 9);
			num -= num2;
			ulong num3 = DigitsToInt(digits, num2);
			if (num > 0)
			{
				num2 = Math.Min(num, 9);
				num -= num2;
				uint b = (uint)(s_rgval64Power10[num2 - 1] >> 64 - s_rgexp64Power10[num2 - 1]);
				num3 = Mul32x32To64((uint)num3, b) + DigitsToInt(digits.Slice(9), num2);
			}
			int num4 = number.Scale - (numDigits - num);
			int num5 = abs(num4);
			if (num5 >= 352)
			{
				ulong num6 = ((num4 > 0) ? 9218868437227405312uL : 0);
				if (number.IsNegative)
				{
					num6 |= 0x8000000000000000uL;
				}
				return *(double*)(&num6);
			}
			int pexp = 64;
			if ((num3 & 0xFFFFFFFF00000000uL) == 0L)
			{
				num3 <<= 32;
				pexp -= 32;
			}
			if ((num3 & 0xFFFF000000000000uL) == 0L)
			{
				num3 <<= 16;
				pexp -= 16;
			}
			if ((num3 & 0xFF00000000000000uL) == 0L)
			{
				num3 <<= 8;
				pexp -= 8;
			}
			if ((num3 & 0xF000000000000000uL) == 0L)
			{
				num3 <<= 4;
				pexp -= 4;
			}
			if ((num3 & 0xC000000000000000uL) == 0L)
			{
				num3 <<= 2;
				pexp -= 2;
			}
			if ((num3 & 0x8000000000000000uL) == 0L)
			{
				num3 <<= 1;
				pexp--;
			}
			int num7 = num5 & 0xF;
			if (num7 != 0)
			{
				int num8 = s_rgexp64Power10[num7 - 1];
				pexp += ((num4 < 0) ? (-num8 + 1) : num8);
				ulong b2 = s_rgval64Power10[num7 + ((num4 < 0) ? 15 : 0) - 1];
				num3 = Mul64Lossy(num3, b2, ref pexp);
			}
			num7 = num5 >> 4;
			if (num7 != 0)
			{
				int num9 = s_rgexp64Power10By16[num7 - 1];
				pexp += ((num4 < 0) ? (-num9 + 1) : num9);
				ulong b3 = s_rgval64Power10By16[num7 + ((num4 < 0) ? 21 : 0) - 1];
				num3 = Mul64Lossy(num3, b3, ref pexp);
			}
			if (((uint)(int)num3 & 0x400u) != 0)
			{
				ulong num10 = num3 + 1023 + (ulong)(((int)num3 >> 11) & 1);
				if (num10 < num3)
				{
					num10 = (num10 >> 1) | 0x8000000000000000uL;
					pexp++;
				}
				num3 = num10;
			}
			pexp += 1022;
			num3 = ((pexp <= 0) ? ((pexp == -52 && num3 >= 9223372036854775896uL) ? 1 : ((pexp > -52) ? (num3 >> -pexp + 11 + 1) : 0)) : ((pexp < 2047) ? ((ulong)((long)pexp << 52) + ((num3 >> 11) & 0xFFFFFFFFFFFFFL)) : 9218868437227405312uL));
			if (number.IsNegative)
			{
				num3 |= 0x8000000000000000uL;
			}
			return *(double*)(&num3);
		}
	}
	internal ref struct NumberBuffer
	{
		public int Scale;

		public bool IsNegative;

		public const int BufferSize = 51;

		private byte _b0;

		private byte _b1;

		private byte _b2;

		private byte _b3;

		private byte _b4;

		private byte _b5;

		private byte _b6;

		private byte _b7;

		private byte _b8;

		private byte _b9;

		private byte _b10;

		private byte _b11;

		private byte _b12;

		private byte _b13;

		private byte _b14;

		private byte _b15;

		private byte _b16;

		private byte _b17;

		private byte _b18;

		private byte _b19;

		private byte _b20;

		private byte _b21;

		private byte _b22;

		private byte _b23;

		private byte _b24;

		private byte _b25;

		private byte _b26;

		private byte _b27;

		private byte _b28;

		private byte _b29;

		private byte _b30;

		private byte _b31;

		private byte _b32;

		private byte _b33;

		private byte _b34;

		private byte _b35;

		private byte _b36;

		private byte _b37;

		private byte _b38;

		private byte _b39;

		private byte _b40;

		private byte _b41;

		private byte _b42;

		private byte _b43;

		private byte _b44;

		private byte _b45;

		private byte _b46;

		private byte _b47;

		private byte _b48;

		private byte _b49;

		private byte _b50;

		public unsafe Span<byte> Digits => new Span<byte>(Unsafe.AsPointer(ref _b0), 51);

		public unsafe byte* UnsafeDigits => (byte*)Unsafe.AsPointer(ref _b0);

		public int NumDigits => Digits.IndexOf<byte>(0);

		[Conditional("DEBUG")]
		public void CheckConsistency()
		{
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append('[');
			stringBuilder.Append('"');
			Span<byte> digits = Digits;
			for (int i = 0; i < 51; i++)
			{
				byte b = digits[i];
				if (b == 0)
				{
					break;
				}
				stringBuilder.Append((char)b);
			}
			stringBuilder.Append('"');
			stringBuilder.Append(", Scale = " + Scale);
			stringBuilder.Append(", IsNegative   = " + IsNegative);
			stringBuilder.Append(']');
			return stringBuilder.ToString();
		}
	}
	[DebuggerTypeProxy(typeof(System.MemoryDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	public readonly struct Memory<T>
	{
		private readonly object _object;

		private readonly int _index;

		private readonly int _length;

		private const int RemoveFlagsBitMask = int.MaxValue;

		public static Memory<T> Empty => default(Memory<T>);

		public int Length => _length & 0x7FFFFFFF;

		public bool IsEmpty => (_length & 0x7FFFFFFF) == 0;

		public Span<T> Span
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				Span<T> result;
				if (_index < 0)
				{
					result = ((MemoryManager<T>)_object).GetSpan();
					return result.Slice(_index & 0x7FFFFFFF, _length);
				}
				if (typeof(T) == typeof(char) && _object is string text)
				{
					result = new Span<T>(Unsafe.As<Pinnable<T>>(text), MemoryExtensions.StringAdjustment, text.Length);
					return result.Slice(_index, _length);
				}
				if (_object != null)
				{
					return new Span<T>((T[])_object, _index, _length & 0x7FFFFFFF);
				}
				result = default(Span<T>);
				return result;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Memory(T[] array)
		{
			if (array == null)
			{
				this = default(Memory<T>);
				return;
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			_object = array;
			_index = 0;
			_length = array.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal Memory(T[] array, int start)
		{
			if (array == null)
			{
				if (start != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException();
				}
				this = default(Memory<T>);
				return;
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			if ((uint)start > (uint)array.Length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			_object = array;
			_index = start;
			_length = array.Length - start;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Memory(T[] array, int start, int length)
		{
			if (array == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException();
				}
				this = default(Memory<T>);
				return;
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			_object = array;
			_index = start;
			_length = length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal Memory(MemoryManager<T> manager, int length)
		{
			if (length < 0)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			_object = manager;
			_index = int.MinValue;
			_length = length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal Memory(MemoryManager<T> manager, int start, int length)
		{
			if (length < 0 || start < 0)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			_object = manager;
			_index = start | int.MinValue;
			_length = length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal Memory(object obj, int start, int length)
		{
			_object = obj;
			_index = start;
			_length = length;
		}

		public static implicit operator Memory<T>(T[] array)
		{
			return new Memory<T>(array);
		}

		public static implicit operator Memory<T>(ArraySegment<T> segment)
		{
			return new Memory<T>(segment.Array, segment.Offset, segment.Count);
		}

		public static implicit operator ReadOnlyMemory<T>(Memory<T> memory)
		{
			return Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory);
		}

		public override string ToString()
		{
			if (typeof(T) == typeof(char))
			{
				if (!(_object is string text))
				{
					return Span.ToString();
				}
				return text.Substring(_index, _length & 0x7FFFFFFF);
			}
			return $"System.Memory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]";
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Memory<T> Slice(int start)
		{
			int length = _length;
			int num = length & 0x7FFFFFFF;
			if ((uint)start > (uint)num)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new Memory<T>(_object, _index + start, length - start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Memory<T> Slice(int start, int length)
		{
			int length2 = _length;
			int num = length2 & 0x7FFFFFFF;
			if ((uint)start > (uint)num || (uint)length > (uint)(num - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			return new Memory<T>(_object, _index + start, length | (length2 & int.MinValue));
		}

		public void CopyTo(Memory<T> destination)
		{
			Span.CopyTo(destination.Span);
		}

		public bool TryCopyTo(Memory<T> destination)
		{
			return Span.TryCopyTo(destination.Span);
		}

		public unsafe MemoryHandle Pin()
		{
			if (_index < 0)
			{
				return ((MemoryManager<T>)_object).Pin(_index & 0x7FFFFFFF);
			}
			if (typeof(T) == typeof(char) && _object is string value)
			{
				GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned);
				void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
				return new MemoryHandle(pointer, handle);
			}
			if (_object is T[] array)
			{
				if (_length < 0)
				{
					void* pointer2 = Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetReference<T>(array)), _index);
					return new MemoryHandle(pointer2);
				}
				GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned);
				void* pointer3 = Unsafe.Add<T>((void*)handle2.AddrOfPinnedObject(), _index);
				return new MemoryHandle(pointer3, handle2);
			}
			return default(MemoryHandle);
		}

		public T[] ToArray()
		{
			return Span.ToArray();
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object obj)
		{
			if (obj is ReadOnlyMemory<T> readOnlyMemory)
			{
				return readOnlyMemory.Equals(this);
			}
			if (obj is Memory<T> other)
			{
				return Equals(other);
			}
			return false;
		}

		public bool Equals(Memory<T> other)
		{
			if (_object == other._object && _index == other._index)
			{
				return _length == other._length;
			}
			return false;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			if (_object == null)
			{
				return 0;
			}
			int hashCode = _object.GetHashCode();
			int index = _index;
			int hashCode2 = index.GetHashCode();
			index = _length;
			return CombineHashCodes(hashCode, hashCode2, index.GetHashCode());
		}

		private static int CombineHashCodes(int left, int right)
		{
			return ((left << 5) + left) ^ right;
		}

		private static int CombineHashCodes(int h1, int h2, int h3)
		{
			return CombineHashCodes(CombineHashCodes(h1, h2), h3);
		}
	}
	internal sealed class MemoryDebugView<T>
	{
		private readonly ReadOnlyMemory<T> _memory;

		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		public T[] Items => _memory.ToArray();

		public MemoryDebugView(Memory<T> memory)
		{
			_memory = memory;
		}

		public MemoryDebugView(ReadOnlyMemory<T> memory)
		{
			_memory = memory;
		}
	}
	public static class MemoryExtensions
	{
		internal static readonly IntPtr StringAdjustment = MeasureStringAdjustment();

		public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span)
		{
			return span.TrimStart().TrimEnd();
		}

		public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span)
		{
			int i;
			for (i = 0; i < span.Length && char.IsWhiteSpace(span[i]); i++)
			{
			}
			return span.Slice(i);
		}

		public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span)
		{
			int num = span.Length - 1;
			while (num >= 0 && char.IsWhiteSpace(span[num]))
			{
				num--;
			}
			return span.Slice(0, num + 1);
		}

		public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span, char trimChar)
		{
			return span.TrimStart(trimChar).TrimEnd(trimChar);
		}

		public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span, char trimChar)
		{
			int i;
			for (i = 0; i < span.Length && span[i] == trimChar; i++)
			{
			}
			return span.Slice(i);
		}

		public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span, char trimChar)
		{
			int num = span.Length - 1;
			while (num >= 0 && span[num] == trimChar)
			{
				num--;
			}
			return span.Slice(0, num + 1);
		}

		public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars)
		{
			return span.TrimStart(trimChars).TrimEnd(trimChars);
		}

		public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars)
		{
			if (trimChars.IsEmpty)
			{
				return span.TrimStart();
			}
			int i;
			for (i = 0; i < span.Length; i++)
			{
				int num = 0;
				while (num < trimChars.Length)
				{
					if (span[i] != trimChars[num])
					{
						num++;
						continue;
					}
					goto IL_003c;
				}
				break;
				IL_003c:;
			}
			return span.Slice(i);
		}

		public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars)
		{
			if (trimChars.IsEmpty)
			{
				return span.TrimEnd();
			}
			int num;
			for (num = span.Length - 1; num >= 0; num--)
			{
				int num2 = 0;
				while (num2 < trimChars.Length)
				{
					if (span[num] != trimChars[num2])
					{
						num2++;
						continue;
					}
					goto IL_0044;
				}
				break;
				IL_0044:;
			}
			return span.Slice(0, num + 1);
		}

		public static bool IsWhiteSpace(this ReadOnlySpan<char> span)
		{
			for (int i = 0; i < span.Length; i++)
			{
				if (!char.IsWhiteSpace(span[i]))
				{
					return false;
				}
			}
			return true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOf<T>(this Span<T> span, T value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.IndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length);
			}
			return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length);
			}
			return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOf<T>(this Span<T> span, T value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length);
			}
			return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length);
			}
			return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool SequenceEqual<T>(this Span<T> span, ReadOnlySpan<T> other) where T : IEquatable<T>
		{
			int length = span.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length == other.Length)
				{
					return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), (NUInt)length * size);
				}
				return false;
			}
			if (length == other.Length)
			{
				return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length);
			}
			return false;
		}

		public static int SequenceCompareTo<T>(this Span<T> span, ReadOnlySpan<T> other) where T : IComparable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(other)), other.Length);
			}
			return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOf<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.IndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length);
			}
			return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length);
			}
			return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOf<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, char>(ref value), span.Length);
			}
			return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length);
			}
			return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this Span<T> span, T value0, T value1) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this Span<T> span, T value0, T value1, T value2) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this Span<T> span, ReadOnlySpan<T> values) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1, T value2) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> values) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this Span<T> span, T value0, T value1) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this Span<T> span, T value0, T value1, T value2) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this Span<T> span, ReadOnlySpan<T> values) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), span.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1, T value2) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), Unsafe.As<T, byte>(ref value2), span.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> values) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool SequenceEqual<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) where T : IEquatable<T>
		{
			int length = span.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length == other.Length)
				{
					return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), (NUInt)length * size);
				}
				return false;
			}
			if (length == other.Length)
			{
				return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length);
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int SequenceCompareTo<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) where T : IComparable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(other)), other.Length);
			}
			return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool StartsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			int length = value.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length <= span.Length)
				{
					return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length * size);
				}
				return false;
			}
			if (length <= span.Length)
			{
				return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length);
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool StartsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			int length = value.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length <= span.Length)
				{
					return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length * size);
				}
				return false;
			}
			if (length <= span.Length)
			{
				return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length);
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool EndsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			int length = span.Length;
			int length2 = value.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length2 <= length)
				{
					return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size);
				}
				return false;
			}
			if (length2 <= length)
			{
				return System.SpanHelpers.SequenceEqual(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2);
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool EndsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			int length = span.Length;
			int length2 = value.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length2 <= length)
				{
					return System.SpanHelpers.SequenceEqual(ref Unsafe.As<T, byte>(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size);
				}
				return false;
			}
			if (length2 <= length)
			{
				return System.SpanHelpers.SequenceEqual(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2);
			}
			return false;
		}

		public static void Reverse<T>(this Span<T> span)
		{
			ref T reference = ref MemoryMarshal.GetReference(span);
			int num = 0;
			int num2 = span.Length - 1;
			while (num < num2)
			{
				T val = Unsafe.Add(ref reference, num);
				Unsafe.Add(ref reference, num) = Unsafe.Add(ref reference, num2);
				Unsafe.Add(ref reference, num2) = val;
				num++;
				num2--;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Span<T> AsSpan<T>(this T[] array)
		{
			return new Span<T>(array);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Span<T> AsSpan<T>(this T[] array, int start, int length)
		{
			return new Span<T>(array, start, length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Span<T> AsSpan<T>(this ArraySegment<T> segment)
		{
			return new Span<T>(segment.Array, segment.Offset, segment.Count);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Span<T> AsSpan<T>(this ArraySegment<T> segment, int start)
		{
			if ((uint)start > segment.Count)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new Span<T>(segment.Array, segment.Offset + start, segment.Count - start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Span<T> AsSpan<T>(this ArraySegment<T> segment, int start, int length)
		{
			if ((uint)start > segment.Count)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			if ((uint)length > segment.Count - start)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length);
			}
			return new Span<T>(segment.Array, segment.Offset + start, length);
		}

		public static Memory<T> AsMemory<T>(this T[] array)
		{
			return new Memory<T>(array);
		}

		public static Memory<T> AsMemory<T>(this T[] array, int start)
		{
			return new Memory<T>(array, start);
		}

		public static Memory<T> AsMemory<T>(this T[] array, int start, int length)
		{
			return new Memory<T>(array, start, length);
		}

		public static Memory<T> AsMemory<T>(this ArraySegment<T> segment)
		{
			return new Memory<T>(segment.Array, segment.Offset, segment.Count);
		}

		public static Memory<T> AsMemory<T>(this ArraySegment<T> segment, int start)
		{
			if ((uint)start > segment.Count)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new Memory<T>(segment.Array, segment.Offset + start, segment.Count - start);
		}

		public static Memory<T> AsMemory<T>(this ArraySegment<T> segment, int start, int length)
		{
			if ((uint)start > segment.Count)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			if ((uint)length > segment.Count - start)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length);
			}
			return new Memory<T>(segment.Array, segment.Offset + start, length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void CopyTo<T>(this T[] source, Span<T> destination)
		{
			new ReadOnlySpan<T>(source).CopyTo(destination);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void CopyTo<T>(this T[] source, Memory<T> destination)
		{
			source.CopyTo(destination.Span);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool Overlaps<T>(this Span<T> span, ReadOnlySpan<T> other)
		{
			return ((ReadOnlySpan<T>)span).Overlaps(other);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool Overlaps<T>(this Span<T> span, ReadOnlySpan<T> other, out int elementOffset)
		{
			return ((ReadOnlySpan<T>)span).Overlaps(other, out elementOffset);
		}

		public static bool Overlaps<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other)
		{
			if (span.IsEmpty || other.IsEmpty)
			{
				return false;
			}
			IntPtr intPtr = Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other));
			if (Unsafe.SizeOf<IntPtr>() == 4)
			{
				if ((uint)(int)intPtr >= (uint)(span.Length * Unsafe.SizeOf<T>()))
				{
					return (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf<T>()));
				}
				return true;
			}
			if ((ulong)(long)intPtr >= (ulong)((long)span.Length * (long)Unsafe.SizeOf<T>()))
			{
				return (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf<T>()));
			}
			return true;
		}

		public static bool Overlaps<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other, out int elementOffset)
		{
			if (span.IsEmpty || other.IsEmpty)
			{
				elementOffset = 0;
				return false;
			}
			IntPtr intPtr = Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other));
			if (Unsafe.SizeOf<IntPtr>() == 4)
			{
				if ((uint)(int)intPtr < (uint)(span.Length * Unsafe.SizeOf<T>()) || (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf<T>())))
				{
					if ((int)intPtr % Unsafe.SizeOf<T>() != 0)
					{
						System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch();
					}
					elementOffset = (int)intPtr / Unsafe.SizeOf<T>();
					return true;
				}
				elementOffset = 0;
				return false;
			}
			if ((ulong)(long)intPtr < (ulong)((long)span.Length * (long)Unsafe.SizeOf<T>()) || (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf<T>())))
			{
				if ((long)intPtr % Unsafe.SizeOf<T>() != 0L)
				{
					System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch();
				}
				elementOffset = (int)((long)intPtr / Unsafe.SizeOf<T>());
				return true;
			}
			elementOffset = 0;
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T>(this Span<T> span, IComparable<T> comparable)
		{
			return span.BinarySearch<T, IComparable<T>>(comparable);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T, TComparable>(this Span<T> span, TComparable comparable) where TComparable : IComparable<T>
		{
			return BinarySearch((ReadOnlySpan<T>)span, comparable);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T, TComparer>(this Span<T> span, T value, TComparer comparer) where TComparer : IComparer<T>
		{
			return ((ReadOnlySpan<T>)span).BinarySearch(value, comparer);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T>(this ReadOnlySpan<T> span, IComparable<T> comparable)
		{
			return MemoryExtensions.BinarySearch<T, IComparable<T>>(span, comparable);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T, TComparable>(this ReadOnlySpan<T> span, TComparable comparable) where TComparable : IComparable<T>
		{
			return System.SpanHelpers.BinarySearch(span, comparable);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T, TComparer>(this ReadOnlySpan<T> span, T value, TComparer comparer) where TComparer : IComparer<T>
		{
			if (comparer == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparer);
			}
			System.SpanHelpers.ComparerComparable<T, TComparer> comparable = new System.SpanHelpers.ComparerComparable<T, TComparer>(value, comparer);
			return BinarySearch(span, comparable);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static bool IsTypeComparableAsBytes<T>(out NUInt size)
		{
			if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte))
			{
				size = (NUInt)1;
				return true;
			}
			if (typeof(T) == typeof(char) || typeof(T) == typeof(short) || typeof(T) == typeof(ushort))
			{
				size = (NUInt)2;
				return true;
			}
			if (typeof(T) == typeof(int) || typeof(T) == typeof(uint))
			{
				size = (NUInt)4;
				return true;
			}
			if (typeof(T) == typeof(long) || typeof(T) == typeof(ulong))
			{
				size = (NUInt)8;
				return true;
			}
			size = default(NUInt);
			return false;
		}

		public static Span<T> AsSpan<T>(this T[] array, int start)
		{
			return Span<T>.Create(array, start);
		}

		public static bool Contains(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
		{
			return span.IndexOf(value, comparisonType) >= 0;
		}

		public static bool Equals(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType)
		{
			switch (comparisonType)
			{
			case StringComparison.Ordinal:
				return span.SequenceEqual(other);
			case StringComparison.OrdinalIgnoreCase:
				if (span.Length != other.Length)
				{
					return false;
				}
				return EqualsOrdinalIgnoreCase(span, other);
			default:
				return span.ToString().Equals(other.ToString(), comparisonType);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static bool EqualsOrdinalIgnoreCase(ReadOnlySpan<char> span, ReadOnlySpan<char> other)
		{
			if (other.Length == 0)
			{
				return true;
			}
			return CompareToOrdinalIgnoreCase(span, other) == 0;
		}

		public static int CompareTo(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType)
		{
			return comparisonType switch
			{
				StringComparison.Ordinal => span.SequenceCompareTo(other), 
				StringComparison.OrdinalIgnoreCase => CompareToOrdinalIgnoreCase(span, other), 
				_ => string.Compare(span.ToString(), other.ToString(), comparisonType), 
			};
		}

		private unsafe static int CompareToOrdinalIgnoreCase(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB)
		{
			int num = Math.Min(strA.Length, strB.Length);
			int num2 = num;
			fixed (char* ptr = &MemoryMarshal.GetReference(strA))
			{
				fixed (char* ptr3 = &MemoryMarshal.GetReference(strB))
				{
					char* ptr2 = ptr;
					char* ptr4 = ptr3;
					while (num != 0 && *ptr2 <= '\u007f' && *ptr4 <= '\u007f')
					{
						int num3 = *ptr2;
						int num4 = *ptr4;
						if (num3 == num4)
						{
							ptr2++;
							ptr4++;
							num--;
							continue;
						}
						if ((uint)(num3 - 97) <= 25u)
						{
							num3 -= 32;
						}
						if ((uint)(num4 - 97) <= 25u)
						{
							num4 -= 32;
						}
						if (num3 != num4)
						{
							return num3 - num4;
						}
						ptr2++;
						ptr4++;
						num--;
					}
					if (num == 0)
					{
						return strA.Length - strB.Length;
					}
					num2 -= num;
					return string.Compare(strA.Slice(num2).ToString(), strB.Slice(num2).ToString(), StringComparison.OrdinalIgnoreCase);
				}
			}
		}

		public static int IndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
		{
			if (comparisonType == StringComparison.Ordinal)
			{
				return span.IndexOf(value);
			}
			return span.ToString().IndexOf(value.ToString(), comparisonType);
		}

		public static int ToLower(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture)
		{
			if (culture == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture);
			}
			if (destination.Length < source.Length)
			{
				return -1;
			}
			string text = source.ToString();
			string text2 = text.ToLower(culture);
			AsSpan(text2).CopyTo(destination);
			return source.Length;
		}

		public static int ToLowerInvariant(this ReadOnlySpan<char> source, Span<char> destination)
		{
			return source.ToLower(destination, CultureInfo.InvariantCulture);
		}

		public static int ToUpper(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture)
		{
			if (culture == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture);
			}
			if (destination.Length < source.Length)
			{
				return -1;
			}
			string text = source.ToString();
			string text2 = text.ToUpper(culture);
			AsSpan(text2).CopyTo(destination);
			return source.Length;
		}

		public static int ToUpperInvariant(this ReadOnlySpan<char> source, Span<char> destination)
		{
			return source.ToUpper(destination, CultureInfo.InvariantCulture);
		}

		public static bool EndsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
		{
			switch (comparisonType)
			{
			case StringComparison.Ordinal:
				return span.EndsWith(value);
			case StringComparison.OrdinalIgnoreCase:
				if (value.Length <= span.Length)
				{
					return EqualsOrdinalIgnoreCase(span.Slice(span.Length - value.Length), value);
				}
				return false;
			default:
			{
				string text = span.ToString();
				string value2 = value.ToString();
				return text.EndsWith(value2, comparisonType);
			}
			}
		}

		public static bool StartsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
		{
			switch (comparisonType)
			{
			case StringComparison.Ordinal:
				return span.StartsWith(value);
			case StringComparison.OrdinalIgnoreCase:
				if (value.Length <= span.Length)
				{
					return EqualsOrdinalIgnoreCase(span.Slice(0, value.Length), value);
				}
				return false;
			default:
			{
				string text = span.ToString();
				string value2 = value.ToString();
				return text.StartsWith(value2, comparisonType);
			}
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ReadOnlySpan<char> AsSpan(this string text)
		{
			if (text == null)
			{
				return default(ReadOnlySpan<char>);
			}
			return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), StringAdjustment, text.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ReadOnlySpan<char> AsSpan(this string text, int start)
		{
			if (text == null)
			{
				if (start != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				return default(ReadOnlySpan<char>);
			}
			if ((uint)start > (uint)text.Length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), StringAdjustment + start * 2, text.Length - start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ReadOnlySpan<char> AsSpan(this string text, int start, int length)
		{
			if (text == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				return default(ReadOnlySpan<char>);
			}
			if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), StringAdjustment + start * 2, length);
		}

		public static ReadOnlyMemory<char> AsMemory(this string text)
		{
			if (text == null)
			{
				return default(ReadOnlyMemory<char>);
			}
			return new ReadOnlyMemory<char>(text, 0, text.Length);
		}

		public static ReadOnlyMemory<char> AsMemory(this string text, int start)
		{
			if (text == null)
			{
				if (start != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				return default(ReadOnlyMemory<char>);
			}
			if ((uint)start > (uint)text.Length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlyMemory<char>(text, start, text.Length - start);
		}

		public static ReadOnlyMemory<char> AsMemory(this string text, int start, int length)
		{
			if (text == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				return default(ReadOnlyMemory<char>);
			}
			if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlyMemory<char>(text, start, length);
		}

		private unsafe static IntPtr MeasureStringAdjustment()
		{
			string text = "a";
			fixed (char* source = text)
			{
				return Unsafe.ByteOffset(ref Unsafe.As<Pinnable<char>>(text).Data, ref Unsafe.AsRef<char>(source));
			}
		}
	}
	[DebuggerTypeProxy(typeof(System.MemoryDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	public readonly struct ReadOnlyMemory<T>
	{
		private readonly object _object;

		private readonly int _index;

		private readonly int _length;

		internal const int RemoveFlagsBitMask = int.MaxValue;

		public static ReadOnlyMemory<T> Empty => default(ReadOnlyMemory<T>);

		public int Length => _length & 0x7FFFFFFF;

		public bool IsEmpty => (_length & 0x7FFFFFFF) == 0;

		public ReadOnlySpan<T> Span
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				if (_index < 0)
				{
					return ((MemoryManager<T>)_object).GetSpan().Slice(_index & 0x7FFFFFFF, _length);
				}
				ReadOnlySpan<T> result;
				if (typeof(T) == typeof(char) && _object is string text)
				{
					result = new ReadOnlySpan<T>(Unsafe.As<Pinnable<T>>(text), MemoryExtensions.StringAdjustment, text.Length);
					return result.Slice(_index, _length);
				}
				if (_object != null)
				{
					return new ReadOnlySpan<T>((T[])_object, _index, _length & 0x7FFFFFFF);
				}
				result = default(ReadOnlySpan<T>);
				return result;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlyMemory(T[] array)
		{
			if (array == null)
			{
				this = default(ReadOnlyMemory<T>);
				return;
			}
			_object = array;
			_index = 0;
			_length = array.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlyMemory(T[] array, int start, int length)
		{
			if (array == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException();
				}
				this = default(ReadOnlyMemory<T>);
				return;
			}
			if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			_object = array;
			_index = start;
			_length = length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal ReadOnlyMemory(object obj, int start, int length)
		{
			_object = obj;
			_index = start;
			_length = length;
		}

		public static implicit operator ReadOnlyMemory<T>(T[] array)
		{
			return new ReadOnlyMemory<T>(array);
		}

		public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> segment)
		{
			return new ReadOnlyMemory<T>(segment.Array, segment.Offset, segment.Count);
		}

		public override string ToString()
		{
			if (typeof(T) == typeof(char))
			{
				if (!(_object is string text))
				{
					return Span.ToString();
				}
				return text.Substring(_index, _length & 0x7FFFFFFF);
			}
			return $"System.ReadOnlyMemory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]";
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlyMemory<T> Slice(int start)
		{
			int length = _length;
			int num = length & 0x7FFFFFFF;
			if ((uint)start > (uint)num)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlyMemory<T>(_object, _index + start, length - start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlyMemory<T> Slice(int start, int length)
		{
			int length2 = _length;
			int num = _length & 0x7FFFFFFF;
			if ((uint)start > (uint)num || (uint)length > (uint)(num - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlyMemory<T>(_object, _index + start, length | (length2 & int.MinValue));
		}

		public void CopyTo(Memory<T> destination)
		{
			Span.CopyTo(destination.Span);
		}

		public bool TryCopyTo(Memory<T> destination)
		{
			return Span.TryCopyTo(destination.Span);
		}

		public unsafe MemoryHandle Pin()
		{
			if (_index < 0)
			{
				return ((MemoryManager<T>)_object).Pin(_index & 0x7FFFFFFF);
			}
			if (typeof(T) == typeof(char) && _object is string value)
			{
				GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned);
				void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
				return new MemoryHandle(pointer, handle);
			}
			if (_object is T[] array)
			{
				if (_length < 0)
				{
					void* pointer2 = Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetReference<T>(array)), _index);
					return new MemoryHandle(pointer2);
				}
				GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned);
				void* pointer3 = Unsafe.Add<T>((void*)handle2.AddrOfPinnedObject(), _index);
				return new MemoryHandle(pointer3, handle2);
			}
			return default(MemoryHandle);
		}

		public T[] ToArray()
		{
			return Span.ToArray();
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object obj)
		{
			if (obj is ReadOnlyMemory<T> other)
			{
				return Equals(other);
			}
			if (obj is Memory<T> memory)
			{
				return Equals(memory);
			}
			return false;
		}

		public bool Equals(ReadOnlyMemory<T> other)
		{
			if (_object == other._object && _index == other._index)
			{
				return _length == other._length;
			}
			return false;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			if (_object == null)
			{
				return 0;
			}
			int hashCode = _object.GetHashCode();
			int index = _index;
			int hashCode2 = index.GetHashCode();
			index = _length;
			return CombineHashCodes(hashCode, hashCode2, index.GetHashCode());
		}

		private static int CombineHashCodes(int left, int right)
		{
			return ((left << 5) + left) ^ right;
		}

		private static int CombineHashCodes(int h1, int h2, int h3)
		{
			return CombineHashCodes(CombineHashCodes(h1, h2), h3);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal object GetObjectStartLength(out int start, out int length)
		{
			start = _index;
			length = _length;
			return _object;
		}
	}
	[DebuggerTypeProxy(typeof(System.SpanDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	[DebuggerTypeProxy(typeof(System.SpanDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	public readonly ref struct ReadOnlySpan<T>
	{
		public ref struct Enumerator
		{
			private readonly ReadOnlySpan<T> _span;

			private int _index;

			public ref readonly T Current
			{
				[MethodImpl(MethodImplOptions.AggressiveInlining)]
				get
				{
					return ref _span[_index];
				}
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			internal Enumerator(ReadOnlySpan<T> span)
			{
				_span = span;
				_index = -1;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public bool MoveNext()
			{
				int num = _index + 1;
				if (num < _span.Length)
				{
					_index = num;
					return true;
				}
				return false;
			}
		}

		private readonly Pinnable<T> _pinnable;

		private readonly IntPtr _byteOffset;

		private readonly int _length;

		public int Length => _length;

		public bool IsEmpty => _length == 0;

		public static ReadOnlySpan<T> Empty => default(ReadOnlySpan<T>);

		public unsafe ref readonly T this[int index]
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				if ((uint)index >= (uint)_length)
				{
					System.ThrowHelper.ThrowIndexOutOfRangeException();
				}
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					return ref Unsafe.Add(ref Unsafe.AsRef<T>(byteOffset.ToPointer()), index);
				}
				return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset), index);
			}
		}

		internal Pinnable<T> Pinnable => _pinnable;

		internal IntPtr ByteOffset => _byteOffset;

		public static bool operator !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right)
		{
			return !(left == right);
		}

		[Obsolete("Equals() on ReadOnlySpan will always throw an exception. Use == instead.")]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object obj)
		{
			throw new NotSupportedException(System.SR.NotSupported_CannotCallEqualsOnSpan);
		}

		[Obsolete("GetHashCode() on ReadOnlySpan will always throw an exception.")]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			throw new NotSupportedException(System.SR.NotSupported_CannotCallGetHashCodeOnSpan);
		}

		public static implicit operator ReadOnlySpan<T>(T[] array)
		{
			return new ReadOnlySpan<T>(array);
		}

		public static implicit operator ReadOnlySpan<T>(ArraySegment<T> segment)
		{
			return new ReadOnlySpan<T>(segment.Array, segment.Offset, segment.Count);
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(this);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlySpan(T[] array)
		{
			if (array == null)
			{
				this = default(ReadOnlySpan<T>);
				return;
			}
			_length = array.Length;
			_pinnable = Unsafe.As<Pinnable<T>>(array);
			_byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlySpan(T[] array, int start, int length)
		{
			if (array == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				this = default(ReadOnlySpan<T>);
				return;
			}
			if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			_length = length;
			_pinnable = Unsafe.As<Pinnable<T>>(array);
			_byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public unsafe ReadOnlySpan(void* pointer, int length)
		{
			if (System.SpanHelpers.IsReferenceOrContainsReferences<T>())
			{
				System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T));
			}
			if (length < 0)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			_length = length;
			_pinnable = null;
			_byteOffset = new IntPtr(pointer);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal ReadOnlySpan(Pinnable<T> pinnable, IntPtr byteOffset, int length)
		{
			_length = length;
			_pinnable = pinnable;
			_byteOffset = byteOffset;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public unsafe ref readonly T GetPinnableReference()
		{
			if (_length != 0)
			{
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					return ref Unsafe.AsRef<T>(byteOffset.ToPointer());
				}
				return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset);
			}
			return ref Unsafe.AsRef<T>(null);
		}

		public void CopyTo(Span<T> destination)
		{
			if (!TryCopyTo(destination))
			{
				System.ThrowHelper.ThrowArgumentException_DestinationTooShort();
			}
		}

		public bool TryCopyTo(Span<T> destination)
		{
			int length = _length;
			int length2 = destination.Length;
			if (length == 0)
			{
				return true;
			}
			if ((uint)length > (uint)length2)
			{
				return false;
			}
			ref T src = ref DangerousGetPinnableReference();
			System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length);
			return true;
		}

		public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right)
		{
			if (left._length == right._length)
			{
				return Unsafe.AreSame(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference());
			}
			return false;
		}

		public unsafe override string ToString()
		{
			if (typeof(T) == typeof(char))
			{
				if (_byteOffset == MemoryExtensions.StringAdjustment)
				{
					object obj = Unsafe.As<object>(_pinnable);
					if (obj is string text && _length == text.Length)
					{
						return text;
					}
				}
				fixed (char* value = &Unsafe.As<T, char>(ref DangerousGetPinnableReference()))
				{
					return new string(value, 0, _length);
				}
			}
			return $"System.ReadOnlySpan<{typeof(T).Name}>[{_length}]";
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlySpan<T> Slice(int start)
		{
			if ((uint)start > (uint)_length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			IntPtr byteOffset = _byteOffset.Add<T>(start);
			int length = _length - start;
			return new ReadOnlySpan<T>(_pinnable, byteOffset, length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlySpan<T> Slice(int start, int length)
		{
			if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			IntPtr byteOffset = _byteOffset.Add<T>(start);
			return new ReadOnlySpan<T>(_pinnable, byteOffset, length);
		}

		public T[] ToArray()
		{
			if (_length == 0)
			{
				return System.SpanHelpers.PerTypeValues<T>.EmptyArray;
			}
			T[] array = new T[_length];
			CopyTo(array);
			return array;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[EditorBrowsable(EditorBrowsableState.Never)]
		internal unsafe ref T DangerousGetPinnableReference()
		{
			if (_pinnable == null)
			{
				IntPtr byteOffset = _byteOffset;
				return ref Unsafe.AsRef<T>(byteOffset.ToPointer());
			}
			return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset);
		}
	}
	[DebuggerTypeProxy(typeof(System.SpanDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	[DebuggerTypeProxy(typeof(System.SpanDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	public readonly ref struct Span<T>
	{
		public ref struct Enumerator
		{
			private readonly Span<T> _span;

			private int _index;

			public ref T Current
			{
				[MethodImpl(MethodImplOptions.AggressiveInlining)]
				get
				{
					return ref _span[_index];
				}
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			internal Enumerator(Span<T> span)
			{
				_span = span;
				_index = -1;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public bool MoveNext()
			{
				int num = _index + 1;
				if (num < _span.Length)
				{
					_index = num;
					return true;
				}
				return false;
			}
		}

		private readonly Pinnable<T> _pinnable;

		private readonly IntPtr _byteOffset;

		private readonly int _length;

		public int Length => _length;

		public bool IsEmpty => _length == 0;

		public static Span<T> Empty => default(Span<T>);

		public unsafe ref T this[int index]
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				if ((uint)index >= (uint)_length)
				{
					System.ThrowHelper.ThrowIndexOutOfRangeException();
				}
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					return ref Unsafe.Add(ref Unsafe.AsRef<T>(byteOffset.ToPointer()), index);
				}
				return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset), index);
			}
		}

		internal Pinnable<T> Pinnable => _pinnable;

		internal IntPtr ByteOffset => _byteOffset;

		public static bool operator !=(Span<T> left, Span<T> right)
		{
			return !(left == right);
		}

		[Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object obj)
		{
			throw new NotSupportedException(System.SR.NotSupported_CannotCallEqualsOnSpan);
		}

		[Obsolete("GetHashCode() on Span will always throw an exception.")]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			throw new NotSupportedException(System.SR.NotSupported_CannotCallGetHashCodeOnSpan);
		}

		public static implicit operator Span<T>(T[] array)
		{
			return new Span<T>(array);
		}

		public static implicit operator Span<T>(ArraySegment<T> segment)
		{
			return new Span<T>(segment.Array, segment.Offset, segment.Count);
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(this);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span(T[] array)
		{
			if (array == null)
			{
				this = default(Span<T>);
				return;
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			_length = array.Length;
			_pinnable = Unsafe.As<Pinnable<T>>(array);
			_byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static Span<T> Create(T[] array, int start)
		{
			if (array == null)
			{
				if (start != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				return default(Span<T>);
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			if ((uint)start > (uint)array.Length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			IntPtr byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
			int length = array.Length - start;
			return new Span<T>(Unsafe.As<Pinnable<T>>(array), byteOffset, length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span(T[] array, int start, int length)
		{
			if (array == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				this = default(Span<T>);
				return;
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			_length = length;
			_pinnable = Unsafe.As<Pinnable<T>>(array);
			_byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public unsafe Span(void* pointer, int length)
		{
			if (System.SpanHelpers.IsReferenceOrContainsReferences<T>())
			{
				System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T));
			}
			if (length < 0)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			_length = length;
			_pinnable = null;
			_byteOffset = new IntPtr(pointer);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal Span(Pinnable<T> pinnable, IntPtr byteOffset, int length)
		{
			_length = length;
			_pinnable = pinnable;
			_byteOffset = byteOffset;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public unsafe ref T GetPinnableReference()
		{
			if (_length != 0)
			{
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					return ref Unsafe.AsRef<T>(byteOffset.ToPointer());
				}
				return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset);
			}
			return ref Unsafe.AsRef<T>(null);
		}

		public unsafe void Clear()
		{
			int length = _length;
			if (length == 0)
			{
				return;
			}
			UIntPtr byteLength = (UIntPtr)(ulong)((uint)length * Unsafe.SizeOf<T>());
			if ((Unsafe.SizeOf<T>() & (sizeof(IntPtr) - 1)) != 0)
			{
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					byte* ptr = (byte*)byteOffset.ToPointer();
					System.SpanHelpers.ClearLessThanPointerSized(ptr, byteLength);
				}
				else
				{
					System.SpanHelpers.ClearLessThanPointerSized(ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset)), byteLength);
				}
			}
			else if (System.SpanHelpers.IsReferenceOrContainsReferences<T>())
			{
				UIntPtr pointerSizeLength = (UIntPtr)(ulong)(length * Unsafe.SizeOf<T>() / sizeof(IntPtr));
				System.SpanHelpers.ClearPointerSizedWithReferences(ref Unsafe.As<T, IntPtr>(ref DangerousGetPinnableReference()), pointerSizeLength);
			}
			else
			{
				System.SpanHelpers.ClearPointerSizedWithoutReferences(ref Unsafe.As<T, byte>(ref DangerousGetPinnableReference()), byteLength);
			}
		}

		public unsafe void Fill(T value)
		{
			int length = _length;
			if (length == 0)
			{
				return;
			}
			if (Unsafe.SizeOf<T>() == 1)
			{
				byte value2 = Unsafe.As<T, byte>(ref value);
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					Unsafe.InitBlockUnaligned(byteOffset.ToPointer(), value2, (uint)length);
				}
				else
				{
					Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset)), value2, (uint)length);
				}
				return;
			}
			ref T source = ref DangerousGetPinnableReference();
			int i;
			for (i = 0; i < (length & -8); i += 8)
			{
				Unsafe.Add(ref source, i) = value;
				Unsafe.Add(ref source, i + 1) = value;
				Unsafe.Add(ref source, i + 2) = value;
				Unsafe.Add(ref source, i + 3) = value;
				Unsafe.Add(ref source, i + 4) = value;
				Unsafe.Add(ref source, i + 5) = value;
				Unsafe.Add(ref source, i + 6) = value;
				Unsafe.Add(ref source, i + 7) = value;
			}
			if (i < (length & -4))
			{
				Unsafe.Add(ref source, i) = value;
				Unsafe.Add(ref source, i + 1) = value;
				Unsafe.Add(ref source, i + 2) = value;
				Unsafe.Add(ref source, i + 3) = value;
				i += 4;
			}
			for (; i < length; i++)
			{
				Unsafe.Add(ref source, i) = value;
			}
		}

		public void CopyTo(Span<T> destination)
		{
			if (!TryCopyTo(destination))
			{
				System.ThrowHelper.ThrowArgumentException_DestinationTooShort();
			}
		}

		public bool TryCopyTo(Span<T> destination)
		{
			int length = _length;
			int length2 = destination._length;
			if (length == 0)
			{
				return true;
			}
			if ((uint)length > (uint)length2)
			{
				return false;
			}
			ref T src = ref DangerousGetPinnableReference();
			System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length);
			return true;
		}

		public static bool operator ==(Span<T> left, Span<T> right)
		{
			if (left._length == right._length)
			{
				return Unsafe.AreSame(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference());
			}
			return false;
		}

		public static implicit operator ReadOnlySpan<T>(Span<T> span)
		{
			return new ReadOnlySpan<T>(span._pinnable, span._byteOffset, span._length);
		}

		public unsafe override string ToString()
		{
			if (typeof(T) == typeof(char))
			{
				fixed (char* value = &Unsafe.As<T, char>(ref DangerousGetPinnableReference()))
				{
					return new string(value, 0, _length);
				}
			}
			return $"System.Span<{typeof(T).Name}>[{_length}]";
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<T> Slice(int start)
		{
			if ((uint)start > (uint)_length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			IntPtr byteOffset = _byteOffset.Add<T>(start);
			int length = _length - start;
			return new Span<T>(_pinnable, byteOffset, length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<T> Slice(int start, int length)
		{
			if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			IntPtr byteOffset = _byteOffset.Add<T>(start);
			return new Span<T>(_pinnable, byteOffset, length);
		}

		public T[] ToArray()
		{
			if (_length == 0)
			{
				return System.SpanHelpers.PerTypeValues<T>.EmptyArray;
			}
			T[] array = new T[_length];
			CopyTo(array);
			return array;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[EditorBrowsable(EditorBrowsableState.Never)]
		internal unsafe ref T DangerousGetPinnableReference()
		{
			if (_pinnable == null)
			{
				IntPtr byteOffset = _byteOffset;
				return ref Unsafe.AsRef<T>(byteOffset.ToPointer());
			}
			return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset);
		}
	}
	internal sealed class SpanDebugView<T>
	{
		private readonly T[] _array;

		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		public T[] Items => _array;

		public SpanDebugView(Span<T> span)
		{
			_array = span.ToArray();
		}

		public SpanDebugView(ReadOnlySpan<T> span)
		{
			_array = span.ToArray();
		}
	}
	internal static class SpanHelpers
	{
		internal struct ComparerComparable<T, TComparer> : IComparable<T> where TComparer : IComparer<T>
		{
			private readonly T _value;

			private readonly TComparer _comparer;

			public ComparerComparable(T value, TComparer comparer)
			{
				_value = value;
				_comparer = comparer;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public int CompareTo(T other)
			{
				return _comparer.Compare(_value, other);
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 64)]
		private struct Reg64
		{
		}

		[StructLayout(LayoutKind.Sequential, Size = 32)]
		private struct Reg32
		{
		}

		[StructLayout(LayoutKind.Sequential, Size = 16)]
		private struct Reg16
		{
		}

		public static class PerTypeValues<T>
		{
			public static readonly bool IsReferenceOrContainsReferences = IsReferenceOrContainsReferencesCore(typeof(T));

			public static readonly T[] EmptyArray = new T[0];

			public static readonly IntPtr ArrayAdjustment = MeasureArrayAdjustment();

			private static IntPtr MeasureArrayAdjustment()
			{
				T[] array = new T[1];
				return Unsafe.ByteOffset(ref Unsafe.As<Pinnable<T>>(array).Data, ref array[0]);
			}
		}

		private const ulong XorPowerOfTwoToHighByte = 283686952306184uL;

		private const ulong XorPowerOfTwoToHighChar = 4295098372uL;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T, TComparable>(this ReadOnlySpan<T> span, TComparable comparable) where TComparable : IComparable<T>
		{
			if (comparable == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparable);
			}
			return BinarySearch(ref MemoryMarshal.GetReference(span), span.Length, comparable);
		}

		public static int BinarySearch<T, TComparable>(ref T spanStart, int length, TComparable comparable) where TComparable : IComparable<T>
		{
			int num = 0;
			int num2 = length - 1;
			while (num <= num2)
			{
				int num3 = num2 + num >>> 1;
				int num4 = comparable.CompareTo(Unsafe.Add(ref spanStart, num3));
				if (num4 == 0)
				{
					return num3;
				}
				if (num4 > 0)
				{
					num = num3 + 1;
				}
				else
				{
					num2 = num3 - 1;
				}
			}
			return ~num;
		}

		public static int IndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
		{
			if (valueLength == 0)
			{
				return 0;
			}
			byte value2 = value;
			ref byte second = ref Unsafe.Add(ref value, 1);
			int num = valueLength - 1;
			int num2 = 0;
			while (true)
			{
				int num3 = searchSpaceLength - num2 - num;
				if (num3 <= 0)
				{
					break;
				}
				int num4 = IndexOf(ref Unsafe.Add(ref searchSpace, num2), value2, num3);
				if (num4 == -1)
				{
					break;
				}
				num2 += num4;
				if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num2 + 1), ref second, num))
				{
					return num2;
				}
				num2++;
			}
			return -1;
		}

		public static int IndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
		{
			if (valueLength == 0)
			{
				return 0;
			}
			int num = -1;
			for (int i = 0; i < valueLength; i++)
			{
				int num2 = IndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength);
				if ((uint)num2 < (uint)num)
				{
					num = num2;
					searchSpaceLength = num2;
					if (num == 0)
					{
						break;
					}
				}
			}
			return num;
		}

		public static int LastIndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
		{
			if (valueLength == 0)
			{
				return 0;
			}
			int num = -1;
			for (int i = 0; i < valueLength; i++)
			{
				int num2 = LastIndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength);
				if (num2 > num)
				{
					num = num2;
				}
			}
			return num;
		}

		public unsafe static int IndexOf(ref byte searchSpace, byte value, int length)
		{
			IntPtr intPtr = (IntPtr)0;
			IntPtr intPtr2 = (IntPtr)length;
			if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
			{
				int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
				intPtr2 = (IntPtr)((Vector<byte>.Count - num) & (Vector<byte>.Count - 1));
			}
			while (true)
			{
				if ((nuint)(void*)intPtr2 >= (nuint)8u)
				{
					intPtr2 -= 8;
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr))
					{
						goto IL_0242;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1))
					{
						goto IL_024a;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2))
					{
						goto IL_0258;
					}
					if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 3))
					{
						if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 4))
						{
							if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 5))
							{
								if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 6))
								{
									if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 7))
									{
										break;
									}
									intPtr += 8;
									continue;
								}
								return (int)(void*)(intPtr + 6);
							}
							return (int)(void*)(intPtr + 5);
						}
						return (int)(void*)(intPtr + 4);
					}
					goto IL_0266;
				}
				if ((nuint)(void*)intPtr2 >= (nuint)4u)
				{
					intPtr2 -= 4;
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr))
					{
						goto IL_0242;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1))
					{
						goto IL_024a;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2))
					{
						goto IL_0258;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 3))
					{
						goto IL_0266;
					}
					intPtr += 4;
				}
				while ((void*)intPtr2 != null)
				{
					intPtr2 -= 1;
					if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr))
					{
						intPtr += 1;
						continue;
					}
					goto IL_0242;
				}
				if (Vector.IsHardwareAccelerated && (int)(void*)intPtr < length)
				{
					intPtr2 = (IntPtr)((length - (int)(void*)intPtr) & ~(Vector<byte>.Count - 1));
					Vector<byte> vector = GetVector(value);
					for (; (void*)intPtr2 > (void*)intPtr; intPtr += Vector<byte>.Count)
					{
						Vector<byte> vector2 = Vector.Equals(vector, Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, intPtr)));
						if (!Vector<byte>.Zero.Equals(vector2))
						{
							return (int)(void*)intPtr + LocateFirstFoundByte(vector2);
						}
					}
					if ((int)(void*)intPtr < length)
					{
						intPtr2 = (IntPtr)(length - (int)(void*)intPtr);
						continue;
					}
				}
				return -1;
				IL_0266:
				return (int)(void*)(intPtr + 3);
				IL_0242:
				return (int)(void*)intPtr;
				IL_0258:
				return (int)(void*)(intPtr + 2);
				IL_024a:
				return (int)(void*)(intPtr + 1);
			}
			return (int)(void*)(intPtr + 7);
		}

		public static int LastIndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
		{
			if (valueLength == 0)
			{
				return 0;
			}
			byte value2 = value;
			ref byte second = ref Unsafe.Add(ref value, 1);
			int num = valueLength - 1;
			int num2 = 0;
			while (true)
			{
				int num3 = searchSpaceLength - num2 - num;
				if (num3 <= 0)
				{
					break;
				}
				int num4 = LastIndexOf(ref searchSpace, value2, num3);
				if (num4 == -1)
				{
					break;
				}
				if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num4 + 1), ref second, num))
				{
					return num4;
				}
				num2 += num3 - num4;
			}
			return -1;
		}

		public unsafe static int LastIndexOf(ref byte searchSpace, byte value, int length)
		{
			IntPtr intPtr = (IntPtr)length;
			IntPtr intPtr2 = (IntPtr)length;
			if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
			{
				int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
				intPtr2 = (IntPtr)(((length & (Vector<byte>.Count - 1)) + num) & (Vector<byte>.Count - 1));
			}
			while (true)
			{
				if ((nuint)(void*)intPtr2 >= (nuint)8u)
				{
					intPtr2 -= 8;
					intPtr -= 8;
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 7))
					{
						break;
					}
					if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 6))
					{
						if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 5))
						{
							if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 4))
							{
								if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 3))
								{
									if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 2))
									{
										if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 1))
										{
											if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr))
											{
												continue;
											}
											goto IL_0254;
										}
										goto IL_025c;
									}
									goto IL_026a;
								}
								goto IL_0278;
							}
							return (int)(void*)(intPtr + 4);
						}
						return (int)(void*)(intPtr + 5);
					}
					return (int)(void*)(intPtr + 6);
				}
				if ((nuint)(void*)intPtr2 >= (nuint)4u)
				{
					intPtr2 -= 4;
					intPtr -= 4;
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 3))
					{
						goto IL_0278;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2))
					{
						goto IL_026a;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1))
					{
						goto IL_025c;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr))
					{
						goto IL_0254;
					}
				}
				while ((void*)intPtr2 != null)
				{
					intPtr2 -= 1;
					intPtr -= 1;
					if (value != Unsa

plugins/System.Numerics.Vectors.dll

Decompiled a day ago
using System;
using System.Diagnostics;
using System.Globalization;
using System.Numerics.Hashing;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using FxResources.System.Numerics.Vectors;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyTitle("System.Numerics.Vectors")]
[assembly: AssemblyDescription("System.Numerics.Vectors")]
[assembly: AssemblyDefaultAlias("System.Numerics.Vectors")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: AssemblyCopyright("© Microsoft Corporation.  All rights reserved.")]
[assembly: AssemblyFileVersion("4.6.25519.03")]
[assembly: AssemblyInformationalVersion("4.6.25519.03 built by: dlab-DDVSOWINAGE013. Commit Hash: 8321c729934c0f8be754953439b88e6e1c120c24")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.1.3.0")]
[module: UnverifiableCode]
namespace FxResources.System.Numerics.Vectors
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class MathF
	{
		public const float PI = 3.1415927f;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Abs(float x)
		{
			return Math.Abs(x);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Acos(float x)
		{
			return (float)Math.Acos(x);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Cos(float x)
		{
			return (float)Math.Cos(x);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float IEEERemainder(float x, float y)
		{
			return (float)Math.IEEERemainder(x, y);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Sin(float x)
		{
			return (float)Math.Sin(x);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Sqrt(float x)
		{
			return (float)Math.Sqrt(x);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Tan(float x)
		{
			return (float)Math.Tan(x);
		}
	}
	internal static class SR
	{
		private static ResourceManager s_resourceManager;

		private const string s_resourcesName = "FxResources.System.Numerics.Vectors.SR";

		private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType));

		internal static string Arg_ArgumentOutOfRangeException => GetResourceString("Arg_ArgumentOutOfRangeException", null);

		internal static string Arg_ElementsInSourceIsGreaterThanDestination => GetResourceString("Arg_ElementsInSourceIsGreaterThanDestination", null);

		internal static string Arg_NullArgumentNullRef => GetResourceString("Arg_NullArgumentNullRef", null);

		internal static string Arg_TypeNotSupported => GetResourceString("Arg_TypeNotSupported", null);

		internal static Type ResourceType => typeof(SR);

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static bool UsingResourceKeys()
		{
			return false;
		}

		internal static string GetResourceString(string resourceKey, string defaultString)
		{
			string text = null;
			try
			{
				text = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal))
			{
				return defaultString;
			}
			return text;
		}

		internal static string Format(string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + string.Join(", ", args);
				}
				return string.Format(resourceFormat, args);
			}
			return resourceFormat;
		}

		internal static string Format(string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(resourceFormat, p1);
		}

		internal static string Format(string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(resourceFormat, p1, p2);
		}

		internal static string Format(string resourceFormat, object p1, object p2, object p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(resourceFormat, p1, p2, p3);
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.All)]
	internal class __BlockReflectionAttribute : Attribute
	{
	}
}
namespace System.Numerics
{
	internal class ConstantHelper
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static byte GetByteWithAllBitsSet()
		{
			byte result = 0;
			result = byte.MaxValue;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static sbyte GetSByteWithAllBitsSet()
		{
			sbyte result = 0;
			result = -1;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ushort GetUInt16WithAllBitsSet()
		{
			ushort result = 0;
			result = ushort.MaxValue;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static short GetInt16WithAllBitsSet()
		{
			short result = 0;
			result = -1;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static uint GetUInt32WithAllBitsSet()
		{
			uint result = 0u;
			result = uint.MaxValue;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int GetInt32WithAllBitsSet()
		{
			int result = 0;
			result = -1;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ulong GetUInt64WithAllBitsSet()
		{
			ulong result = 0uL;
			result = ulong.MaxValue;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static long GetInt64WithAllBitsSet()
		{
			long result = 0L;
			result = -1L;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static float GetSingleWithAllBitsSet()
		{
			float result = 0f;
			*(int*)(&result) = -1;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static double GetDoubleWithAllBitsSet()
		{
			double result = 0.0;
			*(long*)(&result) = -1L;
			return result;
		}
	}
	[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property)]
	internal class JitIntrinsicAttribute : Attribute
	{
	}
	[StructLayout(LayoutKind.Explicit)]
	internal struct Register
	{
		[FieldOffset(0)]
		internal byte byte_0;

		[FieldOffset(1)]
		internal byte byte_1;

		[FieldOffset(2)]
		internal byte byte_2;

		[FieldOffset(3)]
		internal byte byte_3;

		[FieldOffset(4)]
		internal byte byte_4;

		[FieldOffset(5)]
		internal byte byte_5;

		[FieldOffset(6)]
		internal byte byte_6;

		[FieldOffset(7)]
		internal byte byte_7;

		[FieldOffset(8)]
		internal byte byte_8;

		[FieldOffset(9)]
		internal byte byte_9;

		[FieldOffset(10)]
		internal byte byte_10;

		[FieldOffset(11)]
		internal byte byte_11;

		[FieldOffset(12)]
		internal byte byte_12;

		[FieldOffset(13)]
		internal byte byte_13;

		[FieldOffset(14)]
		internal byte byte_14;

		[FieldOffset(15)]
		internal byte byte_15;

		[FieldOffset(0)]
		internal sbyte sbyte_0;

		[FieldOffset(1)]
		internal sbyte sbyte_1;

		[FieldOffset(2)]
		internal sbyte sbyte_2;

		[FieldOffset(3)]
		internal sbyte sbyte_3;

		[FieldOffset(4)]
		internal sbyte sbyte_4;

		[FieldOffset(5)]
		internal sbyte sbyte_5;

		[FieldOffset(6)]
		internal sbyte sbyte_6;

		[FieldOffset(7)]
		internal sbyte sbyte_7;

		[FieldOffset(8)]
		internal sbyte sbyte_8;

		[FieldOffset(9)]
		internal sbyte sbyte_9;

		[FieldOffset(10)]
		internal sbyte sbyte_10;

		[FieldOffset(11)]
		internal sbyte sbyte_11;

		[FieldOffset(12)]
		internal sbyte sbyte_12;

		[FieldOffset(13)]
		internal sbyte sbyte_13;

		[FieldOffset(14)]
		internal sbyte sbyte_14;

		[FieldOffset(15)]
		internal sbyte sbyte_15;

		[FieldOffset(0)]
		internal ushort uint16_0;

		[FieldOffset(2)]
		internal ushort uint16_1;

		[FieldOffset(4)]
		internal ushort uint16_2;

		[FieldOffset(6)]
		internal ushort uint16_3;

		[FieldOffset(8)]
		internal ushort uint16_4;

		[FieldOffset(10)]
		internal ushort uint16_5;

		[FieldOffset(12)]
		internal ushort uint16_6;

		[FieldOffset(14)]
		internal ushort uint16_7;

		[FieldOffset(0)]
		internal short int16_0;

		[FieldOffset(2)]
		internal short int16_1;

		[FieldOffset(4)]
		internal short int16_2;

		[FieldOffset(6)]
		internal short int16_3;

		[FieldOffset(8)]
		internal short int16_4;

		[FieldOffset(10)]
		internal short int16_5;

		[FieldOffset(12)]
		internal short int16_6;

		[FieldOffset(14)]
		internal short int16_7;

		[FieldOffset(0)]
		internal uint uint32_0;

		[FieldOffset(4)]
		internal uint uint32_1;

		[FieldOffset(8)]
		internal uint uint32_2;

		[FieldOffset(12)]
		internal uint uint32_3;

		[FieldOffset(0)]
		internal int int32_0;

		[FieldOffset(4)]
		internal int int32_1;

		[FieldOffset(8)]
		internal int int32_2;

		[FieldOffset(12)]
		internal int int32_3;

		[FieldOffset(0)]
		internal ulong uint64_0;

		[FieldOffset(8)]
		internal ulong uint64_1;

		[FieldOffset(0)]
		internal long int64_0;

		[FieldOffset(8)]
		internal long int64_1;

		[FieldOffset(0)]
		internal float single_0;

		[FieldOffset(4)]
		internal float single_1;

		[FieldOffset(8)]
		internal float single_2;

		[FieldOffset(12)]
		internal float single_3;

		[FieldOffset(0)]
		internal double double_0;

		[FieldOffset(8)]
		internal double double_1;
	}
	public struct Vector<T> : IEquatable<Vector<T>>, IFormattable where T : struct
	{
		private struct VectorSizeHelper
		{
			internal Vector<T> _placeholder;

			internal byte _byte;
		}

		private System.Numerics.Register register;

		private static readonly int s_count = InitializeCount();

		private static readonly Vector<T> zero = new Vector<T>(GetZeroValue());

		private static readonly Vector<T> one = new Vector<T>(GetOneValue());

		private static readonly Vector<T> allOnes = new Vector<T>(GetAllBitsSetValue());

		[JitIntrinsic]
		public static int Count => s_count;

		[JitIntrinsic]
		public static Vector<T> Zero => zero;

		[JitIntrinsic]
		public static Vector<T> One => one;

		internal static Vector<T> AllOnes => allOnes;

		[JitIntrinsic]
		public unsafe T this[int index]
		{
			get
			{
				if (index >= Count || index < 0)
				{
					throw new IndexOutOfRangeException(System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, index));
				}
				if (typeof(T) == typeof(byte))
				{
					fixed (byte* ptr = &register.byte_0)
					{
						return (T)(object)ptr[index];
					}
				}
				if (typeof(T) == typeof(sbyte))
				{
					fixed (sbyte* ptr2 = &register.sbyte_0)
					{
						return (T)(object)ptr2[index];
					}
				}
				if (typeof(T) == typeof(ushort))
				{
					fixed (ushort* ptr3 = &register.uint16_0)
					{
						return (T)(object)ptr3[index];
					}
				}
				if (typeof(T) == typeof(short))
				{
					fixed (short* ptr4 = &register.int16_0)
					{
						return (T)(object)ptr4[index];
					}
				}
				if (typeof(T) == typeof(uint))
				{
					fixed (uint* ptr5 = &register.uint32_0)
					{
						return (T)(object)ptr5[index];
					}
				}
				if (typeof(T) == typeof(int))
				{
					fixed (int* ptr6 = &register.int32_0)
					{
						return (T)(object)ptr6[index];
					}
				}
				if (typeof(T) == typeof(ulong))
				{
					fixed (ulong* ptr7 = &register.uint64_0)
					{
						return (T)(object)ptr7[index];
					}
				}
				if (typeof(T) == typeof(long))
				{
					fixed (long* ptr8 = &register.int64_0)
					{
						return (T)(object)ptr8[index];
					}
				}
				if (typeof(T) == typeof(float))
				{
					fixed (float* ptr9 = &register.single_0)
					{
						return (T)(object)ptr9[index];
					}
				}
				if (typeof(T) == typeof(double))
				{
					fixed (double* ptr10 = &register.double_0)
					{
						return (T)(object)ptr10[index];
					}
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
		}

		private unsafe static int InitializeCount()
		{
			VectorSizeHelper vectorSizeHelper = default(VectorSizeHelper);
			byte* ptr = &vectorSizeHelper._placeholder.register.byte_0;
			byte* ptr2 = &vectorSizeHelper._byte;
			int num = (int)(ptr2 - ptr);
			int num2 = -1;
			if (typeof(T) == typeof(byte))
			{
				num2 = 1;
			}
			else if (typeof(T) == typeof(sbyte))
			{
				num2 = 1;
			}
			else if (typeof(T) == typeof(ushort))
			{
				num2 = 2;
			}
			else if (typeof(T) == typeof(short))
			{
				num2 = 2;
			}
			else if (typeof(T) == typeof(uint))
			{
				num2 = 4;
			}
			else if (typeof(T) == typeof(int))
			{
				num2 = 4;
			}
			else if (typeof(T) == typeof(ulong))
			{
				num2 = 8;
			}
			else if (typeof(T) == typeof(long))
			{
				num2 = 8;
			}
			else if (typeof(T) == typeof(float))
			{
				num2 = 4;
			}
			else
			{
				if (!(typeof(T) == typeof(double)))
				{
					throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
				}
				num2 = 8;
			}
			return num / num2;
		}

		[JitIntrinsic]
		public unsafe Vector(T value)
		{
			this = default(Vector<T>);
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					fixed (byte* ptr = &register.byte_0)
					{
						for (int i = 0; i < Count; i++)
						{
							ptr[i] = (byte)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(sbyte))
				{
					fixed (sbyte* ptr2 = &register.sbyte_0)
					{
						for (int j = 0; j < Count; j++)
						{
							ptr2[j] = (sbyte)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(ushort))
				{
					fixed (ushort* ptr3 = &register.uint16_0)
					{
						for (int k = 0; k < Count; k++)
						{
							ptr3[k] = (ushort)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(short))
				{
					fixed (short* ptr4 = &register.int16_0)
					{
						for (int l = 0; l < Count; l++)
						{
							ptr4[l] = (short)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(uint))
				{
					fixed (uint* ptr5 = &register.uint32_0)
					{
						for (int m = 0; m < Count; m++)
						{
							ptr5[m] = (uint)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(int))
				{
					fixed (int* ptr6 = &register.int32_0)
					{
						for (int n = 0; n < Count; n++)
						{
							ptr6[n] = (int)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(ulong))
				{
					fixed (ulong* ptr7 = &register.uint64_0)
					{
						for (int num = 0; num < Count; num++)
						{
							ptr7[num] = (ulong)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(long))
				{
					fixed (long* ptr8 = &register.int64_0)
					{
						for (int num2 = 0; num2 < Count; num2++)
						{
							ptr8[num2] = (long)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(float))
				{
					fixed (float* ptr9 = &register.single_0)
					{
						for (int num3 = 0; num3 < Count; num3++)
						{
							ptr9[num3] = (float)(object)value;
						}
					}
				}
				else
				{
					if (!(typeof(T) == typeof(double)))
					{
						return;
					}
					fixed (double* ptr10 = &register.double_0)
					{
						for (int num4 = 0; num4 < Count; num4++)
						{
							ptr10[num4] = (double)(object)value;
						}
					}
				}
			}
			else if (typeof(T) == typeof(byte))
			{
				register.byte_0 = (byte)(object)value;
				register.byte_1 = (byte)(object)value;
				register.byte_2 = (byte)(object)value;
				register.byte_3 = (byte)(object)value;
				register.byte_4 = (byte)(object)value;
				register.byte_5 = (byte)(object)value;
				register.byte_6 = (byte)(object)value;
				register.byte_7 = (byte)(object)value;
				register.byte_8 = (byte)(object)value;
				register.byte_9 = (byte)(object)value;
				register.byte_10 = (byte)(object)value;
				register.byte_11 = (byte)(object)value;
				register.byte_12 = (byte)(object)value;
				register.byte_13 = (byte)(object)value;
				register.byte_14 = (byte)(object)value;
				register.byte_15 = (byte)(object)value;
			}
			else if (typeof(T) == typeof(sbyte))
			{
				register.sbyte_0 = (sbyte)(object)value;
				register.sbyte_1 = (sbyte)(object)value;
				register.sbyte_2 = (sbyte)(object)value;
				register.sbyte_3 = (sbyte)(object)value;
				register.sbyte_4 = (sbyte)(object)value;
				register.sbyte_5 = (sbyte)(object)value;
				register.sbyte_6 = (sbyte)(object)value;
				register.sbyte_7 = (sbyte)(object)value;
				register.sbyte_8 = (sbyte)(object)value;
				register.sbyte_9 = (sbyte)(object)value;
				register.sbyte_10 = (sbyte)(object)value;
				register.sbyte_11 = (sbyte)(object)value;
				register.sbyte_12 = (sbyte)(object)value;
				register.sbyte_13 = (sbyte)(object)value;
				register.sbyte_14 = (sbyte)(object)value;
				register.sbyte_15 = (sbyte)(object)value;
			}
			else if (typeof(T) == typeof(ushort))
			{
				register.uint16_0 = (ushort)(object)value;
				register.uint16_1 = (ushort)(object)value;
				register.uint16_2 = (ushort)(object)value;
				register.uint16_3 = (ushort)(object)value;
				register.uint16_4 = (ushort)(object)value;
				register.uint16_5 = (ushort)(object)value;
				register.uint16_6 = (ushort)(object)value;
				register.uint16_7 = (ushort)(object)value;
			}
			else if (typeof(T) == typeof(short))
			{
				register.int16_0 = (short)(object)value;
				register.int16_1 = (short)(object)value;
				register.int16_2 = (short)(object)value;
				register.int16_3 = (short)(object)value;
				register.int16_4 = (short)(object)value;
				register.int16_5 = (short)(object)value;
				register.int16_6 = (short)(object)value;
				register.int16_7 = (short)(object)value;
			}
			else if (typeof(T) == typeof(uint))
			{
				register.uint32_0 = (uint)(object)value;
				register.uint32_1 = (uint)(object)value;
				register.uint32_2 = (uint)(object)value;
				register.uint32_3 = (uint)(object)value;
			}
			else if (typeof(T) == typeof(int))
			{
				register.int32_0 = (int)(object)value;
				register.int32_1 = (int)(object)value;
				register.int32_2 = (int)(object)value;
				register.int32_3 = (int)(object)value;
			}
			else if (typeof(T) == typeof(ulong))
			{
				register.uint64_0 = (ulong)(object)value;
				register.uint64_1 = (ulong)(object)value;
			}
			else if (typeof(T) == typeof(long))
			{
				register.int64_0 = (long)(object)value;
				register.int64_1 = (long)(object)value;
			}
			else if (typeof(T) == typeof(float))
			{
				register.single_0 = (float)(object)value;
				register.single_1 = (float)(object)value;
				register.single_2 = (float)(object)value;
				register.single_3 = (float)(object)value;
			}
			else if (typeof(T) == typeof(double))
			{
				register.double_0 = (double)(object)value;
				register.double_1 = (double)(object)value;
			}
		}

		[JitIntrinsic]
		public Vector(T[] values)
			: this(values, 0)
		{
		}

		public unsafe Vector(T[] values, int index)
		{
			this = default(Vector<T>);
			if (values == null)
			{
				throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef);
			}
			if (index < 0 || values.Length - index < Count)
			{
				throw new IndexOutOfRangeException();
			}
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					fixed (byte* ptr = &register.byte_0)
					{
						for (int i = 0; i < Count; i++)
						{
							ptr[i] = (byte)(object)values[i + index];
						}
					}
				}
				else if (typeof(T) == typeof(sbyte))
				{
					fixed (sbyte* ptr2 = &register.sbyte_0)
					{
						for (int j = 0; j < Count; j++)
						{
							ptr2[j] = (sbyte)(object)values[j + index];
						}
					}
				}
				else if (typeof(T) == typeof(ushort))
				{
					fixed (ushort* ptr3 = &register.uint16_0)
					{
						for (int k = 0; k < Count; k++)
						{
							ptr3[k] = (ushort)(object)values[k + index];
						}
					}
				}
				else if (typeof(T) == typeof(short))
				{
					fixed (short* ptr4 = &register.int16_0)
					{
						for (int l = 0; l < Count; l++)
						{
							ptr4[l] = (short)(object)values[l + index];
						}
					}
				}
				else if (typeof(T) == typeof(uint))
				{
					fixed (uint* ptr5 = &register.uint32_0)
					{
						for (int m = 0; m < Count; m++)
						{
							ptr5[m] = (uint)(object)values[m + index];
						}
					}
				}
				else if (typeof(T) == typeof(int))
				{
					fixed (int* ptr6 = &register.int32_0)
					{
						for (int n = 0; n < Count; n++)
						{
							ptr6[n] = (int)(object)values[n + index];
						}
					}
				}
				else if (typeof(T) == typeof(ulong))
				{
					fixed (ulong* ptr7 = &register.uint64_0)
					{
						for (int num = 0; num < Count; num++)
						{
							ptr7[num] = (ulong)(object)values[num + index];
						}
					}
				}
				else if (typeof(T) == typeof(long))
				{
					fixed (long* ptr8 = &register.int64_0)
					{
						for (int num2 = 0; num2 < Count; num2++)
						{
							ptr8[num2] = (long)(object)values[num2 + index];
						}
					}
				}
				else if (typeof(T) == typeof(float))
				{
					fixed (float* ptr9 = &register.single_0)
					{
						for (int num3 = 0; num3 < Count; num3++)
						{
							ptr9[num3] = (float)(object)values[num3 + index];
						}
					}
				}
				else
				{
					if (!(typeof(T) == typeof(double)))
					{
						return;
					}
					fixed (double* ptr10 = &register.double_0)
					{
						for (int num4 = 0; num4 < Count; num4++)
						{
							ptr10[num4] = (double)(object)values[num4 + index];
						}
					}
				}
			}
			else if (typeof(T) == typeof(byte))
			{
				fixed (byte* ptr11 = &register.byte_0)
				{
					*ptr11 = (byte)(object)values[index];
					ptr11[1] = (byte)(object)values[1 + index];
					ptr11[2] = (byte)(object)values[2 + index];
					ptr11[3] = (byte)(object)values[3 + index];
					ptr11[4] = (byte)(object)values[4 + index];
					ptr11[5] = (byte)(object)values[5 + index];
					ptr11[6] = (byte)(object)values[6 + index];
					ptr11[7] = (byte)(object)values[7 + index];
					ptr11[8] = (byte)(object)values[8 + index];
					ptr11[9] = (byte)(object)values[9 + index];
					ptr11[10] = (byte)(object)values[10 + index];
					ptr11[11] = (byte)(object)values[11 + index];
					ptr11[12] = (byte)(object)values[12 + index];
					ptr11[13] = (byte)(object)values[13 + index];
					ptr11[14] = (byte)(object)values[14 + index];
					ptr11[15] = (byte)(object)values[15 + index];
				}
			}
			else if (typeof(T) == typeof(sbyte))
			{
				fixed (sbyte* ptr12 = &register.sbyte_0)
				{
					*ptr12 = (sbyte)(object)values[index];
					ptr12[1] = (sbyte)(object)values[1 + index];
					ptr12[2] = (sbyte)(object)values[2 + index];
					ptr12[3] = (sbyte)(object)values[3 + index];
					ptr12[4] = (sbyte)(object)values[4 + index];
					ptr12[5] = (sbyte)(object)values[5 + index];
					ptr12[6] = (sbyte)(object)values[6 + index];
					ptr12[7] = (sbyte)(object)values[7 + index];
					ptr12[8] = (sbyte)(object)values[8 + index];
					ptr12[9] = (sbyte)(object)values[9 + index];
					ptr12[10] = (sbyte)(object)values[10 + index];
					ptr12[11] = (sbyte)(object)values[11 + index];
					ptr12[12] = (sbyte)(object)values[12 + index];
					ptr12[13] = (sbyte)(object)values[13 + index];
					ptr12[14] = (sbyte)(object)values[14 + index];
					ptr12[15] = (sbyte)(object)values[15 + index];
				}
			}
			else if (typeof(T) == typeof(ushort))
			{
				fixed (ushort* ptr13 = &register.uint16_0)
				{
					*ptr13 = (ushort)(object)values[index];
					ptr13[1] = (ushort)(object)values[1 + index];
					ptr13[2] = (ushort)(object)values[2 + index];
					ptr13[3] = (ushort)(object)values[3 + index];
					ptr13[4] = (ushort)(object)values[4 + index];
					ptr13[5] = (ushort)(object)values[5 + index];
					ptr13[6] = (ushort)(object)values[6 + index];
					ptr13[7] = (ushort)(object)values[7 + index];
				}
			}
			else if (typeof(T) == typeof(short))
			{
				fixed (short* ptr14 = &register.int16_0)
				{
					*ptr14 = (short)(object)values[index];
					ptr14[1] = (short)(object)values[1 + index];
					ptr14[2] = (short)(object)values[2 + index];
					ptr14[3] = (short)(object)values[3 + index];
					ptr14[4] = (short)(object)values[4 + index];
					ptr14[5] = (short)(object)values[5 + index];
					ptr14[6] = (short)(object)values[6 + index];
					ptr14[7] = (short)(object)values[7 + index];
				}
			}
			else if (typeof(T) == typeof(uint))
			{
				fixed (uint* ptr15 = &register.uint32_0)
				{
					*ptr15 = (uint)(object)values[index];
					ptr15[1] = (uint)(object)values[1 + index];
					ptr15[2] = (uint)(object)values[2 + index];
					ptr15[3] = (uint)(object)values[3 + index];
				}
			}
			else if (typeof(T) == typeof(int))
			{
				fixed (int* ptr16 = &register.int32_0)
				{
					*ptr16 = (int)(object)values[index];
					ptr16[1] = (int)(object)values[1 + index];
					ptr16[2] = (int)(object)values[2 + index];
					ptr16[3] = (int)(object)values[3 + index];
				}
			}
			else if (typeof(T) == typeof(ulong))
			{
				fixed (ulong* ptr17 = &register.uint64_0)
				{
					*ptr17 = (ulong)(object)values[index];
					ptr17[1] = (ulong)(object)values[1 + index];
				}
			}
			else if (typeof(T) == typeof(long))
			{
				fixed (long* ptr18 = &register.int64_0)
				{
					*ptr18 = (long)(object)values[index];
					ptr18[1] = (long)(object)values[1 + index];
				}
			}
			else if (typeof(T) == typeof(float))
			{
				fixed (float* ptr19 = &register.single_0)
				{
					*ptr19 = (float)(object)values[index];
					ptr19[1] = (float)(object)values[1 + index];
					ptr19[2] = (float)(object)values[2 + index];
					ptr19[3] = (float)(object)values[3 + index];
				}
			}
			else if (typeof(T) == typeof(double))
			{
				fixed (double* ptr20 = &register.double_0)
				{
					*ptr20 = (double)(object)values[index];
					ptr20[1] = (double)(object)values[1 + index];
				}
			}
		}

		internal unsafe Vector(void* dataPointer)
			: this(dataPointer, 0)
		{
		}

		internal unsafe Vector(void* dataPointer, int offset)
		{
			this = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				byte* ptr = (byte*)dataPointer;
				ptr += offset;
				fixed (byte* ptr2 = &register.byte_0)
				{
					for (int i = 0; i < Count; i++)
					{
						ptr2[i] = ptr[i];
					}
				}
				return;
			}
			if (typeof(T) == typeof(sbyte))
			{
				sbyte* ptr3 = (sbyte*)dataPointer;
				ptr3 += offset;
				fixed (sbyte* ptr4 = &register.sbyte_0)
				{
					for (int j = 0; j < Count; j++)
					{
						ptr4[j] = ptr3[j];
					}
				}
				return;
			}
			if (typeof(T) == typeof(ushort))
			{
				ushort* ptr5 = (ushort*)dataPointer;
				ptr5 += offset;
				fixed (ushort* ptr6 = &register.uint16_0)
				{
					for (int k = 0; k < Count; k++)
					{
						ptr6[k] = ptr5[k];
					}
				}
				return;
			}
			if (typeof(T) == typeof(short))
			{
				short* ptr7 = (short*)dataPointer;
				ptr7 += offset;
				fixed (short* ptr8 = &register.int16_0)
				{
					for (int l = 0; l < Count; l++)
					{
						ptr8[l] = ptr7[l];
					}
				}
				return;
			}
			if (typeof(T) == typeof(uint))
			{
				uint* ptr9 = (uint*)dataPointer;
				ptr9 += offset;
				fixed (uint* ptr10 = &register.uint32_0)
				{
					for (int m = 0; m < Count; m++)
					{
						ptr10[m] = ptr9[m];
					}
				}
				return;
			}
			if (typeof(T) == typeof(int))
			{
				int* ptr11 = (int*)dataPointer;
				ptr11 += offset;
				fixed (int* ptr12 = &register.int32_0)
				{
					for (int n = 0; n < Count; n++)
					{
						ptr12[n] = ptr11[n];
					}
				}
				return;
			}
			if (typeof(T) == typeof(ulong))
			{
				ulong* ptr13 = (ulong*)dataPointer;
				ptr13 += offset;
				fixed (ulong* ptr14 = &register.uint64_0)
				{
					for (int num = 0; num < Count; num++)
					{
						ptr14[num] = ptr13[num];
					}
				}
				return;
			}
			if (typeof(T) == typeof(long))
			{
				long* ptr15 = (long*)dataPointer;
				ptr15 += offset;
				fixed (long* ptr16 = &register.int64_0)
				{
					for (int num2 = 0; num2 < Count; num2++)
					{
						ptr16[num2] = ptr15[num2];
					}
				}
				return;
			}
			if (typeof(T) == typeof(float))
			{
				float* ptr17 = (float*)dataPointer;
				ptr17 += offset;
				fixed (float* ptr18 = &register.single_0)
				{
					for (int num3 = 0; num3 < Count; num3++)
					{
						ptr18[num3] = ptr17[num3];
					}
				}
				return;
			}
			if (typeof(T) == typeof(double))
			{
				double* ptr19 = (double*)dataPointer;
				ptr19 += offset;
				fixed (double* ptr20 = &register.double_0)
				{
					for (int num4 = 0; num4 < Count; num4++)
					{
						ptr20[num4] = ptr19[num4];
					}
				}
				return;
			}
			throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
		}

		private Vector(ref System.Numerics.Register existingRegister)
		{
			register = existingRegister;
		}

		[JitIntrinsic]
		public void CopyTo(T[] destination)
		{
			CopyTo(destination, 0);
		}

		[JitIntrinsic]
		public unsafe void CopyTo(T[] destination, int startIndex)
		{
			if (destination == null)
			{
				throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef);
			}
			if (startIndex < 0 || startIndex >= destination.Length)
			{
				throw new ArgumentOutOfRangeException("startIndex", System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, startIndex));
			}
			if (destination.Length - startIndex < Count)
			{
				throw new ArgumentException(System.SR.Format(System.SR.Arg_ElementsInSourceIsGreaterThanDestination, startIndex));
			}
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					fixed (byte* ptr = (byte[])(object)destination)
					{
						for (int i = 0; i < Count; i++)
						{
							ptr[startIndex + i] = (byte)(object)this[i];
						}
					}
				}
				else if (typeof(T) == typeof(sbyte))
				{
					fixed (sbyte* ptr2 = (sbyte[])(object)destination)
					{
						for (int j = 0; j < Count; j++)
						{
							ptr2[startIndex + j] = (sbyte)(object)this[j];
						}
					}
				}
				else if (typeof(T) == typeof(ushort))
				{
					fixed (ushort* ptr3 = (ushort[])(object)destination)
					{
						for (int k = 0; k < Count; k++)
						{
							ptr3[startIndex + k] = (ushort)(object)this[k];
						}
					}
				}
				else if (typeof(T) == typeof(short))
				{
					fixed (short* ptr4 = (short[])(object)destination)
					{
						for (int l = 0; l < Count; l++)
						{
							ptr4[startIndex + l] = (short)(object)this[l];
						}
					}
				}
				else if (typeof(T) == typeof(uint))
				{
					fixed (uint* ptr5 = (uint[])(object)destination)
					{
						for (int m = 0; m < Count; m++)
						{
							ptr5[startIndex + m] = (uint)(object)this[m];
						}
					}
				}
				else if (typeof(T) == typeof(int))
				{
					fixed (int* ptr6 = (int[])(object)destination)
					{
						for (int n = 0; n < Count; n++)
						{
							ptr6[startIndex + n] = (int)(object)this[n];
						}
					}
				}
				else if (typeof(T) == typeof(ulong))
				{
					fixed (ulong* ptr7 = (ulong[])(object)destination)
					{
						for (int num = 0; num < Count; num++)
						{
							ptr7[startIndex + num] = (ulong)(object)this[num];
						}
					}
				}
				else if (typeof(T) == typeof(long))
				{
					fixed (long* ptr8 = (long[])(object)destination)
					{
						for (int num2 = 0; num2 < Count; num2++)
						{
							ptr8[startIndex + num2] = (long)(object)this[num2];
						}
					}
				}
				else if (typeof(T) == typeof(float))
				{
					fixed (float* ptr9 = (float[])(object)destination)
					{
						for (int num3 = 0; num3 < Count; num3++)
						{
							ptr9[startIndex + num3] = (float)(object)this[num3];
						}
					}
				}
				else
				{
					if (!(typeof(T) == typeof(double)))
					{
						return;
					}
					fixed (double* ptr10 = (double[])(object)destination)
					{
						for (int num4 = 0; num4 < Count; num4++)
						{
							ptr10[startIndex + num4] = (double)(object)this[num4];
						}
					}
				}
			}
			else if (typeof(T) == typeof(byte))
			{
				fixed (byte* ptr11 = (byte[])(object)destination)
				{
					ptr11[startIndex] = register.byte_0;
					ptr11[startIndex + 1] = register.byte_1;
					ptr11[startIndex + 2] = register.byte_2;
					ptr11[startIndex + 3] = register.byte_3;
					ptr11[startIndex + 4] = register.byte_4;
					ptr11[startIndex + 5] = register.byte_5;
					ptr11[startIndex + 6] = register.byte_6;
					ptr11[startIndex + 7] = register.byte_7;
					ptr11[startIndex + 8] = register.byte_8;
					ptr11[startIndex + 9] = register.byte_9;
					ptr11[startIndex + 10] = register.byte_10;
					ptr11[startIndex + 11] = register.byte_11;
					ptr11[startIndex + 12] = register.byte_12;
					ptr11[startIndex + 13] = register.byte_13;
					ptr11[startIndex + 14] = register.byte_14;
					ptr11[startIndex + 15] = register.byte_15;
				}
			}
			else if (typeof(T) == typeof(sbyte))
			{
				fixed (sbyte* ptr12 = (sbyte[])(object)destination)
				{
					ptr12[startIndex] = register.sbyte_0;
					ptr12[startIndex + 1] = register.sbyte_1;
					ptr12[startIndex + 2] = register.sbyte_2;
					ptr12[startIndex + 3] = register.sbyte_3;
					ptr12[startIndex + 4] = register.sbyte_4;
					ptr12[startIndex + 5] = register.sbyte_5;
					ptr12[startIndex + 6] = register.sbyte_6;
					ptr12[startIndex + 7] = register.sbyte_7;
					ptr12[startIndex + 8] = register.sbyte_8;
					ptr12[startIndex + 9] = register.sbyte_9;
					ptr12[startIndex + 10] = register.sbyte_10;
					ptr12[startIndex + 11] = register.sbyte_11;
					ptr12[startIndex + 12] = register.sbyte_12;
					ptr12[startIndex + 13] = register.sbyte_13;
					ptr12[startIndex + 14] = register.sbyte_14;
					ptr12[startIndex + 15] = register.sbyte_15;
				}
			}
			else if (typeof(T) == typeof(ushort))
			{
				fixed (ushort* ptr13 = (ushort[])(object)destination)
				{
					ptr13[startIndex] = register.uint16_0;
					ptr13[startIndex + 1] = register.uint16_1;
					ptr13[startIndex + 2] = register.uint16_2;
					ptr13[startIndex + 3] = register.uint16_3;
					ptr13[startIndex + 4] = register.uint16_4;
					ptr13[startIndex + 5] = register.uint16_5;
					ptr13[startIndex + 6] = register.uint16_6;
					ptr13[startIndex + 7] = register.uint16_7;
				}
			}
			else if (typeof(T) == typeof(short))
			{
				fixed (short* ptr14 = (short[])(object)destination)
				{
					ptr14[startIndex] = register.int16_0;
					ptr14[startIndex + 1] = register.int16_1;
					ptr14[startIndex + 2] = register.int16_2;
					ptr14[startIndex + 3] = register.int16_3;
					ptr14[startIndex + 4] = register.int16_4;
					ptr14[startIndex + 5] = register.int16_5;
					ptr14[startIndex + 6] = register.int16_6;
					ptr14[startIndex + 7] = register.int16_7;
				}
			}
			else if (typeof(T) == typeof(uint))
			{
				fixed (uint* ptr15 = (uint[])(object)destination)
				{
					ptr15[startIndex] = register.uint32_0;
					ptr15[startIndex + 1] = register.uint32_1;
					ptr15[startIndex + 2] = register.uint32_2;
					ptr15[startIndex + 3] = register.uint32_3;
				}
			}
			else if (typeof(T) == typeof(int))
			{
				fixed (int* ptr16 = (int[])(object)destination)
				{
					ptr16[startIndex] = register.int32_0;
					ptr16[startIndex + 1] = register.int32_1;
					ptr16[startIndex + 2] = register.int32_2;
					ptr16[startIndex + 3] = register.int32_3;
				}
			}
			else if (typeof(T) == typeof(ulong))
			{
				fixed (ulong* ptr17 = (ulong[])(object)destination)
				{
					ptr17[startIndex] = register.uint64_0;
					ptr17[startIndex + 1] = register.uint64_1;
				}
			}
			else if (typeof(T) == typeof(long))
			{
				fixed (long* ptr18 = (long[])(object)destination)
				{
					ptr18[startIndex] = register.int64_0;
					ptr18[startIndex + 1] = register.int64_1;
				}
			}
			else if (typeof(T) == typeof(float))
			{
				fixed (float* ptr19 = (float[])(object)destination)
				{
					ptr19[startIndex] = register.single_0;
					ptr19[startIndex + 1] = register.single_1;
					ptr19[startIndex + 2] = register.single_2;
					ptr19[startIndex + 3] = register.single_3;
				}
			}
			else if (typeof(T) == typeof(double))
			{
				fixed (double* ptr20 = (double[])(object)destination)
				{
					ptr20[startIndex] = register.double_0;
					ptr20[startIndex + 1] = register.double_1;
				}
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public override bool Equals(object obj)
		{
			if (!(obj is Vector<T>))
			{
				return false;
			}
			return Equals((Vector<T>)obj);
		}

		[JitIntrinsic]
		public bool Equals(Vector<T> other)
		{
			if (Vector.IsHardwareAccelerated)
			{
				for (int i = 0; i < Count; i++)
				{
					if (!ScalarEquals(this[i], other[i]))
					{
						return false;
					}
				}
				return true;
			}
			if (typeof(T) == typeof(byte))
			{
				if (register.byte_0 == other.register.byte_0 && register.byte_1 == other.register.byte_1 && register.byte_2 == other.register.byte_2 && register.byte_3 == other.register.byte_3 && register.byte_4 == other.register.byte_4 && register.byte_5 == other.register.byte_5 && register.byte_6 == other.register.byte_6 && register.byte_7 == other.register.byte_7 && register.byte_8 == other.register.byte_8 && register.byte_9 == other.register.byte_9 && register.byte_10 == other.register.byte_10 && register.byte_11 == other.register.byte_11 && register.byte_12 == other.register.byte_12 && register.byte_13 == other.register.byte_13 && register.byte_14 == other.register.byte_14)
				{
					return register.byte_15 == other.register.byte_15;
				}
				return false;
			}
			if (typeof(T) == typeof(sbyte))
			{
				if (register.sbyte_0 == other.register.sbyte_0 && register.sbyte_1 == other.register.sbyte_1 && register.sbyte_2 == other.register.sbyte_2 && register.sbyte_3 == other.register.sbyte_3 && register.sbyte_4 == other.register.sbyte_4 && register.sbyte_5 == other.register.sbyte_5 && register.sbyte_6 == other.register.sbyte_6 && register.sbyte_7 == other.register.sbyte_7 && register.sbyte_8 == other.register.sbyte_8 && register.sbyte_9 == other.register.sbyte_9 && register.sbyte_10 == other.register.sbyte_10 && register.sbyte_11 == other.register.sbyte_11 && register.sbyte_12 == other.register.sbyte_12 && register.sbyte_13 == other.register.sbyte_13 && register.sbyte_14 == other.register.sbyte_14)
				{
					return register.sbyte_15 == other.register.sbyte_15;
				}
				return false;
			}
			if (typeof(T) == typeof(ushort))
			{
				if (register.uint16_0 == other.register.uint16_0 && register.uint16_1 == other.register.uint16_1 && register.uint16_2 == other.register.uint16_2 && register.uint16_3 == other.register.uint16_3 && register.uint16_4 == other.register.uint16_4 && register.uint16_5 == other.register.uint16_5 && register.uint16_6 == other.register.uint16_6)
				{
					return register.uint16_7 == other.register.uint16_7;
				}
				return false;
			}
			if (typeof(T) == typeof(short))
			{
				if (register.int16_0 == other.register.int16_0 && register.int16_1 == other.register.int16_1 && register.int16_2 == other.register.int16_2 && register.int16_3 == other.register.int16_3 && register.int16_4 == other.register.int16_4 && register.int16_5 == other.register.int16_5 && register.int16_6 == other.register.int16_6)
				{
					return register.int16_7 == other.register.int16_7;
				}
				return false;
			}
			if (typeof(T) == typeof(uint))
			{
				if (register.uint32_0 == other.register.uint32_0 && register.uint32_1 == other.register.uint32_1 && register.uint32_2 == other.register.uint32_2)
				{
					return register.uint32_3 == other.register.uint32_3;
				}
				return false;
			}
			if (typeof(T) == typeof(int))
			{
				if (register.int32_0 == other.register.int32_0 && register.int32_1 == other.register.int32_1 && register.int32_2 == other.register.int32_2)
				{
					return register.int32_3 == other.register.int32_3;
				}
				return false;
			}
			if (typeof(T) == typeof(ulong))
			{
				if (register.uint64_0 == other.register.uint64_0)
				{
					return register.uint64_1 == other.register.uint64_1;
				}
				return false;
			}
			if (typeof(T) == typeof(long))
			{
				if (register.int64_0 == other.register.int64_0)
				{
					return register.int64_1 == other.register.int64_1;
				}
				return false;
			}
			if (typeof(T) == typeof(float))
			{
				if (register.single_0 == other.register.single_0 && register.single_1 == other.register.single_1 && register.single_2 == other.register.single_2)
				{
					return register.single_3 == other.register.single_3;
				}
				return false;
			}
			if (typeof(T) == typeof(double))
			{
				if (register.double_0 == other.register.double_0)
				{
					return register.double_1 == other.register.double_1;
				}
				return false;
			}
			throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
		}

		public override int GetHashCode()
		{
			int num = 0;
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					for (int i = 0; i < Count; i++)
					{
						num = HashHelpers.Combine(num, ((byte)(object)this[i]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(sbyte))
				{
					for (int j = 0; j < Count; j++)
					{
						num = HashHelpers.Combine(num, ((sbyte)(object)this[j]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(ushort))
				{
					for (int k = 0; k < Count; k++)
					{
						num = HashHelpers.Combine(num, ((ushort)(object)this[k]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(short))
				{
					for (int l = 0; l < Count; l++)
					{
						num = HashHelpers.Combine(num, ((short)(object)this[l]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(uint))
				{
					for (int m = 0; m < Count; m++)
					{
						num = HashHelpers.Combine(num, ((uint)(object)this[m]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(int))
				{
					for (int n = 0; n < Count; n++)
					{
						num = HashHelpers.Combine(num, ((int)(object)this[n]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(ulong))
				{
					for (int num2 = 0; num2 < Count; num2++)
					{
						num = HashHelpers.Combine(num, ((ulong)(object)this[num2]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(long))
				{
					for (int num3 = 0; num3 < Count; num3++)
					{
						num = HashHelpers.Combine(num, ((long)(object)this[num3]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(float))
				{
					for (int num4 = 0; num4 < Count; num4++)
					{
						num = HashHelpers.Combine(num, ((float)(object)this[num4]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(double))
				{
					for (int num5 = 0; num5 < Count; num5++)
					{
						num = HashHelpers.Combine(num, ((double)(object)this[num5]).GetHashCode());
					}
					return num;
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
			if (typeof(T) == typeof(byte))
			{
				num = HashHelpers.Combine(num, register.byte_0.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_1.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_2.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_3.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_4.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_5.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_6.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_7.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_8.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_9.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_10.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_11.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_12.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_13.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_14.GetHashCode());
				return HashHelpers.Combine(num, register.byte_15.GetHashCode());
			}
			if (typeof(T) == typeof(sbyte))
			{
				num = HashHelpers.Combine(num, register.sbyte_0.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_1.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_2.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_3.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_4.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_5.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_6.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_7.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_8.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_9.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_10.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_11.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_12.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_13.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_14.GetHashCode());
				return HashHelpers.Combine(num, register.sbyte_15.GetHashCode());
			}
			if (typeof(T) == typeof(ushort))
			{
				num = HashHelpers.Combine(num, register.uint16_0.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_1.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_2.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_3.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_4.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_5.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_6.GetHashCode());
				return HashHelpers.Combine(num, register.uint16_7.GetHashCode());
			}
			if (typeof(T) == typeof(short))
			{
				num = HashHelpers.Combine(num, register.int16_0.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_1.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_2.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_3.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_4.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_5.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_6.GetHashCode());
				return HashHelpers.Combine(num, register.int16_7.GetHashCode());
			}
			if (typeof(T) == typeof(uint))
			{
				num = HashHelpers.Combine(num, register.uint32_0.GetHashCode());
				num = HashHelpers.Combine(num, register.uint32_1.GetHashCode());
				num = HashHelpers.Combine(num, register.uint32_2.GetHashCode());
				return HashHelpers.Combine(num, register.uint32_3.GetHashCode());
			}
			if (typeof(T) == typeof(int))
			{
				num = HashHelpers.Combine(num, register.int32_0.GetHashCode());
				num = HashHelpers.Combine(num, register.int32_1.GetHashCode());
				num = HashHelpers.Combine(num, register.int32_2.GetHashCode());
				return HashHelpers.Combine(num, register.int32_3.GetHashCode());
			}
			if (typeof(T) == typeof(ulong))
			{
				num = HashHelpers.Combine(num, register.uint64_0.GetHashCode());
				return HashHelpers.Combine(num, register.uint64_1.GetHashCode());
			}
			if (typeof(T) == typeof(long))
			{
				num = HashHelpers.Combine(num, register.int64_0.GetHashCode());
				return HashHelpers.Combine(num, register.int64_1.GetHashCode());
			}
			if (typeof(T) == typeof(float))
			{
				num = HashHelpers.Combine(num, register.single_0.GetHashCode());
				num = HashHelpers.Combine(num, register.single_1.GetHashCode());
				num = HashHelpers.Combine(num, register.single_2.GetHashCode());
				return HashHelpers.Combine(num, register.single_3.GetHashCode());
			}
			if (typeof(T) == typeof(double))
			{
				num = HashHelpers.Combine(num, register.double_0.GetHashCode());
				return HashHelpers.Combine(num, register.double_1.GetHashCode());
			}
			throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
		}

		public override string ToString()
		{
			return ToString("G", CultureInfo.CurrentCulture);
		}

		public string ToString(string format)
		{
			return ToString(format, CultureInfo.CurrentCulture);
		}

		public string ToString(string format, IFormatProvider formatProvider)
		{
			StringBuilder stringBuilder = new StringBuilder();
			string numberGroupSeparator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator;
			stringBuilder.Append('<');
			for (int i = 0; i < Count - 1; i++)
			{
				stringBuilder.Append(((IFormattable)(object)this[i]).ToString(format, formatProvider));
				stringBuilder.Append(numberGroupSeparator);
				stringBuilder.Append(' ');
			}
			stringBuilder.Append(((IFormattable)(object)this[Count - 1]).ToString(format, formatProvider));
			stringBuilder.Append('>');
			return stringBuilder.ToString();
		}

		public unsafe static Vector<T>operator +(Vector<T> left, Vector<T> right)
		{
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int i = 0; i < Count; i++)
					{
						ptr[i] = (byte)(object)ScalarAdd(left[i], right[i]);
					}
					return new Vector<T>(ptr);
				}
				if (typeof(T) == typeof(sbyte))
				{
					sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int j = 0; j < Count; j++)
					{
						ptr2[j] = (sbyte)(object)ScalarAdd(left[j], right[j]);
					}
					return new Vector<T>(ptr2);
				}
				if (typeof(T) == typeof(ushort))
				{
					ushort* ptr3 = stackalloc ushort[Count];
					for (int k = 0; k < Count; k++)
					{
						ptr3[k] = (ushort)(object)ScalarAdd(left[k], right[k]);
					}
					return new Vector<T>(ptr3);
				}
				if (typeof(T) == typeof(short))
				{
					short* ptr4 = stackalloc short[Count];
					for (int l = 0; l < Count; l++)
					{
						ptr4[l] = (short)(object)ScalarAdd(left[l], right[l]);
					}
					return new Vector<T>(ptr4);
				}
				if (typeof(T) == typeof(uint))
				{
					uint* ptr5 = stackalloc uint[Count];
					for (int m = 0; m < Count; m++)
					{
						ptr5[m] = (uint)(object)ScalarAdd(left[m], right[m]);
					}
					return new Vector<T>(ptr5);
				}
				if (typeof(T) == typeof(int))
				{
					int* ptr6 = stackalloc int[Count];
					for (int n = 0; n < Count; n++)
					{
						ptr6[n] = (int)(object)ScalarAdd(left[n], right[n]);
					}
					return new Vector<T>(ptr6);
				}
				if (typeof(T) == typeof(ulong))
				{
					ulong* ptr7 = stackalloc ulong[Count];
					for (int num = 0; num < Count; num++)
					{
						ptr7[num] = (ulong)(object)ScalarAdd(left[num], right[num]);
					}
					return new Vector<T>(ptr7);
				}
				if (typeof(T) == typeof(long))
				{
					long* ptr8 = stackalloc long[Count];
					for (int num2 = 0; num2 < Count; num2++)
					{
						ptr8[num2] = (long)(object)ScalarAdd(left[num2], right[num2]);
					}
					return new Vector<T>(ptr8);
				}
				if (typeof(T) == typeof(float))
				{
					float* ptr9 = stackalloc float[Count];
					for (int num3 = 0; num3 < Count; num3++)
					{
						ptr9[num3] = (float)(object)ScalarAdd(left[num3], right[num3]);
					}
					return new Vector<T>(ptr9);
				}
				if (typeof(T) == typeof(double))
				{
					double* ptr10 = stackalloc double[Count];
					for (int num4 = 0; num4 < Count; num4++)
					{
						ptr10[num4] = (double)(object)ScalarAdd(left[num4], right[num4]);
					}
					return new Vector<T>(ptr10);
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(left.register.byte_0 + right.register.byte_0);
				result.register.byte_1 = (byte)(left.register.byte_1 + right.register.byte_1);
				result.register.byte_2 = (byte)(left.register.byte_2 + right.register.byte_2);
				result.register.byte_3 = (byte)(left.register.byte_3 + right.register.byte_3);
				result.register.byte_4 = (byte)(left.register.byte_4 + right.register.byte_4);
				result.register.byte_5 = (byte)(left.register.byte_5 + right.register.byte_5);
				result.register.byte_6 = (byte)(left.register.byte_6 + right.register.byte_6);
				result.register.byte_7 = (byte)(left.register.byte_7 + right.register.byte_7);
				result.register.byte_8 = (byte)(left.register.byte_8 + right.register.byte_8);
				result.register.byte_9 = (byte)(left.register.byte_9 + right.register.byte_9);
				result.register.byte_10 = (byte)(left.register.byte_10 + right.register.byte_10);
				result.register.byte_11 = (byte)(left.register.byte_11 + right.register.byte_11);
				result.register.byte_12 = (byte)(left.register.byte_12 + right.register.byte_12);
				result.register.byte_13 = (byte)(left.register.byte_13 + right.register.byte_13);
				result.register.byte_14 = (byte)(left.register.byte_14 + right.register.byte_14);
				result.register.byte_15 = (byte)(left.register.byte_15 + right.register.byte_15);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 + right.register.sbyte_0);
				result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 + right.register.sbyte_1);
				result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 + right.register.sbyte_2);
				result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 + right.register.sbyte_3);
				result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 + right.register.sbyte_4);
				result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 + right.register.sbyte_5);
				result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 + right.register.sbyte_6);
				result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 + right.register.sbyte_7);
				result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 + right.register.sbyte_8);
				result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 + right.register.sbyte_9);
				result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 + right.register.sbyte_10);
				result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 + right.register.sbyte_11);
				result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 + right.register.sbyte_12);
				result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 + right.register.sbyte_13);
				result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 + right.register.sbyte_14);
				result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 + right.register.sbyte_15);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(left.register.uint16_0 + right.register.uint16_0);
				result.register.uint16_1 = (ushort)(left.register.uint16_1 + right.register.uint16_1);
				result.register.uint16_2 = (ushort)(left.register.uint16_2 + right.register.uint16_2);
				result.register.uint16_3 = (ushort)(left.register.uint16_3 + right.register.uint16_3);
				result.register.uint16_4 = (ushort)(left.register.uint16_4 + right.register.uint16_4);
				result.register.uint16_5 = (ushort)(left.register.uint16_5 + right.register.uint16_5);
				result.register.uint16_6 = (ushort)(left.register.uint16_6 + right.register.uint16_6);
				result.register.uint16_7 = (ushort)(left.register.uint16_7 + right.register.uint16_7);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(left.register.int16_0 + right.register.int16_0);
				result.register.int16_1 = (short)(left.register.int16_1 + right.register.int16_1);
				result.register.int16_2 = (short)(left.register.int16_2 + right.register.int16_2);
				result.register.int16_3 = (short)(left.register.int16_3 + right.register.int16_3);
				result.register.int16_4 = (short)(left.register.int16_4 + right.register.int16_4);
				result.register.int16_5 = (short)(left.register.int16_5 + right.register.int16_5);
				result.register.int16_6 = (short)(left.register.int16_6 + right.register.int16_6);
				result.register.int16_7 = (short)(left.register.int16_7 + right.register.int16_7);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = left.register.uint32_0 + right.register.uint32_0;
				result.register.uint32_1 = left.register.uint32_1 + right.register.uint32_1;
				result.register.uint32_2 = left.register.uint32_2 + right.register.uint32_2;
				result.register.uint32_3 = left.register.uint32_3 + right.register.uint32_3;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = left.register.int32_0 + right.register.int32_0;
				result.register.int32_1 = left.register.int32_1 + right.register.int32_1;
				result.register.int32_2 = left.register.int32_2 + right.register.int32_2;
				result.register.int32_3 = left.register.int32_3 + right.register.int32_3;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = left.register.uint64_0 + right.register.uint64_0;
				result.register.uint64_1 = left.register.uint64_1 + right.register.uint64_1;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = left.register.int64_0 + right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 + right.register.int64_1;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = left.register.single_0 + right.register.single_0;
				result.register.single_1 = left.register.single_1 + right.register.single_1;
				result.register.single_2 = left.register.single_2 + right.register.single_2;
				result.register.single_3 = left.register.single_3 + right.register.single_3;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = left.register.double_0 + right.register.double_0;
				result.register.double_1 = left.register.double_1 + right.register.double_1;
			}
			return result;
		}

		public unsafe static Vector<T>operator -(Vector<T> left, Vector<T> right)
		{
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int i = 0; i < Count; i++)
					{
						ptr[i] = (byte)(object)ScalarSubtract(left[i], right[i]);
					}
					return new Vector<T>(ptr);
				}
				if (typeof(T) == typeof(sbyte))
				{
					sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int j = 0; j < Count; j++)
					{
						ptr2[j] = (sbyte)(object)ScalarSubtract(left[j], right[j]);
					}
					return new Vector<T>(ptr2);
				}
				if (typeof(T) == typeof(ushort))
				{
					ushort* ptr3 = stackalloc ushort[Count];
					for (int k = 0; k < Count; k++)
					{
						ptr3[k] = (ushort)(object)ScalarSubtract(left[k], right[k]);
					}
					return new Vector<T>(ptr3);
				}
				if (typeof(T) == typeof(short))
				{
					short* ptr4 = stackalloc short[Count];
					for (int l = 0; l < Count; l++)
					{
						ptr4[l] = (short)(object)ScalarSubtract(left[l], right[l]);
					}
					return new Vector<T>(ptr4);
				}
				if (typeof(T) == typeof(uint))
				{
					uint* ptr5 = stackalloc uint[Count];
					for (int m = 0; m < Count; m++)
					{
						ptr5[m] = (uint)(object)ScalarSubtract(left[m], right[m]);
					}
					return new Vector<T>(ptr5);
				}
				if (typeof(T) == typeof(int))
				{
					int* ptr6 = stackalloc int[Count];
					for (int n = 0; n < Count; n++)
					{
						ptr6[n] = (int)(object)ScalarSubtract(left[n], right[n]);
					}
					return new Vector<T>(ptr6);
				}
				if (typeof(T) == typeof(ulong))
				{
					ulong* ptr7 = stackalloc ulong[Count];
					for (int num = 0; num < Count; num++)
					{
						ptr7[num] = (ulong)(object)ScalarSubtract(left[num], right[num]);
					}
					return new Vector<T>(ptr7);
				}
				if (typeof(T) == typeof(long))
				{
					long* ptr8 = stackalloc long[Count];
					for (int num2 = 0; num2 < Count; num2++)
					{
						ptr8[num2] = (long)(object)ScalarSubtract(left[num2], right[num2]);
					}
					return new Vector<T>(ptr8);
				}
				if (typeof(T) == typeof(float))
				{
					float* ptr9 = stackalloc float[Count];
					for (int num3 = 0; num3 < Count; num3++)
					{
						ptr9[num3] = (float)(object)ScalarSubtract(left[num3], right[num3]);
					}
					return new Vector<T>(ptr9);
				}
				if (typeof(T) == typeof(double))
				{
					double* ptr10 = stackalloc double[Count];
					for (int num4 = 0; num4 < Count; num4++)
					{
						ptr10[num4] = (double)(object)ScalarSubtract(left[num4], right[num4]);
					}
					return new Vector<T>(ptr10);
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(left.register.byte_0 - right.register.byte_0);
				result.register.byte_1 = (byte)(left.register.byte_1 - right.register.byte_1);
				result.register.byte_2 = (byte)(left.register.byte_2 - right.register.byte_2);
				result.register.byte_3 = (byte)(left.register.byte_3 - right.register.byte_3);
				result.register.byte_4 = (byte)(left.register.byte_4 - right.register.byte_4);
				result.register.byte_5 = (byte)(left.register.byte_5 - right.register.byte_5);
				result.register.byte_6 = (byte)(left.register.byte_6 - right.register.byte_6);
				result.register.byte_7 = (byte)(left.register.byte_7 - right.register.byte_7);
				result.register.byte_8 = (byte)(left.register.byte_8 - right.register.byte_8);
				result.register.byte_9 = (byte)(left.register.byte_9 - right.register.byte_9);
				result.register.byte_10 = (byte)(left.register.byte_10 - right.register.byte_10);
				result.register.byte_11 = (byte)(left.register.byte_11 - right.register.byte_11);
				result.register.byte_12 = (byte)(left.register.byte_12 - right.register.byte_12);
				result.register.byte_13 = (byte)(left.register.byte_13 - right.register.byte_13);
				result.register.byte_14 = (byte)(left.register.byte_14 - right.register.byte_14);
				result.register.byte_15 = (byte)(left.register.byte_15 - right.register.byte_15);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 - right.register.sbyte_0);
				result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 - right.register.sbyte_1);
				result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 - right.register.sbyte_2);
				result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 - right.register.sbyte_3);
				result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 - right.register.sbyte_4);
				result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 - right.register.sbyte_5);
				result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 - right.register.sbyte_6);
				result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 - right.register.sbyte_7);
				result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 - right.register.sbyte_8);
				result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 - right.register.sbyte_9);
				result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 - right.register.sbyte_10);
				result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 - right.register.sbyte_11);
				result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 - right.register.sbyte_12);
				result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 - right.register.sbyte_13);
				result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 - right.register.sbyte_14);
				result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 - right.register.sbyte_15);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(left.register.uint16_0 - right.register.uint16_0);
				result.register.uint16_1 = (ushort)(left.register.uint16_1 - right.register.uint16_1);
				result.register.uint16_2 = (ushort)(left.register.uint16_2 - right.register.uint16_2);
				result.register.uint16_3 = (ushort)(left.register.uint16_3 - right.register.uint16_3);
				result.register.uint16_4 = (ushort)(left.register.uint16_4 - right.register.uint16_4);
				result.register.uint16_5 = (ushort)(left.register.uint16_5 - right.register.uint16_5);
				result.register.uint16_6 = (ushort)(left.register.uint16_6 - right.register.uint16_6);
				result.register.uint16_7 = (ushort)(left.register.uint16_7 - right.register.uint16_7);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(left.register.int16_0 - right.register.int16_0);
				result.register.int16_1 = (short)(left.register.int16_1 - right.register.int16_1);
				result.register.int16_2 = (short)(left.register.int16_2 - right.register.int16_2);
				result.register.int16_3 = (short)(left.register.int16_3 - right.register.int16_3);
				result.register.int16_4 = (short)(left.register.int16_4 - right.register.int16_4);
				result.register.int16_5 = (short)(left.register.int16_5 - right.register.int16_5);
				result.register.int16_6 = (short)(left.register.int16_6 - right.register.int16_6);
				result.register.int16_7 = (short)(left.register.int16_7 - right.register.int16_7);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = left.register.uint32_0 - right.register.uint32_0;
				result.register.uint32_1 = left.register.uint32_1 - right.register.uint32_1;
				result.register.uint32_2 = left.register.uint32_2 - right.register.uint32_2;
				result.register.uint32_3 = left.register.uint32_3 - right.register.uint32_3;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = left.register.int32_0 - right.register.int32_0;
				result.register.int32_1 = left.register.int32_1 - right.register.int32_1;
				result.register.int32_2 = left.register.int32_2 - right.register.int32_2;
				result.register.int32_3 = left.register.int32_3 - right.register.int32_3;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = left.register.uint64_0 - right.register.uint64_0;
				result.register.uint64_1 = left.register.uint64_1 - right.register.uint64_1;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = left.register.int64_0 - right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 - right.register.int64_1;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = left.register.single_0 - right.register.single_0;
				result.register.single_1 = left.register.single_1 - right.register.single_1;
				result.register.single_2 = left.register.single_2 - right.register.single_2;
				result.register.single_3 = left.register.single_3 - right.register.single_3;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = left.register.double_0 - right.register.double_0;
				result.register.double_1 = left.register.double_1 - right.register.double_1;
			}
			return result;
		}

		public unsafe static Vector<T>operator *(Vector<T> left, Vector<T> right)
		{
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int i = 0; i < Count; i++)
					{
						ptr[i] = (byte)(object)ScalarMultiply(left[i], right[i]);
					}
					return new Vector<T>(ptr);
				}
				if (typeof(T) == typeof(sbyte))
				{
					sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int j = 0; j < Count; j++)
					{
						ptr2[j] = (sbyte)(object)ScalarMultiply(left[j], right[j]);
					}
					return new Vector<T>(ptr2);
				}
				if (typeof(T) == typeof(ushort))
				{
					ushort* ptr3 = stackalloc ushort[Count];
					for (int k = 0; k < Count; k++)
					{
						ptr3[k] = (ushort)(object)ScalarMultiply(left[k], right[k]);
					}
					return new Vector<T>(ptr3);
				}
				if (typeof(T) == typeof(short))
				{
					short* ptr4 = stackalloc short[Count];
					for (int l = 0; l < Count; l++)
					{
						ptr4[l] = (short)(object)ScalarMultiply(left[l], right[l]);
					}
					return new Vector<T>(ptr4);
				}
				if (typeof(T) == typeof(uint))
				{
					uint* ptr5 = stackalloc uint[Count];
					for (int m = 0; m < Count; m++)
					{
						ptr5[m] = (uint)(object)ScalarMultiply(left[m], right[m]);
					}
					return new Vector<T>(ptr5);
				}
				if (typeof(T) == typeof(int))
				{
					int* ptr6 = stackalloc int[Count];
					for (int n = 0; n < Count; n++)
					{
						ptr6[n] = (int)(object)ScalarMultiply(left[n], right[n]);
					}
					return new Vector<T>(ptr6);
				}
				if (typeof(T) == typeof(ulong))
				{
					ulong* ptr7 = stackalloc ulong[Count];
					for (int num = 0; num < Count; num++)
					{
						ptr7[num] = (ulong)(object)ScalarMultiply(left[num], right[num]);
					}
					return new Vector<T>(ptr7);
				}
				if (typeof(T) == typeof(long))
				{
					long* ptr8 = stackalloc long[Count];
					for (int num2 = 0; num2 < Count; num2++)
					{
						ptr8[num2] = (long)(object)ScalarMultiply(left[num2], right[num2]);
					}
					return new Vector<T>(ptr8);
				}
				if (typeof(T) == typeof(float))
				{
					float* ptr9 = stackalloc float[Count];
					for (int num3 = 0; num3 < Count; num3++)
					{
						ptr9[num3] = (float)(object)ScalarMultiply(left[num3], right[num3]);
					}
					return new Vector<T>(ptr9);
				}
				if (typeof(T) == typeof(double))
				{
					double* ptr10 = stackalloc double[Count];
					for (int num4 = 0; num4 < Count; num4++)
					{
						ptr10[num4] = (double)(object)ScalarMultiply(left[num4], right[num4]);
					}
					return new Vector<T>(ptr10);
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(left.register.byte_0 * right.register.byte_0);
				result.register.byte_1 = (byte)(left.register.byte_1 * right.register.byte_1);
				result.register.byte_2 = (byte)(left.register.byte_2 * right.register.byte_2);
				result.register.byte_3 = (byte)(left.register.byte_3 * right.register.byte_3);
				result.register.byte_4 = (byte)(left.register.byte_4 * right.register.byte_4);
				result.register.byte_5 = (byte)(left.register.byte_5 * right.register.byte_5);
				result.register.byte_6 = (byte)(left.register.byte_6 * right.register.byte_6);
				result.register.byte_7 = (byte)(left.register.byte_7 * right.register.byte_7);
				result.register.byte_8 = (byte)(left.register.byte_8 * right.register.byte_8);
				result.register.byte_9 = (byte)(left.register.byte_9 * right.register.byte_9);
				result.register.byte_10 = (byte)(left.register.byte_10 * right.register.byte_10);
				result.register.byte_11 = (byte)(left.register.byte_11 * right.register.byte_11);
				result.register.byte_12 = (byte)(left.register.byte_12 * right.register.byte_12);
				result.register.byte_13 = (byte)(left.register.byte_13 * right.register.byte_13);
				result.register.byte_14 = (byte)(left.register.byte_14 * right.register.byte_14);
				result.register.byte_15 = (byte)(left.register.byte_15 * right.register.byte_15);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 * right.register.sbyte_0);
				result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 * right.register.sbyte_1);
				result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 * right.register.sbyte_2);
				result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 * right.register.sbyte_3);
				result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 * right.register.sbyte_4);
				result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 * right.register.sbyte_5);
				result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 * right.register.sbyte_6);
				result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 * right.register.sbyte_7);
				result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 * right.register.sbyte_8);
				result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 * right.register.sbyte_9);
				result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 * right.register.sbyte_10);
				result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 * right.register.sbyte_11);
				result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 * right.register.sbyte_12);
				result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 * right.register.sbyte_13);
				result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 * right.register.sbyte_14);
				result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 * right.register.sbyte_15);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(left.register.uint16_0 * right.register.uint16_0);
				result.register.uint16_1 = (ushort)(left.register.uint16_1 * right.register.uint16_1);
				result.register.uint16_2 = (ushort)(left.register.uint16_2 * right.register.uint16_2);
				result.register.uint16_3 = (ushort)(left.register.uint16_3 * right.register.uint16_3);
				result.register.uint16_4 = (ushort)(left.register.uint16_4 * right.register.uint16_4);
				result.register.uint16_5 = (ushort)(left.register.uint16_5 * right.register.uint16_5);
				result.register.uint16_6 = (ushort)(left.register.uint16_6 * right.register.uint16_6);
				result.register.uint16_7 = (ushort)(left.register.uint16_7 * right.register.uint16_7);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(left.register.int16_0 * right.register.int16_0);
				result.register.int16_1 = (short)(left.register.int16_1 * right.register.int16_1);
				result.register.int16_2 = (short)(left.register.int16_2 * right.register.int16_2);
				result.register.int16_3 = (short)(left.register.int16_3 * right.register.int16_3);
				result.register.int16_4 = (short)(left.register.int16_4 * right.register.int16_4);
				result.register.int16_5 = (short)(left.register.int16_5 * right.register.int16_5);
				result.register.int16_6 = (short)(left.register.int16_6 * right.register.int16_6);
				result.register.int16_7 = (short)(left.register.int16_7 * right.register.int16_7);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = left.register.uint32_0 * right.register.uint32_0;
				result.register.uint32_1 = left.register.uint32_1 * right.register.uint32_1;
				result.register.uint32_2 = left.register.uint32_2 * right.register.uint32_2;
				result.register.uint32_3 = left.register.uint32_3 * right.register.uint32_3;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = left.register.int32_0 * right.register.int32_0;
				result.register.int32_1 = left.register.int32_1 * right.register.int32_1;
				result.register.int32_2 = left.register.int32_2 * right.register.int32_2;
				result.register.int32_3 = left.register.int32_3 * right.register.int32_3;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = left.register.uint64_0 * right.register.uint64_0;
				result.register.uint64_1 = left.register.uint64_1 * right.register.uint64_1;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = left.register.int64_0 * right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 * right.register.int64_1;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = left.register.single_0 * right.register.single_0;
				result.register.single_1 = left.register.single_1 * right.register.single_1;
				result.register.single_2 = left.register.single_2 * right.register.single_2;
				result.register.single_3 = left.register.single_3 * right.register.single_3;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = left.register.double_0 * right.register.double_0;
				result.register.double_1 = left.register.double_1 * right.register.double_1;
			}
			return result;
		}

		public static Vector<T>operator *(Vector<T> value, T factor)
		{
			if (Vector.IsHardwareAccelerated)
			{
				return new Vector<T>(factor) * value;
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor);
				result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor);
				result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor);
				result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor);
				result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor);
				result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor);
				result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor);
				result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor);
				result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor);
				result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor);
				result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor);
				result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor);
				result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor);
				result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor);
				result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor);
				result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor);
				result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor);
				result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor);
				result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor);
				result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor);
				result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor);
				result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor);
				result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor);
				result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor);
				result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor);
				result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor);
				result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor);
				result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor);
				result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor);
				result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor);
				result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor);
				result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor);
				result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor);
				result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor);
				result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor);
				result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor);
				result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor);
				result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor);
				result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor);
				result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor);
				result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor);
				result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor);
				result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor);
				result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor);
				result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor;
				result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor;
				result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor;
				result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = value.register.int32_0 * (int)(object)factor;
				result.register.int32_1 = value.register.int32_1 * (int)(object)factor;
				result.register.int32_2 = value.register.int32_2 * (int)(object)factor;
				result.register.int32_3 = value.register.int32_3 * (int)(object)factor;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor;
				result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = value.register.int64_0 * (long)(object)factor;
				result.register.int64_1 = value.register.int64_1 * (long)(object)factor;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = value.register.single_0 * (float)(object)factor;
				result.register.single_1 = value.register.single_1 * (float)(object)factor;
				result.register.single_2 = value.register.single_2 * (float)(object)factor;
				result.register.single_3 = value.register.single_3 * (float)(object)factor;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = value.register.double_0 * (double)(object)factor;
				result.register.double_1 = value.register.double_1 * (double)(object)factor;
			}
			return result;
		}

		public static Vector<T>operator *(T factor, Vector<T> value)
		{
			if (Vector.IsHardwareAccelerated)
			{
				return new Vector<T>(factor) * value;
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor);
				result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor);
				result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor);
				result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor);
				result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor);
				result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor);
				result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor);
				result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor);
				result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor);
				result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor);
				result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor);
				result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor);
				result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor);
				result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor);
				result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor);
				result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor);
				result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor);
				result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor);
				result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor);
				result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor);
				result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor);
				result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor);
				result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor);
				result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor);
				result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor);
				result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor);
				result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor);
				result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor);
				result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor);
				result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor);
				result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor);
				result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor);
				result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor);
				result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor);
				result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor);
				result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor);
				result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor);
				result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor);
				result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor);
				result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor);
				result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor);
				result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor);
				result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor);
				result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor);
				result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor;
				result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor;
				result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor;
				result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = value.register.int32_0 * (int)(object)factor;
				result.register.int32_1 = value.register.int32_1 * (int)(object)factor;
				result.register.int32_2 = value.register.int32_2 * (int)(object)factor;
				result.register.int32_3 = value.register.int32_3 * (int)(object)factor;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor;
				result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = value.register.int64_0 * (long)(object)factor;
				result.register.int64_1 = value.register.int64_1 * (long)(object)factor;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = value.register.single_0 * (float)(object)factor;
				result.register.single_1 = value.register.single_1 * (float)(object)factor;
				result.register.single_2 = value.register.single_2 * (float)(object)factor;
				result.register.single_3 = value.register.single_3 * (float)(object)factor;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = value.register.double_0 * (double)(object)factor;
				result.register.double_1 = value.register.double_1 * (double)(object)factor;
			}
			return result;
		}

		public unsafe static Vector<T>operator /(Vector<T> left, Vector<T> right)
		{
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int i = 0; i < Count; i++)
					{
						ptr[i] = (byte)(object)ScalarDivide(left[i], right[i]);
					}
					return new Vector<T>(ptr);
				}
				if (typeof(T) == typeof(sbyte))
				{
					sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int j = 0; j < Count; j++)
					{
						ptr2[j] = (sbyte)(object)ScalarDivide(left[j], right[j]);
					}
					return new Vector<T>(ptr2);
				}
				if (typeof(T) == typeof(ushort))
				{
					ushort* ptr3 = stackalloc ushort[Count];
					for (int k = 0; k < Count; k++)
					{
						ptr3[k] = (ushort)(object)ScalarDivide(left[k], right[k]);
					}
					return new Vector<T>(ptr3);
				}
				if (typeof(T) == typeof(short))
				{
					short* ptr4 = stackalloc short[Count];
					for (int l = 0; l < Count; l++)
					{
						ptr4[l] = (short)(object)ScalarDivide(left[l], right[l]);
					}
					return new Vector<T>(ptr4);
				}
				if (typeof(T) == typeof(uint))
				{
					uint* ptr5 = stackalloc uint[Count];
					for (int m = 0; m < Count; m++)
					{
						ptr5[m] = (uint)(object)ScalarDivide(left[m], right[m]);
					}
					return new Vector<T>(ptr5);
				}
				if (typeof(T) == typeof(int))
				{
					int* ptr6 = stackalloc int[Count];
					for (int n = 0; n < Count; n++)
					{
						ptr6[n] = (int)(object)ScalarDivide(left[n], right[n]);
					}
					return new Vector<T>(ptr6);
				}
				if (typeof(T) == typeof(ulong))
				{
					ulong* ptr7 = stackalloc ulong[Count];
					for (int num = 0; num < Count; num++)
					{
						ptr7[num] = (ulong)(object)ScalarDivide(left[num], right[num]);
					}
					return new Vector<T>(ptr7);
				}
				if (typeof(T) == typeof(long))
				{
					long* ptr8 = stackalloc long[Count];
					for (int num2 = 0; num2 < Count; num2++)
					{
						ptr8[num2] = (long)(object)ScalarDivide(left[num2], right[num2]);
					}
					return new Vector<T>(ptr8);
				}
				if (typeof(T) == typeof(float))
				{
					float* ptr9 = stackalloc float[Count];
					for (int num3 = 0; num3 < Count; num3++)
					{
						ptr9[num3] = (float)(object)ScalarDivide(left[num3], right[num3]);
					}
					return new Vector<T>(ptr9);
				}
				if (typeof(T) == typeof(double))
				{
					double* ptr10 = stackalloc double[Count];
					for (int num4 = 0; num4 < Count; num4++)
					{
						ptr10[num4] = (double)(object)ScalarDivide(left[num4], right[num4]);
					}
					return new Vector<T>(ptr10);
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(left.register.byte_0 / right.register.byte_0);
				result.register.byte_1 = (byte)(left.register.byte_1 / right.register.byte_1);
				result.register.byte_2 = (byte)(left.register.byte_2 / right.register.byte_2);
				result.register.byte_3 = (byte)(left.register.byte_3 / right.register.byte_3);
				result.register.byte_4 = (byte)(left.register.byte_4 / right.register.byte_4);
				result.register.byte_5 = (byte)(left.register.byte_5 / right.register.byte_5);
				result.register.byte_6 = (byte)(left.register.byte_6 / right.register.byte_6);
				result.register.byte_7 = (byte)(left.register.byte_7 / right.register.byte_7);
				result.register.byte_8 = (byte)(left.register.byte_8 / right.register.byte_8);
				result.register.byte_9 = (byte)(left.register.byte_9 / right.register.byte_9);
				result.register.byte_10 = (byte)(left.register.byte_10 / right.register.byte_10);
				result.register.byte_11 = (byte)(left.register.byte_11 / right.register.byte_11);
				result.register.byte_12 = (byte)(left.register.byte_12 / right.register.byte_12);
				result.register.byte_13 = (byte)(left.register.byte_13 / right.register.byte_13);
				result.register.byte_14 = (byte)(left.register.byte_14 / right.register.byte_14);
				result.register.byte_15 = (byte)(left.register.byte_15 / right.register.byte_15);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 / right.register.sbyte_0);
				result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 / right.register.sbyte_1);
				result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 / right.register.sbyte_2);
				result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 / right.register.sbyte_3);
				result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 / right.register.sbyte_4);
				result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 / right.register.sbyte_5);
				result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 / right.register.sbyte_6);
				result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 / right.register.sbyte_7);
				result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 / right.register.sbyte_8);
				result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 / right.register.sbyte_9);
				result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 / right.register.sbyte_10);
				result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 / right.register.sbyte_11);
				result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 / right.register.sbyte_12);
				result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 / right.register.sbyte_13);
				result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 / right.register.sbyte_14);
				result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 / right.register.sbyte_15);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(left.register.uint16_0 / right.register.uint16_0);
				result.register.uint16_1 = (ushort)(left.register.uint16_1 / right.register.uint16_1);
				result.register.uint16_2 = (ushort)(left.register.uint16_2 / right.register.uint16_2);
				result.register.uint16_3 = (ushort)(left.register.uint16_3 / right.register.uint16_3);
				result.register.uint16_4 = (ushort)(left.register.uint16_4 / right.register.uint16_4);
				result.register.uint16_5 = (ushort)(left.register.uint16_5 / right.register.uint16_5);
				result.register.uint16_6 = (ushort)(left.register.uint16_6 / right.register.uint16_6);
				result.register.uint16_7 = (ushort)(left.register.uint16_7 / right.register.uint16_7);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(left.register.int16_0 / right.register.int16_0);
				result.register.int16_1 = (short)(left.register.int16_1 / right.register.int16_1);
				result.register.int16_2 = (short)(left.register.int16_2 / right.register.int16_2);
				result.register.int16_3 = (short)(left.register.int16_3 / right.register.int16_3);
				result.register.int16_4 = (short)(left.register.int16_4 / right.register.int16_4);
				result.register.int16_5 = (short)(left.register.int16_5 / right.register.int16_5);
				result.register.int16_6 = (short)(left.register.int16_6 / right.register.int16_6);
				result.register.int16_7 = (short)(left.register.int16_7 / right.register.int16_7);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = left.register.uint32_0 / right.register.uint32_0;
				result.register.uint32_1 = left.register.uint32_1 / right.register.uint32_1;
				result.register.uint32_2 = left.register.uint32_2 / right.register.uint32_2;
				result.register.uint32_3 = left.register.uint32_3 / right.register.uint32_3;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = left.register.int32_0 / right.register.int32_0;
				result.register.int32_1 = left.register.int32_1 / right.register.int32_1;
				result.register.int32_2 = left.register.int32_2 / right.register.int32_2;
				result.register.int32_3 = left.register.int32_3 / right.register.int32_3;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = left.register.uint64_0 / right.register.uint64_0;
				result.register.uint64_1 = left.register.uint64_1 / right.register.uint64_1;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = left.register.int64_0 / right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 / right.register.int64_1;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = left.register.single_0 / right.register.single_0;
				result.register.single_1 = left.register.single_1 / right.register.single_1;
				result.register.single_2 = left.register.single_2 / right.register.single_2;
				result.register.single_3 = left.register.single_3 / right.register.single_3;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = left.register.double_0 / right.register.double_0;
				result.register.double_1 = left.register.double_1 / right.register.double_1;
			}
			return result;
		}

		public static Vector<T>operator -(Vector<T> value)
		{
			return Zero - value;
		}

		[JitIntrinsic]
		public unsafe static Vector<T>operator &(Vector<T> left, Vector<T> right)
		{
			Vector<T> result = default(Vector<T>);
			if (Vector.IsHardwareAccelerated)
			{
				long* ptr = &result.register.int64_0;
				long* ptr2 = &left.register.int64_0;
				long* ptr3 = &right.register.int64_0;
				for (int i = 0; i < Vector<long>.Count; i++)
				{
					ptr[i] = ptr2[i] & ptr3[i];
				}
			}
			else
			{
				result.register.int64_0 = left.register.int64_0 & right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 & right.register.int64_1;
			}
			return result;
		}

		[JitIntrinsic]
		public unsafe static Vector<T>operator |(Vector<T> left, Vector<T> right)
		{
			Vector<T> result = default(Vector<T>);
			if (Vector.IsHardwareAccelerated)
			{
				long* ptr = &result.register.int64_0;
				long* ptr2 = &left.register.int64_0;
				long* ptr3 = &right.register.int64_0;
				for (int i = 0; i < Vector<long>.Count; i++)
				{
					ptr[i] = ptr2[i] | ptr3[i];
				}
			}
			else
			{
				result.register.int64_0 = left.register.int64_0 | right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 | right.register.int64_1;
			}
			return result;
		}

		[JitIntrinsic]
		public unsafe static Vector<T>operator ^(Vector<T> left, Vector<T> right)
		{
			Vector<T> result = default(Vector<T>);
			if (Vector.IsHardwareAccelerated)
			{
				long* ptr = &result.register.int64_0;
				long* ptr2 = &left.register.int64_0;
				long* ptr3 = &right.register.int64_0;
				for (int i = 0; i < Vector<long>.Count; i++)
				{
					ptr[i] = ptr2[i] ^ ptr3[i];
				}
			}
			else
			{
				result.register.int64_0 = left.register.int64_0 ^ right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 ^ right.register.int64_1;
			}
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector<T>operator ~(Vector<T> value)
		{
			return allOnes ^ value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool operator ==(Vector<T> left, Vector<T> right)
		{
			return left.Equals(right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool operator !=(Vector<T> left, Vector<T> right)
		{
			return !(left == right);
		}

		[JitIntrinsic]
		public static explicit operator Vector<byte>(Vector<T> value)
		{
			return new Vector<byte>(ref value.register);
		}

		[CLSCompliant(false)]
		[JitIntrinsic]
		public static explicit operator Vector<sbyte>(Vector<T> value)
		{
			return new Vector<sbyte>(ref value.register);
		}

		[CLSCompliant(false)]
		[JitIntrinsic]
		public static explicit operator Vector<ushort>(Vector<T> value)
		{
			return new Vector<ushort>(ref value.register);
		}

		[JitIntrinsic]
		public static explicit operator Vector<short>(Vector<T> value)
		{
			return new Vector<short>(ref value.register);
		}

		[CLSCompliant(false)]
		[JitIntrinsic]
		public static explicit operator Vector<uint>(Vector<T> value)
		{
			return new Vector<uint>(ref value.register);
		}

		[JitIntrinsic]
		public static explicit operator Vector<int>(Vector<T> value)
		{
			return new Vector<int>(ref value.register);
		}

		[CLSCompliant(false)]
		[JitIntrinsic]
		public static explicit operator Vector<ulong>(Vector<T> value)
		{
			return new Vector<ulong>(ref value.register);
		}

		[JitIntrinsic]
		public static explicit operator Vector<long>(Vector<T> value)
		{
			return new Vector<long>(ref value.register);
		}

		[JitIntrinsic]
		public static explicit operator Vector<float>(Vector<T> value)
		{
			return new Vector<float>(ref value.register);
		}

		[JitIntrinsic]
		public static explicit operator Vector<double>(Vector<T> value)
		{
			return new Vector<double>(ref value.register);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[JitIntrinsic]
		internal unsafe static Vector<T> Equals(Vector<T> left, Vector<T> right)
		{
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int i = 0; i < Count; i++)
					{
						ptr[i] = (byte)(ScalarEquals(left[i], right[i]) ? ConstantHelper.GetByteWithAllBitsSet() : 0);
					}
					return new Vector<T>(ptr);
				}
				if (typeof(T) == typeof(sbyte))
				{
					sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int j = 0; j < Count; j++)
					{
						ptr2[j] = (sbyte)(ScalarEquals(left[j], right[j]) ? ConstantHelper.GetSByteWithAllBitsSet() : 0);
					}
					return new Vector<T>(ptr2);
				}
				if (typeof(T) == typeof(ushort))
				{
					ushort* ptr3 = stackalloc ushort[Count];
					for (int k = 0; k < Count; k++)
					{
						ptr3[k] = (ushort)(ScalarEquals(left[k], right[k]) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0);
					}
					return new Vector<T>(ptr3);
				}
				if (typeof(T) == typeof(short))
				{
					short* ptr4 

plugins/System.Runtime.CompilerServices.Unsafe.dll

Decompiled a day ago
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;

[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyFileVersion("4.0.0.0")]
[assembly: AssemblyInformationalVersion("4.0.0.0")]
[assembly: AssemblyTitle("System.Runtime.CompilerServices.Unsafe")]
[assembly: AssemblyDescription("System.Runtime.CompilerServices.Unsafe")]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyCopyright("© Microsoft Corporation.  All rights reserved.")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: CLSCompliant(false)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyVersion("4.0.4.0")]
namespace System.Runtime.CompilerServices
{
	public static class Unsafe : Object
	{
		[MethodImpl(256)]
		[NonVersionable]
		public unsafe static T Read<T>(void* source)
		{
			return Unsafe.Read<T>(source);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public unsafe static T ReadUnaligned<T>(void* source)
		{
			return Unsafe.ReadUnaligned<T>(source);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static T ReadUnaligned<T>(ref byte source)
		{
			return Unsafe.ReadUnaligned<T>(ref source);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public unsafe static void Write<T>(void* destination, T value)
		{
			Unsafe.Write(destination, value);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public unsafe static void WriteUnaligned<T>(void* destination, T value)
		{
			Unsafe.WriteUnaligned(destination, value);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static void WriteUnaligned<T>(ref byte destination, T value)
		{
			Unsafe.WriteUnaligned(ref destination, value);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public unsafe static void Copy<T>(void* destination, ref T source)
		{
			Unsafe.Write(destination, source);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public unsafe static void Copy<T>(ref T destination, void* source)
		{
			destination = Unsafe.Read<T>(source);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public unsafe static void* AsPointer<T>(ref T value)
		{
			return Unsafe.AsPointer(ref value);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static int SizeOf<T>()
		{
			return Unsafe.SizeOf<T>();
		}

		[MethodImpl(256)]
		[NonVersionable]
		public unsafe static void CopyBlock(void* destination, void* source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlock(destination, source, byteCount);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static void CopyBlock(ref byte destination, ref byte source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlock(ref destination, ref source, byteCount);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlockUnaligned(destination, source, byteCount);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlock(startAddress, value, byteCount);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static void InitBlock(ref byte startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlock(ref startAddress, value, byteCount);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlockUnaligned(startAddress, value, byteCount);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static T As<T>(object o) where T : class
		{
			return (T)o;
		}

		[MethodImpl(256)]
		[NonVersionable]
		public unsafe static ref T AsRef<T>(void* source)
		{
			return ref *(T*)source;
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static ref T AsRef<T>(in T source)
		{
			return ref source;
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static ref TTo As<TFrom, TTo>(ref TFrom source)
		{
			return ref Unsafe.As<TFrom, TTo>(ref source);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static ref T Add<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public unsafe static void* Add<T>(void* source, int elementOffset)
		{
			return (byte*)source + (nint)elementOffset * (nint)Unsafe.SizeOf<T>();
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static ref T Add<T>(ref T source, System.IntPtr elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static ref T AddByteOffset<T>(ref T source, System.IntPtr byteOffset)
		{
			return ref Unsafe.AddByteOffset(ref source, byteOffset);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static ref T Subtract<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public unsafe static void* Subtract<T>(void* source, int elementOffset)
		{
			return (byte*)source - (nint)elementOffset * (nint)Unsafe.SizeOf<T>();
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static ref T Subtract<T>(ref T source, System.IntPtr elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static ref T SubtractByteOffset<T>(ref T source, System.IntPtr byteOffset)
		{
			return ref Unsafe.SubtractByteOffset(ref source, byteOffset);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static System.IntPtr ByteOffset<T>(ref T origin, ref T target)
		{
			return Unsafe.ByteOffset(target: ref target, origin: ref origin);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static bool AreSame<T>(ref T left, ref T right)
		{
			return Unsafe.AreSame(ref left, ref right);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static bool IsAddressGreaterThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressGreaterThan(ref left, ref right);
		}

		[MethodImpl(256)]
		[NonVersionable]
		public static bool IsAddressLessThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressLessThan(ref left, ref right);
		}
	}
}
namespace System.Runtime.Versioning
{
	[AttributeUsage(/*Could not decode attribute arguments.*/)]
	internal sealed class NonVersionableAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
}

plugins/System.Security.AccessControl.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Threading;
using FxResources.System.Security.AccessControl;
using Microsoft.Win32.SafeHandles;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(/*Could not decode attribute arguments.*/)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyTitle("System.Security.AccessControl")]
[assembly: AssemblyDescription("System.Security.AccessControl")]
[assembly: AssemblyDefaultAlias("System.Security.AccessControl")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: AssemblyCopyright("© Microsoft Corporation.  All rights reserved.")]
[assembly: AssemblyFileVersion("4.6.24705.01")]
[assembly: AssemblyInformationalVersion("4.6.24705.01. Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyVersion("4.0.1.0")]
internal static class Interop
{
	internal static class Libraries
	{
		internal const string Advapi32 = "advapi32.dll";

		internal const string BCrypt = "BCrypt.dll";

		internal const string Combase = "combase.dll";

		internal const string Console_L1 = "api-ms-win-core-console-l1-1-0.dll";

		internal const string Console_L2 = "api-ms-win-core-console-l2-1-0.dll";

		internal const string CoreFile_L1 = "api-ms-win-core-file-l1-1-0.dll";

		internal const string CoreFile_L1_2 = "api-ms-win-core-file-l1-2-0.dll";

		internal const string CoreFile_L2 = "api-ms-win-core-file-l2-1-0.dll";

		internal const string Crypt32 = "crypt32.dll";

		internal const string Debug = "api-ms-win-core-debug-l1-1-0.dll";

		internal const string Error_L1 = "api-ms-win-core-winrt-error-l1-1-0.dll";

		internal const string ErrorHandling = "api-ms-win-core-errorhandling-l1-1-0.dll";

		internal const string Eventing = "api-ms-win-eventing-provider-l1-1-0.dll";

		internal const string Handle = "api-ms-win-core-handle-l1-1-0.dll";

		internal const string Heap = "api-ms-win-core-heap-obsolete-l1-1-0.dll";

		internal const string Heap_L1 = "api-ms-win-core-heap-l1-1-0.dll";

		internal const string IO = "api-ms-win-core-io-l1-1-0.dll";

		internal const string IpHlpApi = "iphlpapi.dll";

		internal const string Kernel32 = "kernel32.dll";

		internal const string Kernel32_L1 = "api-ms-win-core-kernel32-legacy-l1-1-1.dll";

		internal const string Kernel32_L2 = "api-ms-win-core-kernel32-legacy-l1-1-0.dll";

		internal const string Keyboard = "ext-ms-win-ntuser-keyboard-l1-2-1.dll";

		internal const string LibraryLoader = "api-ms-win-core-libraryloader-l1-1-0.dll";

		internal const string Localization = "api-ms-win-core-localization-l1-2-0.dll";

		internal const string Memory_L1_0 = "api-ms-win-core-memory-l1-1-0.dll";

		internal const string Memory_L1_1 = "api-ms-win-core-memory-l1-1-1.dll";

		internal const string Memory_L1_2 = "api-ms-win-core-memory-l1-1-2.dll";

		internal const string Memory_L1_3 = "api-ms-win-core-memory-l1-1-3.dll";

		internal const string NCrypt = "ncrypt.dll";

		internal const string NtDll = "ntdll.dll";

		internal const string OleAut32 = "oleaut32.dll";

		internal const string Pipe = "api-ms-win-core-namedpipe-l1-1-0.dll";

		internal const string Pipe_L2 = "api-ms-win-core-namedpipe-l1-2-1.dll";

		internal const string ProcessEnvironment = "api-ms-win-core-processenvironment-l1-1-0.dll";

		internal const string ProcessThread_L1 = "api-ms-win-core-processthreads-l1-1-0.dll";

		internal const string ProcessThread_L1_1 = "api-ms-win-core-processthreads-l1-1-1.dll";

		internal const string ProcessThread_L1_2 = "api-ms-win-core-processthreads-l1-1-2.dll";

		internal const string ProcessTopology = "api-ms-win-core-processtopology-obsolete-l1-1-0.dll";

		internal const string Profile = "api-ms-win-core-profile-l1-1-0.dll";

		internal const string Psapi = "api-ms-win-core-psapi-l1-1-0.dll";

		internal const string Psapi_Obsolete = "api-ms-win-core-psapi-obsolete-l1-1-0.dll";

		internal const string Registry_L1 = "api-ms-win-core-registry-l1-1-0.dll";

		internal const string Registry_L2 = "api-ms-win-core-registry-l2-1-0.dll";

		internal const string RoBuffer = "api-ms-win-core-winrt-robuffer-l1-1-0.dll";

		internal const string SecurityBase = "api-ms-win-security-base-l1-1-0.dll";

		internal const string SecurityCpwl = "api-ms-win-security-cpwl-l1-1-0.dll";

		internal const string SecurityCryptoApi = "api-ms-win-security-cryptoapi-l1-1-0.dll";

		internal const string SecurityLsa = "api-ms-win-security-lsalookup-l2-1-0.dll";

		internal const string SecurityLsaPolicy = "api-ms-win-security-lsapolicy-l1-1-0.dll";

		internal const string SecurityProvider = "api-ms-win-security-provider-l1-1-0.dll";

		internal const string SecuritySddl = "api-ms-win-security-sddl-l1-1-0.dll";

		internal const string ServiceCore = "api-ms-win-service-core-l1-1-1.dll";

		internal const string ServiceMgmt_L1 = "api-ms-win-service-management-l1-1-0.dll";

		internal const string ServiceMgmt_L2 = "api-ms-win-service-management-l2-1-0.dll";

		internal const string ServiceWinSvc = "api-ms-win-service-winsvc-l1-1-0.dll";

		internal const string Sspi = "sspicli.dll";

		internal const string String_L1 = "api-ms-win-core-string-l1-1-0.dll";

		internal const string Synch = "api-ms-win-core-synch-l1-1-0.dll";

		internal const string SystemInfo_L1_1 = "api-ms-win-core-sysinfo-l1-1-0.dll";

		internal const string SystemInfo_L1_2 = "api-ms-win-core-sysinfo-l1-2-0.dll";

		internal const string ThreadPool = "api-ms-win-core-threadpool-l1-2-0.dll";

		internal const string User32 = "user32.dll";

		internal const string Util = "api-ms-win-core-util-l1-1-0.dll";

		internal const string Version = "api-ms-win-core-version-l1-1-0.dll";

		internal const string WinHttp = "winhttp.dll";

		internal const string Winsock = "Ws2_32.dll";

		internal const string Wow64 = "api-ms-win-core-wow64-l1-1-0.dll";

		internal const string Ws2_32 = "ws2_32.dll";

		internal const string Zlib = "clrcompression.dll";
	}

	internal static class mincore
	{
		internal struct LUID
		{
			internal int LowPart;

			internal int HighPart;
		}

		internal struct LUID_AND_ATTRIBUTES
		{
			public LUID Luid;

			public uint Attributes;
		}

		[DefaultMember("Item")]
		internal struct InlineArray_LUID_AND_ATTRIBUTES_1
		{
			public const int Length = 1;

			private LUID_AND_ATTRIBUTES _elem_0;

			public unsafe LUID_AND_ATTRIBUTES this[uint index]
			{
				get
				{
					//IL_0008: Unknown result type (might be due to invalid IL or missing references)
					if (index < 0 || index >= 1)
					{
						throw new IndexOutOfRangeException();
					}
					fixed (InlineArray_LUID_AND_ATTRIBUTES_1* ptr = &this)
					{
						return *(LUID_AND_ATTRIBUTES*)((byte*)ptr + index * sizeof(LUID_AND_ATTRIBUTES));
					}
				}
				set
				{
					//IL_0008: Unknown result type (might be due to invalid IL or missing references)
					if (index < 0 || index >= 1)
					{
						throw new IndexOutOfRangeException();
					}
					fixed (InlineArray_LUID_AND_ATTRIBUTES_1* ptr = &this)
					{
						*(LUID_AND_ATTRIBUTES*)((byte*)ptr + index * sizeof(LUID_AND_ATTRIBUTES)) = value;
					}
				}
			}
		}

		internal struct TOKEN_PRIVILEGE
		{
			public uint PrivilegeCount;

			public InlineArray_LUID_AND_ATTRIBUTES_1 Privileges;
		}

		internal enum SECURITY_IMPERSONATION_LEVEL : uint
		{
			SecurityAnonymous,
			SecurityIdentification,
			SecurityImpersonation,
			SecurityDelegation
		}

		internal class Errors
		{
			internal const int ERROR_SUCCESS = 0;

			internal const int ERROR_INVALID_FUNCTION = 1;

			internal const int ERROR_FILE_NOT_FOUND = 2;

			internal const int ERROR_PATH_NOT_FOUND = 3;

			internal const int ERROR_ACCESS_DENIED = 5;

			internal const int ERROR_INVALID_HANDLE = 6;

			internal const int ERROR_NOT_ENOUGH_MEMORY = 8;

			internal const int ERROR_INVALID_DATA = 13;

			internal const int ERROR_INVALID_DRIVE = 15;

			internal const int ERROR_NO_MORE_FILES = 18;

			internal const int ERROR_NOT_READY = 21;

			internal const int ERROR_BAD_LENGTH = 24;

			internal const int ERROR_SHARING_VIOLATION = 32;

			internal const int ERROR_LOCK_VIOLATION = 33;

			internal const int ERROR_HANDLE_EOF = 38;

			internal const int ERROR_FILE_EXISTS = 80;

			internal const int ERROR_INVALID_PARAMETER = 87;

			internal const int ERROR_BROKEN_PIPE = 109;

			internal const int ERROR_INSUFFICIENT_BUFFER = 122;

			internal const int ERROR_INVALID_NAME = 123;

			internal const int ERROR_NEGATIVE_SEEK = 131;

			internal const int ERROR_DIR_NOT_EMPTY = 145;

			internal const int ERROR_BAD_PATHNAME = 161;

			internal const int ERROR_LOCK_FAILED = 167;

			internal const int ERROR_BUSY = 170;

			internal const int ERROR_ALREADY_EXISTS = 183;

			internal const int ERROR_BAD_EXE_FORMAT = 193;

			internal const int ERROR_ENVVAR_NOT_FOUND = 203;

			internal const int ERROR_FILENAME_EXCED_RANGE = 206;

			internal const int ERROR_EXE_MACHINE_TYPE_MISMATCH = 216;

			internal const int ERROR_PIPE_BUSY = 231;

			internal const int ERROR_NO_DATA = 232;

			internal const int ERROR_PIPE_NOT_CONNECTED = 233;

			internal const int ERROR_MORE_DATA = 234;

			internal const int ERROR_NO_MORE_ITEMS = 259;

			internal const int ERROR_PARTIAL_COPY = 299;

			internal const int ERROR_ARITHMETIC_OVERFLOW = 534;

			internal const int ERROR_PIPE_CONNECTED = 535;

			internal const int ERROR_PIPE_LISTENING = 536;

			internal const int ERROR_OPERATION_ABORTED = 995;

			internal const int ERROR_IO_PENDING = 997;

			internal const int ERROR_NO_TOKEN = 1008;

			internal const int ERROR_DLL_INIT_FAILED = 1114;

			internal const int ERROR_NOT_FOUND = 1168;

			internal const int ERROR_NON_ACCOUNT_SID = 1257;

			internal const int ERROR_NOT_ALL_ASSIGNED = 1300;

			internal const int ERROR_UNKNOWN_REVISION = 1305;

			internal const int ERROR_INVALID_OWNER = 1307;

			internal const int ERROR_INVALID_PRIMARY_GROUP = 1308;

			internal const int ERROR_NO_SUCH_PRIVILEGE = 1313;

			internal const int ERROR_PRIVILEGE_NOT_HELD = 1314;

			internal const int ERROR_INVALID_ACL = 1336;

			internal const int ERROR_INVALID_SECURITY_DESCR = 1338;

			internal const int ERROR_INVALID_SID = 1337;

			internal const int ERROR_BAD_IMPERSONATION_LEVEL = 1346;

			internal const int ERROR_CANT_OPEN_ANONYMOUS = 1347;

			internal const int ERROR_NO_SECURITY_ON_OBJECT = 1350;

			internal const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 1789;

			internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 1815;

			internal const int EFail = -2147467259;

			internal const int E_FILENOTFOUND = -2147024894;
		}

		internal class SEPrivileges
		{
			internal const uint SE_PRIVILEGE_DISABLED = 0u;

			internal const int SE_PRIVILEGE_ENABLED = 2;
		}

		internal class PerfCounterOptions
		{
			internal const int NtPerfCounterSizeLarge = 256;
		}

		internal class ProcessOptions
		{
			internal const int PROCESS_TERMINATE = 1;

			internal const int PROCESS_VM_READ = 16;

			internal const int PROCESS_SET_QUOTA = 256;

			internal const int PROCESS_SET_INFORMATION = 512;

			internal const int PROCESS_QUERY_INFORMATION = 1024;

			internal const int PROCESS_QUERY_LIMITED_INFORMATION = 4096;

			internal const int PROCESS_ALL_ACCESS = 2035711;

			internal const int STANDARD_RIGHTS_REQUIRED = 983040;

			internal const int SYNCHRONIZE = 1048576;
		}

		internal class RPCStatus
		{
			internal const int RPC_S_SERVER_UNAVAILABLE = 1722;

			internal const int RPC_S_CALL_FAILED = 1726;
		}

		internal class WaitOptions
		{
			internal const int WAIT_TIMEOUT = 258;
		}

		internal class StartupInfoOptions
		{
			internal const int STARTF_USESTDHANDLES = 256;

			internal const int CREATE_UNICODE_ENVIRONMENT = 1024;

			internal const int CREATE_NO_WINDOW = 134217728;

			internal const uint STATUS_INFO_LENGTH_MISMATCH = 3221225476u;
		}

		internal const string SeDebugPrivilege = "SeDebugPrivilege";

		[DllImport("api-ms-win-security-lsalookup-l2-1-0.dll", BestFitMapping = false, CharSet = 3, SetLastError = true)]
		internal static extern bool LookupPrivilegeValue([MarshalAs(22)] string lpSystemName, [MarshalAs(22)] string lpName, out LUID lpLuid);

		[DllImport("api-ms-win-security-base-l1-1-0.dll", CharSet = 3, ExactSpelling = true, SetLastError = true)]
		internal static extern bool RevertToSelf();

		[DllImport("api-ms-win-security-sddl-l1-1-0.dll", CharSet = 3, EntryPoint = "ConvertStringSecurityDescriptorToSecurityDescriptorW", ExactSpelling = true, SetLastError = true)]
		internal static extern bool ConvertSdToStringSd(byte[] securityDescriptor, uint requestedRevision, uint securityInformation, out System.IntPtr resultString, ref uint resultStringLength);

		[DllImport("api-ms-win-security-sddl-l1-1-0.dll", CharSet = 3, EntryPoint = "ConvertStringSecurityDescriptorToSecurityDescriptorW", ExactSpelling = true, SetLastError = true)]
		internal static extern bool ConvertStringSdToSd(string stringSd, uint stringSdRevision, out System.IntPtr resultSd, ref uint resultSdLength);

		[DllImport("api-ms-win-security-provider-l1-1-0.dll", CharSet = 3, EntryPoint = "GetSecurityInfo", ExactSpelling = true, SetLastError = true)]
		internal static extern uint GetSecurityInfoByHandle(SafeHandle handle, uint objectType, uint securityInformation, out System.IntPtr sidOwner, out System.IntPtr sidGroup, out System.IntPtr dacl, out System.IntPtr sacl, out System.IntPtr securityDescriptor);

		[DllImport("api-ms-win-security-provider-l1-1-0.dll", CharSet = 3, EntryPoint = "SetSecurityInfo", ExactSpelling = true, SetLastError = true)]
		internal static extern uint SetSecurityInfoByHandle(SafeHandle handle, uint objectType, uint securityInformation, byte[] owner, byte[] group, byte[] dacl, byte[] sacl);

		[DllImport("api-ms-win-security-provider-l1-1-0.dll", CharSet = 3, EntryPoint = "GetNamedSecurityInfoW", ExactSpelling = true, SetLastError = true)]
		internal static extern uint GetSecurityInfoByName(string name, uint objectType, uint securityInformation, out System.IntPtr sidOwner, out System.IntPtr sidGroup, out System.IntPtr dacl, out System.IntPtr sacl, out System.IntPtr securityDescriptor);

		[DllImport("api-ms-win-security-provider-l1-1-0.dll", CharSet = 3, EntryPoint = "SetNamedSecurityInfoW", ExactSpelling = true, SetLastError = true)]
		internal static extern uint SetSecurityInfoByName(string name, uint objectType, uint securityInformation, byte[] owner, byte[] group, byte[] dacl, byte[] sacl);

		[DllImport("api-ms-win-security-base-l1-1-0.dll", CharSet = 3, ExactSpelling = true, SetLastError = true)]
		internal static extern uint GetSecurityDescriptorLength(System.IntPtr byteArray);

		[DllImport("api-ms-win-core-handle-l1-1-0.dll", SetLastError = true)]
		[return: MarshalAs(2)]
		internal static extern bool CloseHandle(System.IntPtr handle);

		[DllImport("api-ms-win-core-processthreads-l1-1-0.dll", SetLastError = true)]
		internal static extern bool OpenThreadToken(System.IntPtr ThreadHandle, TokenAccessLevels dwDesiredAccess, bool bOpenAsSelf, out SafeTokenHandle phThreadToken);

		[DllImport("api-ms-win-core-processthreads-l1-1-0.dll", CharSet = 3, SetLastError = true)]
		internal static extern bool OpenProcessToken(System.IntPtr ProcessToken, TokenAccessLevels DesiredAccess, out SafeTokenHandle TokenHandle);

		[DllImport("api-ms-win-core-processthreads-l1-1-0.dll", SetLastError = true)]
		internal static extern System.IntPtr GetCurrentProcess();

		[DllImport("api-ms-win-core-processthreads-l1-1-0.dll", SetLastError = true)]
		internal static extern bool SetThreadToken(System.IntPtr ThreadHandle, SafeTokenHandle hToken);

		[DllImport("api-ms-win-core-processthreads-l1-1-0.dll")]
		internal static extern System.IntPtr GetCurrentThread();

		[DllImport("api-ms-win-security-base-l1-1-0.dll", CharSet = 3, SetLastError = true)]
		internal static extern bool AdjustTokenPrivileges(SafeTokenHandle TokenHandle, bool DisableAllPrivileges, ref TOKEN_PRIVILEGE NewState, uint BufferLength, ref TOKEN_PRIVILEGE PreviousState, ref uint ReturnLength);

		[DllImport("api-ms-win-security-base-l1-1-0.dll", SetLastError = true)]
		internal static extern bool DuplicateTokenEx(SafeTokenHandle ExistingTokenHandle, TokenAccessLevels DesiredAccess, System.IntPtr TokenAttributes, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, TokenType TokenType, ref SafeTokenHandle DuplicateTokenHandle);
	}

	internal static class mincore_obsolete
	{
		[DllImport("api-ms-win-core-heap-obsolete-l1-1-0.dll", SetLastError = true)]
		internal static extern System.IntPtr LocalFree(System.IntPtr handle);
	}
}
namespace FxResources.System.Security.AccessControl
{
	internal static class SR
	{
	}
}
namespace Microsoft.Win32.SafeHandles
{
	internal sealed class SafeTokenHandle : SafeHandle
	{
		internal static SafeTokenHandle InvalidHandle => new SafeTokenHandle(System.IntPtr.Zero);

		public override bool IsInvalid
		{
			get
			{
				if (!(base.handle == new System.IntPtr(0)))
				{
					return base.handle == new System.IntPtr(-1);
				}
				return true;
			}
		}

		private SafeTokenHandle()
			: base(System.IntPtr.Zero, true)
		{
		}

		internal SafeTokenHandle(System.IntPtr handle)
			: base(System.IntPtr.Zero, true)
		{
			((SafeHandle)this).SetHandle(handle);
		}

		protected override bool ReleaseHandle()
		{
			return Interop.mincore.CloseHandle(base.handle);
		}
	}
}
namespace System
{
	internal static class NotImplemented
	{
		internal static System.Exception ByDesign => (System.Exception)new NotImplementedException();

		internal static System.Exception ByDesignWithMessage(string message)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			return (System.Exception)new NotImplementedException(message);
		}
	}
	internal static class SR
	{
		private static ResourceManager s_resourceManager;

		private const string s_resourcesName = "FxResources.System.Security.AccessControl.SR";

		private static ResourceManager ResourceManager
		{
			get
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Expected O, but got Unknown
				if (s_resourceManager == null)
				{
					s_resourceManager = new ResourceManager(ResourceType);
				}
				return s_resourceManager;
			}
		}

		internal static string AccessControl_AclTooLong => GetResourceString("AccessControl_AclTooLong", null);

		internal static string AccessControl_InvalidAccessRuleType => GetResourceString("AccessControl_InvalidAccessRuleType", null);

		internal static string AccessControl_InvalidAuditRuleType => GetResourceString("AccessControl_InvalidAuditRuleType", null);

		internal static string AccessControl_InvalidOwner => GetResourceString("AccessControl_InvalidOwner", null);

		internal static string AccessControl_InvalidGroup => GetResourceString("AccessControl_InvalidGroup", null);

		internal static string AccessControl_InvalidHandle => GetResourceString("AccessControl_InvalidHandle", null);

		internal static string AccessControl_InvalidSecurityDescriptorRevision => GetResourceString("AccessControl_InvalidSecurityDescriptorRevision", null);

		internal static string AccessControl_InvalidSecurityDescriptorSelfRelativeForm => GetResourceString("AccessControl_InvalidSecurityDescriptorSelfRelativeForm", null);

		internal static string AccessControl_InvalidSidInSDDLString => GetResourceString("AccessControl_InvalidSidInSDDLString", null);

		internal static string AccessControl_MustSpecifyContainerAcl => GetResourceString("AccessControl_MustSpecifyContainerAcl", null);

		internal static string AccessControl_MustSpecifyDirectoryObjectAcl => GetResourceString("AccessControl_MustSpecifyDirectoryObjectAcl", null);

		internal static string AccessControl_MustSpecifyLeafObjectAcl => GetResourceString("AccessControl_MustSpecifyLeafObjectAcl", null);

		internal static string AccessControl_MustSpecifyNonDirectoryObjectAcl => GetResourceString("AccessControl_MustSpecifyNonDirectoryObjectAcl", null);

		internal static string AccessControl_NoAssociatedSecurity => GetResourceString("AccessControl_NoAssociatedSecurity", null);

		internal static string AccessControl_UnexpectedError => GetResourceString("AccessControl_UnexpectedError", null);

		internal static string Arg_EnumAtLeastOneFlag => GetResourceString("Arg_EnumAtLeastOneFlag", null);

		internal static string Arg_EnumIllegalVal => GetResourceString("Arg_EnumIllegalVal", null);

		internal static string Arg_InvalidOperationException => GetResourceString("Arg_InvalidOperationException", null);

		internal static string Arg_MustBeIdentityReferenceType => GetResourceString("Arg_MustBeIdentityReferenceType", null);

		internal static string Argument_ArgumentZero => GetResourceString("Argument_ArgumentZero", null);

		internal static string Argument_InvalidAnyFlag => GetResourceString("Argument_InvalidAnyFlag", null);

		internal static string Argument_InvalidEnumValue => GetResourceString("Argument_InvalidEnumValue", null);

		internal static string Argument_InvalidName => GetResourceString("Argument_InvalidName", null);

		internal static string Argument_InvalidPrivilegeName => GetResourceString("Argument_InvalidPrivilegeName", null);

		internal static string Argument_InvalidSafeHandle => GetResourceString("Argument_InvalidSafeHandle", null);

		internal static string ArgumentException_InvalidAceBinaryForm => GetResourceString("ArgumentException_InvalidAceBinaryForm", null);

		internal static string ArgumentException_InvalidAclBinaryForm => GetResourceString("ArgumentException_InvalidAclBinaryForm", null);

		internal static string ArgumentException_InvalidSDSddlForm => GetResourceString("ArgumentException_InvalidSDSddlForm", null);

		internal static string ArgumentOutOfRange_ArrayLength => GetResourceString("ArgumentOutOfRange_ArrayLength", null);

		internal static string ArgumentOutOfRange_ArrayLengthMultiple => GetResourceString("ArgumentOutOfRange_ArrayLengthMultiple", null);

		internal static string ArgumentOutOfRange_ArrayTooSmall => GetResourceString("ArgumentOutOfRange_ArrayTooSmall", null);

		internal static string ArgumentOutOfRange_Enum => GetResourceString("ArgumentOutOfRange_Enum", null);

		internal static string ArgumentOutOfRange_InvalidUserDefinedAceType => GetResourceString("ArgumentOutOfRange_InvalidUserDefinedAceType", null);

		internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum", null);

		internal static string InvalidOperation_ModificationOfNonCanonicalAcl => GetResourceString("InvalidOperation_ModificationOfNonCanonicalAcl", null);

		internal static string InvalidOperation_MustBeSameThread => GetResourceString("InvalidOperation_MustBeSameThread", null);

		internal static string InvalidOperation_MustLockForReadOrWrite => GetResourceString("InvalidOperation_MustLockForReadOrWrite", null);

		internal static string InvalidOperation_MustLockForWrite => GetResourceString("InvalidOperation_MustLockForWrite", null);

		internal static string InvalidOperation_MustRevertPrivilege => GetResourceString("InvalidOperation_MustRevertPrivilege", null);

		internal static string InvalidOperation_NoSecurityDescriptor => GetResourceString("InvalidOperation_NoSecurityDescriptor", null);

		internal static string InvalidOperation_OnlyValidForDS => GetResourceString("InvalidOperation_OnlyValidForDS", null);

		internal static string NotSupported_SetMethod => GetResourceString("NotSupported_SetMethod", null);

		internal static string PrivilegeNotHeld_Default => GetResourceString("PrivilegeNotHeld_Default", null);

		internal static string PrivilegeNotHeld_Named => GetResourceString("PrivilegeNotHeld_Named", null);

		internal static string Rank_MultiDimNotSupported => GetResourceString("Rank_MultiDimNotSupported", null);

		internal static System.Type ResourceType => typeof(SR);

		[MethodImpl(8)]
		private static bool UsingResourceKeys()
		{
			return false;
		}

		internal static string GetResourceString(string resourceKey, string defaultString)
		{
			string text = null;
			try
			{
				text = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			if (defaultString != null && resourceKey.Equals(text, (StringComparison)4))
			{
				return defaultString;
			}
			return text;
		}

		internal static string Format(string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + string.Join(", ", args);
				}
				return string.Format(resourceFormat, args);
			}
			return resourceFormat;
		}

		internal static string Format(string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", new object[2] { resourceFormat, p1 });
			}
			return string.Format(resourceFormat, p1);
		}

		internal static string Format(string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", new object[3] { resourceFormat, p1, p2 });
			}
			return string.Format(resourceFormat, p1, p2);
		}

		internal static string Format(string resourceFormat, object p1, object p2, object p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 });
			}
			return string.Format(resourceFormat, p1, p2, p3);
		}
	}
}
namespace System.Security.Principal
{
	internal static class Win32
	{
		internal static int OpenThreadToken(TokenAccessLevels dwDesiredAccess, WinSecurityContext dwOpenAs, out SafeTokenHandle phThreadToken)
		{
			int num = 0;
			bool bOpenAsSelf = true;
			if (dwOpenAs == WinSecurityContext.Thread)
			{
				bOpenAsSelf = false;
			}
			if (!Interop.mincore.OpenThreadToken((System.IntPtr)(-2), dwDesiredAccess, bOpenAsSelf, out phThreadToken))
			{
				if (dwOpenAs == WinSecurityContext.Both)
				{
					bOpenAsSelf = false;
					num = 0;
					if (!Interop.mincore.OpenThreadToken((System.IntPtr)(-2), dwDesiredAccess, bOpenAsSelf, out phThreadToken))
					{
						num = Marshal.GetHRForLastWin32Error();
					}
				}
				else
				{
					num = Marshal.GetHRForLastWin32Error();
				}
			}
			if (num != 0)
			{
				phThreadToken = null;
			}
			return num;
		}

		internal static int SetThreadToken(SafeTokenHandle hToken)
		{
			int result = 0;
			if (!Interop.mincore.SetThreadToken(System.IntPtr.Zero, hToken))
			{
				result = Marshal.GetHRForLastWin32Error();
			}
			return result;
		}
	}
	internal enum WinSecurityContext
	{
		Thread = 1,
		Process,
		Both
	}
	internal enum TokenType
	{
		TokenPrimary = 1,
		TokenImpersonation
	}
}
namespace System.Security.AccessControl
{
	public enum AceType : byte
	{
		AccessAllowed = 0,
		AccessDenied = 1,
		SystemAudit = 2,
		SystemAlarm = 3,
		AccessAllowedCompound = 4,
		AccessAllowedObject = 5,
		AccessDeniedObject = 6,
		SystemAuditObject = 7,
		SystemAlarmObject = 8,
		AccessAllowedCallback = 9,
		AccessDeniedCallback = 10,
		AccessAllowedCallbackObject = 11,
		AccessDeniedCallbackObject = 12,
		SystemAuditCallback = 13,
		SystemAlarmCallback = 14,
		SystemAuditCallbackObject = 15,
		SystemAlarmCallbackObject = 16,
		MaxDefinedAceType = 16
	}
	[Flags]
	public enum AceFlags : byte
	{
		None = 0,
		ObjectInherit = 1,
		ContainerInherit = 2,
		NoPropagateInherit = 4,
		InheritOnly = 8,
		Inherited = 0x10,
		SuccessfulAccess = 0x40,
		FailedAccess = 0x80,
		InheritanceFlags = 0xF,
		AuditFlags = 0xC0
	}
	public abstract class GenericAce
	{
		private readonly AceType _type;

		private AceFlags _flags;

		internal ushort _indexInAcl;

		internal const int HeaderLength = 4;

		public AceType AceType => _type;

		public AceFlags AceFlags
		{
			get
			{
				return _flags;
			}
			set
			{
				_flags = value;
			}
		}

		public bool IsInherited => (AceFlags & AceFlags.Inherited) != 0;

		public InheritanceFlags InheritanceFlags
		{
			get
			{
				InheritanceFlags inheritanceFlags = InheritanceFlags.None;
				if ((AceFlags & AceFlags.ContainerInherit) != 0)
				{
					inheritanceFlags |= InheritanceFlags.ContainerInherit;
				}
				if ((AceFlags & AceFlags.ObjectInherit) != 0)
				{
					inheritanceFlags |= InheritanceFlags.ObjectInherit;
				}
				return inheritanceFlags;
			}
		}

		public PropagationFlags PropagationFlags
		{
			get
			{
				PropagationFlags propagationFlags = PropagationFlags.None;
				if ((AceFlags & AceFlags.InheritOnly) != 0)
				{
					propagationFlags |= PropagationFlags.InheritOnly;
				}
				if ((AceFlags & AceFlags.NoPropagateInherit) != 0)
				{
					propagationFlags |= PropagationFlags.NoPropagateInherit;
				}
				return propagationFlags;
			}
		}

		public AuditFlags AuditFlags
		{
			get
			{
				AuditFlags auditFlags = AuditFlags.None;
				if ((AceFlags & AceFlags.SuccessfulAccess) != 0)
				{
					auditFlags |= AuditFlags.Success;
				}
				if ((AceFlags & AceFlags.FailedAccess) != 0)
				{
					auditFlags |= AuditFlags.Failure;
				}
				return auditFlags;
			}
		}

		public abstract int BinaryLength { get; }

		internal void MarshalHeader(byte[] binaryForm, int offset)
		{
			//IL_000f: 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_0040: 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)
			int binaryLength = BinaryLength;
			if (binaryForm == null)
			{
				throw new ArgumentNullException("binaryForm");
			}
			if (offset < 0)
			{
				throw new ArgumentOutOfRangeException("offset", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if (binaryForm.Length - offset < BinaryLength)
			{
				throw new ArgumentOutOfRangeException("binaryForm", System.SR.ArgumentOutOfRange_ArrayTooSmall);
			}
			if (binaryLength > 65535)
			{
				throw new InvalidOperationException();
			}
			binaryForm[offset] = (byte)AceType;
			binaryForm[offset + 1] = (byte)AceFlags;
			binaryForm[offset + 2] = (byte)binaryLength;
			binaryForm[offset + 3] = (byte)(binaryLength >> 8);
		}

		internal GenericAce(AceType type, AceFlags flags)
		{
			_type = type;
			_flags = flags;
		}

		internal static AceFlags AceFlagsFromAuditFlags(AuditFlags auditFlags)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			AceFlags aceFlags = AceFlags.None;
			if ((auditFlags & AuditFlags.Success) != 0)
			{
				aceFlags |= AceFlags.SuccessfulAccess;
			}
			if ((auditFlags & AuditFlags.Failure) != 0)
			{
				aceFlags |= AceFlags.FailedAccess;
			}
			if (aceFlags == AceFlags.None)
			{
				throw new ArgumentException(System.SR.Arg_EnumAtLeastOneFlag, "auditFlags");
			}
			return aceFlags;
		}

		internal static AceFlags AceFlagsFromInheritanceFlags(InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
		{
			AceFlags aceFlags = AceFlags.None;
			if ((inheritanceFlags & InheritanceFlags.ContainerInherit) != 0)
			{
				aceFlags |= AceFlags.ContainerInherit;
			}
			if ((inheritanceFlags & InheritanceFlags.ObjectInherit) != 0)
			{
				aceFlags |= AceFlags.ObjectInherit;
			}
			if (aceFlags != 0)
			{
				if ((propagationFlags & PropagationFlags.NoPropagateInherit) != 0)
				{
					aceFlags |= AceFlags.NoPropagateInherit;
				}
				if ((propagationFlags & PropagationFlags.InheritOnly) != 0)
				{
					aceFlags |= AceFlags.InheritOnly;
				}
			}
			return aceFlags;
		}

		internal static void VerifyHeader(byte[] binaryForm, int offset)
		{
			//IL_0008: 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_0034: 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)
			if (binaryForm == null)
			{
				throw new ArgumentNullException("binaryForm");
			}
			if (offset < 0)
			{
				throw new ArgumentOutOfRangeException("offset", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if (binaryForm.Length - offset < 4)
			{
				throw new ArgumentOutOfRangeException("binaryForm", System.SR.ArgumentOutOfRange_ArrayTooSmall);
			}
			if ((binaryForm[offset + 3] << 8) + binaryForm[offset + 2] > binaryForm.Length - offset)
			{
				throw new ArgumentOutOfRangeException("binaryForm", System.SR.ArgumentOutOfRange_ArrayTooSmall);
			}
		}

		public static GenericAce CreateFromBinaryForm(byte[] binaryForm, int offset)
		{
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: 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)
			VerifyHeader(binaryForm, offset);
			AceType aceType = (AceType)binaryForm[offset];
			GenericAce genericAce;
			if (aceType == AceType.AccessAllowed || aceType == AceType.AccessDenied || aceType == AceType.SystemAudit || aceType == AceType.SystemAlarm || aceType == AceType.AccessAllowedCallback || aceType == AceType.AccessDeniedCallback || aceType == AceType.SystemAuditCallback || aceType == AceType.SystemAlarmCallback)
			{
				if (CommonAce.ParseBinaryForm(binaryForm, offset, out var qualifier, out var accessMask, out var sid, out var isCallback, out var opaque))
				{
					AceFlags flags = (AceFlags)binaryForm[offset + 1];
					genericAce = new CommonAce(flags, qualifier, accessMask, sid, isCallback, opaque);
					goto IL_0154;
				}
			}
			else if (aceType == AceType.AccessAllowedObject || aceType == AceType.AccessDeniedObject || aceType == AceType.SystemAuditObject || aceType == AceType.SystemAlarmObject || aceType == AceType.AccessAllowedCallbackObject || aceType == AceType.AccessDeniedCallbackObject || aceType == AceType.SystemAuditCallbackObject || aceType == AceType.SystemAlarmCallbackObject)
			{
				if (ObjectAce.ParseBinaryForm(binaryForm, offset, out var qualifier2, out var accessMask2, out var sid2, out var objectFlags, out var objectAceType, out var inheritedObjectAceType, out var isCallback2, out var opaque2))
				{
					AceFlags aceFlags = (AceFlags)binaryForm[offset + 1];
					genericAce = new ObjectAce(aceFlags, qualifier2, accessMask2, sid2, objectFlags, objectAceType, inheritedObjectAceType, isCallback2, opaque2);
					goto IL_0154;
				}
			}
			else if (aceType == AceType.AccessAllowedCompound)
			{
				if (CompoundAce.ParseBinaryForm(binaryForm, offset, out var accessMask3, out var compoundAceType, out var sid3))
				{
					AceFlags flags2 = (AceFlags)binaryForm[offset + 1];
					genericAce = new CompoundAce(flags2, accessMask3, compoundAceType, sid3);
					goto IL_0154;
				}
			}
			else
			{
				AceFlags flags3 = (AceFlags)binaryForm[offset + 1];
				byte[] array = null;
				int num = binaryForm[offset + 2] + (binaryForm[offset + 3] << 8);
				if (num % 4 == 0)
				{
					int num2 = num - 4;
					if (num2 > 0)
					{
						array = new byte[num2];
						for (int i = 0; i < num2; i++)
						{
							array[i] = binaryForm[offset + num - num2 + i];
						}
					}
					genericAce = new CustomAce(aceType, flags3, array);
					goto IL_0154;
				}
			}
			goto IL_01a8;
			IL_01a8:
			throw new ArgumentException(System.SR.ArgumentException_InvalidAceBinaryForm, "binaryForm");
			IL_0154:
			if ((genericAce is ObjectAce || binaryForm[offset + 2] + (binaryForm[offset + 3] << 8) == genericAce.BinaryLength) && (!(genericAce is ObjectAce) || binaryForm[offset + 2] + (binaryForm[offset + 3] << 8) == genericAce.BinaryLength || binaryForm[offset + 2] + (binaryForm[offset + 3] << 8) - 32 == genericAce.BinaryLength))
			{
				return genericAce;
			}
			goto IL_01a8;
		}

		public abstract void GetBinaryForm(byte[] binaryForm, int offset);

		public GenericAce Copy()
		{
			byte[] binaryForm = new byte[BinaryLength];
			GetBinaryForm(binaryForm, 0);
			return CreateFromBinaryForm(binaryForm, 0);
		}

		public virtual sealed bool Equals(object o)
		{
			if (o == null)
			{
				return false;
			}
			GenericAce genericAce = o as GenericAce;
			if (genericAce == null)
			{
				return false;
			}
			if (AceType != genericAce.AceType || AceFlags != genericAce.AceFlags)
			{
				return false;
			}
			int binaryLength = BinaryLength;
			int binaryLength2 = genericAce.BinaryLength;
			if (binaryLength != binaryLength2)
			{
				return false;
			}
			byte[] array = new byte[binaryLength];
			byte[] array2 = new byte[binaryLength2];
			GetBinaryForm(array, 0);
			genericAce.GetBinaryForm(array2, 0);
			for (int i = 0; i < array.Length; i++)
			{
				if (array[i] != array2[i])
				{
					return false;
				}
			}
			return true;
		}

		public virtual sealed int GetHashCode()
		{
			int binaryLength = BinaryLength;
			byte[] array = new byte[binaryLength];
			GetBinaryForm(array, 0);
			int num = 0;
			for (int i = 0; i < binaryLength; i += 4)
			{
				int num2 = array[i] + (array[i + 1] << 8) + (array[i + 2] << 16) + (array[i + 3] << 24);
				num ^= num2;
			}
			return num;
		}

		public static bool operator ==(GenericAce left, GenericAce right)
		{
			if ((object)left == null && (object)right == null)
			{
				return true;
			}
			if ((object)left == null || (object)right == null)
			{
				return false;
			}
			return ((object)left).Equals((object)right);
		}

		public static bool operator !=(GenericAce left, GenericAce right)
		{
			return !(left == right);
		}
	}
	public abstract class KnownAce : GenericAce
	{
		private int _accessMask;

		private SecurityIdentifier _sid;

		internal const int AccessMaskLength = 4;

		public int AccessMask
		{
			get
			{
				return _accessMask;
			}
			set
			{
				_accessMask = value;
			}
		}

		public SecurityIdentifier SecurityIdentifier
		{
			get
			{
				return _sid;
			}
			set
			{
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				if (value == null)
				{
					throw new ArgumentNullException("value");
				}
				_sid = value;
			}
		}

		internal KnownAce(AceType type, AceFlags flags, int accessMask, SecurityIdentifier securityIdentifier)
			: base(type, flags)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			if (securityIdentifier == null)
			{
				throw new ArgumentNullException("securityIdentifier");
			}
			AccessMask = accessMask;
			SecurityIdentifier = securityIdentifier;
		}
	}
	public sealed class CustomAce : GenericAce
	{
		private byte[] _opaque;

		public static readonly int MaxOpaqueLength = 65531;

		public int OpaqueLength
		{
			get
			{
				if (_opaque == null)
				{
					return 0;
				}
				return _opaque.Length;
			}
		}

		public override int BinaryLength => 4 + OpaqueLength;

		public CustomAce(AceType type, AceFlags flags, byte[] opaque)
			: base(type, flags)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			if ((int)type <= 16)
			{
				throw new ArgumentOutOfRangeException("type", System.SR.ArgumentOutOfRange_InvalidUserDefinedAceType);
			}
			SetOpaque(opaque);
		}

		public byte[] GetOpaque()
		{
			return _opaque;
		}

		public void SetOpaque(byte[] opaque)
		{
			//IL_0031: 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)
			if (opaque != null)
			{
				if (opaque.Length > MaxOpaqueLength)
				{
					throw new ArgumentOutOfRangeException("opaque", string.Format((IFormatProvider)(object)CultureInfo.CurrentCulture, System.SR.ArgumentOutOfRange_ArrayLength, (object)0, (object)MaxOpaqueLength));
				}
				if (opaque.Length % 4 != 0)
				{
					throw new ArgumentOutOfRangeException("opaque", string.Format((IFormatProvider)(object)CultureInfo.CurrentCulture, System.SR.ArgumentOutOfRange_ArrayLengthMultiple, (object)4));
				}
			}
			_opaque = opaque;
		}

		public override void GetBinaryForm(byte[] binaryForm, int offset)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			MarshalHeader(binaryForm, offset);
			offset += 4;
			if (OpaqueLength != 0)
			{
				if (OpaqueLength > MaxOpaqueLength)
				{
					throw new InvalidOperationException();
				}
				((System.Array)GetOpaque()).CopyTo((System.Array)binaryForm, offset);
			}
		}
	}
	public enum CompoundAceType
	{
		Impersonation = 1
	}
	public sealed class CompoundAce : KnownAce
	{
		private CompoundAceType _compoundAceType;

		private const int AceTypeLength = 4;

		public CompoundAceType CompoundAceType
		{
			get
			{
				return _compoundAceType;
			}
			set
			{
				_compoundAceType = value;
			}
		}

		public override int BinaryLength => 12 + base.SecurityIdentifier.BinaryLength;

		public CompoundAce(AceFlags flags, int accessMask, CompoundAceType compoundAceType, SecurityIdentifier sid)
			: base(AceType.AccessAllowedCompound, flags, accessMask, sid)
		{
			_compoundAceType = compoundAceType;
		}

		internal static bool ParseBinaryForm(byte[] binaryForm, int offset, out int accessMask, out CompoundAceType compoundAceType, out SecurityIdentifier sid)
		{
			GenericAce.VerifyHeader(binaryForm, offset);
			if (binaryForm.Length - offset >= 12 + SecurityIdentifier.MinBinaryLength)
			{
				int num = offset + 4;
				int num2 = 0;
				accessMask = binaryForm[num] + (binaryForm[num + 1] << 8) + (binaryForm[num + 2] << 16) + (binaryForm[num + 3] << 24);
				num2 += 4;
				compoundAceType = (CompoundAceType)(binaryForm[num + num2] + (binaryForm[num + num2 + 1] << 8));
				num2 += 4;
				sid = new SecurityIdentifier(binaryForm, num + num2);
				return true;
			}
			accessMask = 0;
			compoundAceType = (CompoundAceType)0;
			sid = null;
			return false;
		}

		public override void GetBinaryForm(byte[] binaryForm, int offset)
		{
			MarshalHeader(binaryForm, offset);
			int num = offset + 4;
			int num2 = 0;
			binaryForm[num] = (byte)base.AccessMask;
			binaryForm[num + 1] = (byte)(base.AccessMask >> 8);
			binaryForm[num + 2] = (byte)(base.AccessMask >> 16);
			binaryForm[num + 3] = (byte)(base.AccessMask >> 24);
			num2 += 4;
			binaryForm[num + num2] = (byte)(ushort)CompoundAceType;
			binaryForm[num + num2 + 1] = (byte)((ushort)CompoundAceType >> 8);
			binaryForm[num + num2 + 2] = 0;
			binaryForm[num + num2 + 3] = 0;
			num2 += 4;
			base.SecurityIdentifier.GetBinaryForm(binaryForm, num + num2);
		}
	}
	public enum AceQualifier
	{
		AccessAllowed,
		AccessDenied,
		SystemAudit,
		SystemAlarm
	}
	public abstract class QualifiedAce : KnownAce
	{
		private readonly bool _isCallback;

		private readonly AceQualifier _qualifier;

		private byte[] _opaque;

		public AceQualifier AceQualifier => _qualifier;

		public bool IsCallback => _isCallback;

		internal abstract int MaxOpaqueLengthInternal { get; }

		public int OpaqueLength
		{
			get
			{
				if (_opaque != null)
				{
					return _opaque.Length;
				}
				return 0;
			}
		}

		private AceQualifier QualifierFromType(AceType type, out bool isCallback)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			switch (type)
			{
			case AceType.AccessAllowed:
				isCallback = false;
				return AceQualifier.AccessAllowed;
			case AceType.AccessDenied:
				isCallback = false;
				return AceQualifier.AccessDenied;
			case AceType.SystemAudit:
				isCallback = false;
				return AceQualifier.SystemAudit;
			case AceType.SystemAlarm:
				isCallback = false;
				return AceQualifier.SystemAlarm;
			case AceType.AccessAllowedCallback:
				isCallback = true;
				return AceQualifier.AccessAllowed;
			case AceType.AccessDeniedCallback:
				isCallback = true;
				return AceQualifier.AccessDenied;
			case AceType.SystemAuditCallback:
				isCallback = true;
				return AceQualifier.SystemAudit;
			case AceType.SystemAlarmCallback:
				isCallback = true;
				return AceQualifier.SystemAlarm;
			case AceType.AccessAllowedObject:
				isCallback = false;
				return AceQualifier.AccessAllowed;
			case AceType.AccessDeniedObject:
				isCallback = false;
				return AceQualifier.AccessDenied;
			case AceType.SystemAuditObject:
				isCallback = false;
				return AceQualifier.SystemAudit;
			case AceType.SystemAlarmObject:
				isCallback = false;
				return AceQualifier.SystemAlarm;
			case AceType.AccessAllowedCallbackObject:
				isCallback = true;
				return AceQualifier.AccessAllowed;
			case AceType.AccessDeniedCallbackObject:
				isCallback = true;
				return AceQualifier.AccessDenied;
			case AceType.SystemAuditCallbackObject:
				isCallback = true;
				return AceQualifier.SystemAudit;
			case AceType.SystemAlarmCallbackObject:
				isCallback = true;
				return AceQualifier.SystemAlarm;
			default:
				throw new InvalidOperationException();
			}
		}

		internal QualifiedAce(AceType type, AceFlags flags, int accessMask, SecurityIdentifier sid, byte[] opaque)
			: base(type, flags, accessMask, sid)
		{
			_qualifier = QualifierFromType(type, out _isCallback);
			SetOpaque(opaque);
		}

		public byte[] GetOpaque()
		{
			return _opaque;
		}

		public void SetOpaque(byte[] opaque)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			if (opaque != null)
			{
				if (opaque.Length > MaxOpaqueLengthInternal)
				{
					throw new ArgumentOutOfRangeException("opaque", string.Format((IFormatProvider)(object)CultureInfo.CurrentCulture, System.SR.ArgumentOutOfRange_ArrayLength, (object)0, (object)MaxOpaqueLengthInternal));
				}
				if (opaque.Length % 4 != 0)
				{
					throw new ArgumentOutOfRangeException("opaque", string.Format((IFormatProvider)(object)CultureInfo.CurrentCulture, System.SR.ArgumentOutOfRange_ArrayLengthMultiple, (object)4));
				}
			}
			_opaque = opaque;
		}
	}
	public sealed class CommonAce : QualifiedAce
	{
		public override int BinaryLength => 8 + base.SecurityIdentifier.BinaryLength + base.OpaqueLength;

		internal override int MaxOpaqueLengthInternal => MaxOpaqueLength(base.IsCallback);

		public CommonAce(AceFlags flags, AceQualifier qualifier, int accessMask, SecurityIdentifier sid, bool isCallback, byte[] opaque)
			: base(TypeFromQualifier(isCallback, qualifier), flags, accessMask, sid, opaque)
		{
		}

		private static AceType TypeFromQualifier(bool isCallback, AceQualifier qualifier)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			switch (qualifier)
			{
			case AceQualifier.AccessAllowed:
				if (!isCallback)
				{
					return AceType.AccessAllowed;
				}
				return AceType.AccessAllowedCallback;
			case AceQualifier.AccessDenied:
				if (!isCallback)
				{
					return AceType.AccessDenied;
				}
				return AceType.AccessDeniedCallback;
			case AceQualifier.SystemAudit:
				if (!isCallback)
				{
					return AceType.SystemAudit;
				}
				return AceType.SystemAuditCallback;
			case AceQualifier.SystemAlarm:
				if (!isCallback)
				{
					return AceType.SystemAlarm;
				}
				return AceType.SystemAlarmCallback;
			default:
				throw new ArgumentOutOfRangeException("qualifier", System.SR.ArgumentOutOfRange_Enum);
			}
		}

		internal static bool ParseBinaryForm(byte[] binaryForm, int offset, out AceQualifier qualifier, out int accessMask, out SecurityIdentifier sid, out bool isCallback, out byte[] opaque)
		{
			GenericAce.VerifyHeader(binaryForm, offset);
			if (binaryForm.Length - offset >= 8 + SecurityIdentifier.MinBinaryLength)
			{
				AceType aceType = (AceType)binaryForm[offset];
				if (aceType == AceType.AccessAllowed || aceType == AceType.AccessDenied || aceType == AceType.SystemAudit || aceType == AceType.SystemAlarm)
				{
					isCallback = false;
				}
				else
				{
					if (aceType != AceType.AccessAllowedCallback && aceType != AceType.AccessDeniedCallback && aceType != AceType.SystemAuditCallback && aceType != AceType.SystemAlarmCallback)
					{
						goto IL_0114;
					}
					isCallback = true;
				}
				if (aceType == AceType.AccessAllowed || aceType == AceType.AccessAllowedCallback)
				{
					qualifier = AceQualifier.AccessAllowed;
				}
				else if (aceType == AceType.AccessDenied || aceType == AceType.AccessDeniedCallback)
				{
					qualifier = AceQualifier.AccessDenied;
				}
				else if (aceType == AceType.SystemAudit || aceType == AceType.SystemAuditCallback)
				{
					qualifier = AceQualifier.SystemAudit;
				}
				else
				{
					if (aceType != AceType.SystemAlarm && aceType != AceType.SystemAlarmCallback)
					{
						goto IL_0114;
					}
					qualifier = AceQualifier.SystemAlarm;
				}
				int num = offset + 4;
				int num2 = 0;
				accessMask = binaryForm[num] + (binaryForm[num + 1] << 8) + (binaryForm[num + 2] << 16) + (binaryForm[num + 3] << 24);
				num2 += 4;
				sid = new SecurityIdentifier(binaryForm, num + num2);
				opaque = null;
				int num3 = (binaryForm[offset + 3] << 8) + binaryForm[offset + 2];
				if (num3 % 4 == 0)
				{
					int num4 = num3 - 4 - 4 - (byte)sid.BinaryLength;
					if (num4 > 0)
					{
						opaque = new byte[num4];
						for (int i = 0; i < num4; i++)
						{
							opaque[i] = binaryForm[offset + num3 - num4 + i];
						}
					}
					return true;
				}
			}
			goto IL_0114;
			IL_0114:
			qualifier = AceQualifier.AccessAllowed;
			accessMask = 0;
			sid = null;
			isCallback = false;
			opaque = null;
			return false;
		}

		public static int MaxOpaqueLength(bool isCallback)
		{
			return 65527 - SecurityIdentifier.MaxBinaryLength;
		}

		public override void GetBinaryForm(byte[] binaryForm, int offset)
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			MarshalHeader(binaryForm, offset);
			int num = offset + 4;
			int num2 = 0;
			binaryForm[num] = (byte)base.AccessMask;
			binaryForm[num + 1] = (byte)(base.AccessMask >> 8);
			binaryForm[num + 2] = (byte)(base.AccessMask >> 16);
			binaryForm[num + 3] = (byte)(base.AccessMask >> 24);
			num2 += 4;
			base.SecurityIdentifier.GetBinaryForm(binaryForm, num + num2);
			num2 += base.SecurityIdentifier.BinaryLength;
			if (GetOpaque() != null)
			{
				if (base.OpaqueLength > MaxOpaqueLengthInternal)
				{
					throw new InvalidOperationException();
				}
				((System.Array)GetOpaque()).CopyTo((System.Array)binaryForm, num + num2);
			}
		}
	}
	[Flags]
	public enum ObjectAceFlags
	{
		None = 0,
		ObjectAceTypePresent = 1,
		InheritedObjectAceTypePresent = 2
	}
	public sealed class ObjectAce : QualifiedAce
	{
		private ObjectAceFlags _objectFlags;

		private Guid _objectAceType;

		private Guid _inheritedObjectAceType;

		private const int ObjectFlagsLength = 4;

		private const int GuidLength = 16;

		internal static readonly int AccessMaskWithObjectType = 315;

		public ObjectAceFlags ObjectAceFlags
		{
			get
			{
				return _objectFlags;
			}
			set
			{
				_objectFlags = value;
			}
		}

		public Guid ObjectAceType
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return _objectAceType;
			}
			set
			{
				//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)
				_objectAceType = value;
			}
		}

		public Guid InheritedObjectAceType
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return _inheritedObjectAceType;
			}
			set
			{
				//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)
				_inheritedObjectAceType = value;
			}
		}

		public override int BinaryLength
		{
			get
			{
				int num = (((_objectFlags & ObjectAceFlags.ObjectAceTypePresent) != 0) ? 16 : 0) + (((_objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent) != 0) ? 16 : 0);
				return 12 + num + base.SecurityIdentifier.BinaryLength + base.OpaqueLength;
			}
		}

		internal override int MaxOpaqueLengthInternal => MaxOpaqueLength(base.IsCallback);

		public ObjectAce(AceFlags aceFlags, AceQualifier qualifier, int accessMask, SecurityIdentifier sid, ObjectAceFlags flags, Guid type, Guid inheritedType, bool isCallback, byte[] opaque)
			: base(TypeFromQualifier(isCallback, qualifier), aceFlags, accessMask, sid, opaque)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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)
			_objectFlags = flags;
			_objectAceType = type;
			_inheritedObjectAceType = inheritedType;
		}

		private static AceType TypeFromQualifier(bool isCallback, AceQualifier qualifier)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			switch (qualifier)
			{
			case AceQualifier.AccessAllowed:
				if (!isCallback)
				{
					return AceType.AccessAllowedObject;
				}
				return AceType.AccessAllowedCallbackObject;
			case AceQualifier.AccessDenied:
				if (!isCallback)
				{
					return AceType.AccessDeniedObject;
				}
				return AceType.AccessDeniedCallbackObject;
			case AceQualifier.SystemAudit:
				if (!isCallback)
				{
					return AceType.SystemAuditObject;
				}
				return AceType.SystemAuditCallbackObject;
			case AceQualifier.SystemAlarm:
				if (!isCallback)
				{
					return AceType.SystemAlarmObject;
				}
				return AceType.SystemAlarmCallbackObject;
			default:
				throw new ArgumentOutOfRangeException("qualifier", System.SR.ArgumentOutOfRange_Enum);
			}
		}

		internal bool ObjectTypesMatch(ObjectAceFlags objectFlags, Guid objectType)
		{
			//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_0022: Unknown result type (might be due to invalid IL or missing references)
			if ((ObjectAceFlags & ObjectAceFlags.ObjectAceTypePresent) != (objectFlags & ObjectAceFlags.ObjectAceTypePresent))
			{
				return false;
			}
			if ((ObjectAceFlags & ObjectAceFlags.ObjectAceTypePresent) != 0)
			{
				Guid objectAceType = ObjectAceType;
				if (!((Guid)(ref objectAceType)).Equals(objectType))
				{
					return false;
				}
			}
			return true;
		}

		internal bool InheritedObjectTypesMatch(ObjectAceFlags objectFlags, Guid inheritedObjectType)
		{
			//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_0022: Unknown result type (might be due to invalid IL or missing references)
			if ((ObjectAceFlags & ObjectAceFlags.InheritedObjectAceTypePresent) != (objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent))
			{
				return false;
			}
			if ((ObjectAceFlags & ObjectAceFlags.InheritedObjectAceTypePresent) != 0)
			{
				Guid inheritedObjectAceType = InheritedObjectAceType;
				if (!((Guid)(ref inheritedObjectAceType)).Equals(inheritedObjectType))
				{
					return false;
				}
			}
			return true;
		}

		internal static bool ParseBinaryForm(byte[] binaryForm, int offset, out AceQualifier qualifier, out int accessMask, out SecurityIdentifier sid, out ObjectAceFlags objectFlags, out Guid objectAceType, out Guid inheritedObjectAceType, out bool isCallback, out byte[] opaque)
		{
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: 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)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			byte[] array = new byte[16];
			GenericAce.VerifyHeader(binaryForm, offset);
			if (binaryForm.Length - offset >= 12 + SecurityIdentifier.MinBinaryLength)
			{
				AceType aceType = (AceType)binaryForm[offset];
				if (aceType == AceType.AccessAllowedObject || aceType == AceType.AccessDeniedObject || aceType == AceType.SystemAuditObject || aceType == AceType.SystemAlarmObject)
				{
					isCallback = false;
				}
				else
				{
					if (aceType != AceType.AccessAllowedCallbackObject && aceType != AceType.AccessDeniedCallbackObject && aceType != AceType.SystemAuditCallbackObject && aceType != AceType.SystemAlarmCallbackObject)
					{
						goto IL_0209;
					}
					isCallback = true;
				}
				if (aceType == AceType.AccessAllowedObject || aceType == AceType.AccessAllowedCallbackObject)
				{
					qualifier = AceQualifier.AccessAllowed;
				}
				else if (aceType == AceType.AccessDeniedObject || aceType == AceType.AccessDeniedCallbackObject)
				{
					qualifier = AceQualifier.AccessDenied;
				}
				else if (aceType == AceType.SystemAuditObject || aceType == AceType.SystemAuditCallbackObject)
				{
					qualifier = AceQualifier.SystemAudit;
				}
				else
				{
					if (aceType != AceType.SystemAlarmObject && aceType != AceType.SystemAlarmCallbackObject)
					{
						goto IL_0209;
					}
					qualifier = AceQualifier.SystemAlarm;
				}
				int num = offset + 4;
				int num2 = 0;
				accessMask = binaryForm[num] + (binaryForm[num + 1] << 8) + (binaryForm[num + 2] << 16) + (binaryForm[num + 3] << 24);
				num2 += 4;
				objectFlags = (ObjectAceFlags)(binaryForm[num + num2] + (binaryForm[num + num2 + 1] << 8) + (binaryForm[num + num2 + 2] << 16) + (binaryForm[num + num2 + 3] << 24));
				num2 += 4;
				if ((objectFlags & ObjectAceFlags.ObjectAceTypePresent) != 0)
				{
					for (int i = 0; i < 16; i++)
					{
						array[i] = binaryForm[num + num2 + i];
					}
					num2 += 16;
				}
				else
				{
					for (int j = 0; j < 16; j++)
					{
						array[j] = 0;
					}
				}
				objectAceType = new Guid(array);
				if ((objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent) != 0)
				{
					for (int k = 0; k < 16; k++)
					{
						array[k] = binaryForm[num + num2 + k];
					}
					num2 += 16;
				}
				else
				{
					for (int l = 0; l < 16; l++)
					{
						array[l] = 0;
					}
				}
				inheritedObjectAceType = new Guid(array);
				sid = new SecurityIdentifier(binaryForm, num + num2);
				opaque = null;
				int num3 = (binaryForm[offset + 3] << 8) + binaryForm[offset + 2];
				if (num3 % 4 == 0)
				{
					int num4 = num3 - 4 - 4 - 4 - (byte)sid.BinaryLength;
					if ((objectFlags & ObjectAceFlags.ObjectAceTypePresent) != 0)
					{
						num4 -= 16;
					}
					if ((objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent) != 0)
					{
						num4 -= 16;
					}
					if (num4 > 0)
					{
						opaque = new byte[num4];
						for (int m = 0; m < num4; m++)
						{
							opaque[m] = binaryForm[offset + num3 - num4 + m];
						}
					}
					return true;
				}
			}
			goto IL_0209;
			IL_0209:
			qualifier = AceQualifier.AccessAllowed;
			accessMask = 0;
			sid = null;
			objectFlags = ObjectAceFlags.None;
			objectAceType = Guid.NewGuid();
			inheritedObjectAceType = Guid.NewGuid();
			isCallback = false;
			opaque = null;
			return false;
		}

		public static int MaxOpaqueLength(bool isCallback)
		{
			return 65491 - SecurityIdentifier.MaxBinaryLength;
		}

		public override void GetBinaryForm(byte[] binaryForm, int offset)
		{
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			MarshalHeader(binaryForm, offset);
			int num = offset + 4;
			int num2 = 0;
			binaryForm[num] = (byte)base.AccessMask;
			binaryForm[num + 1] = (byte)(base.AccessMask >> 8);
			binaryForm[num + 2] = (byte)(base.AccessMask >> 16);
			binaryForm[num + 3] = (byte)(base.AccessMask >> 24);
			num2 += 4;
			binaryForm[num + num2] = (byte)ObjectAceFlags;
			binaryForm[num + num2 + 1] = (byte)((uint)ObjectAceFlags >> 8);
			binaryForm[num + num2 + 2] = (byte)((uint)ObjectAceFlags >> 16);
			binaryForm[num + num2 + 3] = (byte)((uint)ObjectAceFlags >> 24);
			num2 += 4;
			Guid val;
			if ((ObjectAceFlags & ObjectAceFlags.ObjectAceTypePresent) != 0)
			{
				val = ObjectAceType;
				((System.Array)((Guid)(ref val)).ToByteArray()).CopyTo((System.Array)binaryForm, num + num2);
				num2 += 16;
			}
			if ((ObjectAceFlags & ObjectAceFlags.InheritedObjectAceTypePresent) != 0)
			{
				val = InheritedObjectAceType;
				((System.Array)((Guid)(ref val)).ToByteArray()).CopyTo((System.Array)binaryForm, num + num2);
				num2 += 16;
			}
			base.SecurityIdentifier.GetBinaryForm(binaryForm, num + num2);
			num2 += base.SecurityIdentifier.BinaryLength;
			if (GetOpaque() != null)
			{
				if (base.OpaqueLength > MaxOpaqueLengthInternal)
				{
					throw new InvalidOperationException();
				}
				((System.Array)GetOpaque()).CopyTo((System.Array)binaryForm, num + num2);
			}
		}
	}
	public sealed class AceEnumerator : System.Collections.IEnumerator
	{
		private int _current;

		private readonly GenericAcl _acl;

		object System.Collections.IEnumerator.Current
		{
			get
			{
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				if (_current == -1 || _current >= _acl.Count)
				{
					throw new InvalidOperationException(System.SR.Arg_InvalidOperationException);
				}
				return _acl[_current];
			}
		}

		public GenericAce Current => ((System.Collections.IEnumerator)this).Current as GenericAce;

		internal AceEnumerator(GenericAcl collection)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			_acl = collection;
			Reset();
		}

		public bool MoveNext()
		{
			_current++;
			return _current < _acl.Count;
		}

		public void Reset()
		{
			_current = -1;
		}
	}
	[DefaultMember("Item")]
	public abstract class GenericAcl : System.Collections.ICollection, System.Collections.IEnumerable
	{
		public static readonly byte AclRevision = 2;

		public static readonly byte AclRevisionDS = 4;

		public static readonly int MaxBinaryLength = 65535;

		internal const int HeaderLength = 8;

		public abstract byte Revision { get; }

		public abstract int BinaryLength { get; }

		public abstract GenericAce this[int index] { get; set; }

		public abstract int Count { get; }

		public bool IsSynchronized => false;

		public virtual object SyncRoot => this;

		public abstract void GetBinaryForm(byte[] binaryForm, int offset);

		void System.Collections.ICollection.CopyTo(System.Array array, int index)
		{
			//IL_0008: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			if (array == null)
			{
				throw new ArgumentNullException("array");
			}
			if (array.Rank != 1)
			{
				throw new RankException(System.SR.Rank_MultiDimNotSupported);
			}
			if (index < 0)
			{
				throw new ArgumentOutOfRangeException("index", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if (array.Length - index < Count)
			{
				throw new ArgumentOutOfRangeException("array", System.SR.ArgumentOutOfRange_ArrayTooSmall);
			}
			for (int i = 0; i < Count; i++)
			{
				array.SetValue((object)this[i], index + i);
			}
		}

		public void CopyTo(GenericAce[] array, int index)
		{
			((System.Collections.ICollection)this).CopyTo((System.Array)array, index);
		}

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return new AceEnumerator(this);
		}

		public AceEnumerator GetEnumerator()
		{
			return ((System.Collections.IEnumerable)this).GetEnumerator() as AceEnumerator;
		}
	}
	[DefaultMember("Item")]
	public sealed class RawAcl : GenericAcl
	{
		private byte _revision;

		private List<GenericAce> _aces;

		public override byte Revision => _revision;

		public override int Count => _aces.Count;

		public override int BinaryLength
		{
			get
			{
				int num = 8;
				for (int i = 0; i < Count; i++)
				{
					GenericAce genericAce = _aces[i];
					num += genericAce.BinaryLength;
				}
				return num;
			}
		}

		public override GenericAce this[int index]
		{
			get
			{
				return _aces[index];
			}
			set
			{
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: 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)
				if (value == null)
				{
					throw new ArgumentNullException("value");
				}
				if (value.BinaryLength % 4 != 0)
				{
					throw new InvalidOperationException();
				}
				int num = BinaryLength - ((index < _aces.Count) ? _aces[index].BinaryLength : 0) + value.BinaryLength;
				if (num > GenericAcl.MaxBinaryLength)
				{
					throw new OverflowException(System.SR.AccessControl_AclTooLong);
				}
				_aces[index] = value;
			}
		}

		private static void VerifyHeader(byte[] binaryForm, int offset, out byte revision, out int count, out int length)
		{
			//IL_0008: 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_0063: Unknown result type (might be due to invalid IL or missing references)
			if (binaryForm == null)
			{
				throw new ArgumentNullException("binaryForm");
			}
			if (offset < 0)
			{
				throw new ArgumentOutOfRangeException("offset", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if (binaryForm.Length - offset >= 8)
			{
				revision = binaryForm[offset];
				length = binaryForm[offset + 2] + (binaryForm[offset + 3] << 8);
				count = binaryForm[offset + 4] + (binaryForm[offset + 5] << 8);
				if (length <= binaryForm.Length - offset)
				{
					return;
				}
			}
			throw new ArgumentOutOfRangeException("binaryForm", System.SR.ArgumentOutOfRange_ArrayTooSmall);
		}

		private void MarshalHeader(byte[] binaryForm, int offset)
		{
			//IL_0008: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			if (binaryForm == null)
			{
				throw new ArgumentNullException("binaryForm");
			}
			if (offset < 0)
			{
				throw new ArgumentOutOfRangeException("offset", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if (BinaryLength > GenericAcl.MaxBinaryLength)
			{
				throw new InvalidOperationException(System.SR.AccessControl_AclTooLong);
			}
			if (binaryForm.Length - offset < BinaryLength)
			{
				throw new ArgumentOutOfRangeException("binaryForm", System.SR.ArgumentOutOfRange_ArrayTooSmall);
			}
			binaryForm[offset] = Revision;
			binaryForm[offset + 1] = 0;
			binaryForm[offset + 2] = (byte)BinaryLength;
			binaryForm[offset + 3] = (byte)(BinaryLength >> 8);
			binaryForm[offset + 4] = (byte)Count;
			binaryForm[offset + 5] = (byte)(Count >> 8);
			binaryForm[offset + 6] = 0;
			binaryForm[offset + 7] = 0;
		}

		internal void SetBinaryForm(byte[] binaryForm, int offset)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			VerifyHeader(binaryForm, offset, out _revision, out var count, out var length);
			length += offset;
			offset += 8;
			_aces = new List<GenericAce>(count);
			int num = 8;
			int num2 = 0;
			while (true)
			{
				if (num2 < count)
				{
					GenericAce genericAce = GenericAce.CreateFromBinaryForm(binaryForm, offset);
					int binaryLength = genericAce.BinaryLength;
					if (num + binaryLength > GenericAcl.MaxBinaryLength)
					{
						throw new ArgumentException(System.SR.ArgumentException_InvalidAclBinaryForm, "binaryForm");
					}
					_aces.Add(genericAce);
					if (binaryLength % 4 != 0)
					{
						throw new InvalidOperationException();
					}
					num += binaryLength;
					offset = ((_revision != GenericAcl.AclRevisionDS) ? (offset + binaryLength) : (offset + (binaryForm[offset + 2] + (binaryForm[offset + 3] << 8))));
					if (offset > length)
					{
						break;
					}
					num2++;
					continue;
				}
				return;
			}
			throw new ArgumentException(System.SR.ArgumentException_InvalidAclBinaryForm, "binaryForm");
		}

		public RawAcl(byte revision, int capacity)
		{
			_revision = revision;
			_aces = new List<GenericAce>(capacity);
		}

		public RawAcl(byte[] binaryForm, int offset)
		{
			SetBinaryForm(binaryForm, offset);
		}

		public override void GetBinaryForm(byte[] binaryForm, int offset)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			MarshalHeader(binaryForm, offset);
			offset += 8;
			for (int i = 0; i < Count; i++)
			{
				GenericAce genericAce = _aces[i];
				genericAce.GetBinaryForm(binaryForm, offset);
				int binaryLength = genericAce.BinaryLength;
				if (binaryLength % 4 != 0)
				{
					throw new InvalidOperationException();
				}
				offset += binaryLength;
			}
		}

		public void InsertAce(int index, GenericAce ace)
		{
			//IL_000e: 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)
			if (ace == null)
			{
				throw new ArgumentNullException("ace");
			}
			if (BinaryLength + ace.BinaryLength > GenericAcl.MaxBinaryLength)
			{
				throw new OverflowException(System.SR.AccessControl_AclTooLong);
			}
			_aces.Insert(index, ace);
		}

		public void RemoveAce(int index)
		{
			GenericAce genericAce = _aces[index];
			_aces.RemoveAt(index);
		}
	}
	[DefaultMember("Item")]
	public abstract class CommonAcl : GenericAcl
	{
		[Flags]
		private enum AF
		{
			CI = 8,
			OI = 4,
			IO = 2,
			NP = 1,
			Invalid = 1
		}

		[Flags]
		private enum PM
		{
			F = 0x10,
			CF = 8,
			CO = 4,
			GF = 2,
			GO = 1,
			Invalid = 1
		}

		private enum ComparisonResult
		{
			LessThan,
			EqualTo,
			GreaterThan
		}

		private static readonly PM[] s_AFtoPM = CreateAFtoPMConversionMatrix();

		private static readonly AF[] s_PMtoAF = CreatePMtoAFConversionMatrix();

		private RawAcl _acl;

		private bool _isDirty;

		private readonly bool _isCanonical;

		private readonly bool _isContainer;

		private readonly bool _isDS;

		internal RawAcl RawAcl => _acl;

		public sealed override byte Revision => _acl.Revision;

		public sealed override int Count
		{
			get
			{
				CanonicalizeIfNecessary();
				return _acl.Count;
			}
		}

		public sealed override int BinaryLength
		{
			get
			{
				CanonicalizeIfNecessary();
				return _acl.BinaryLength;
			}
		}

		public bool IsCanonical => _isCanonical;

		public bool IsContainer => _isContainer;

		public bool IsDS => _isDS;

		public sealed override GenericAce this[int index]
		{
			get
			{
				CanonicalizeIfNecessary();
				return _acl[index].Copy();
			}
			set
			{
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				throw new NotSupportedException(System.SR.NotSupported_SetMethod);
			}
		}

		private static PM[] CreateAFtoPMConversionMatrix()
		{
			PM[] array = new PM[16];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = PM.GO;
			}
			array[0] = PM.F;
			array[4] = PM.F | PM.CO | PM.GO;
			array[5] = PM.F | PM.CO;
			array[6] = PM.CO | PM.GO;
			array[7] = PM.CO;
			array[8] = PM.F | PM.CF | PM.GF;
			array[9] = PM.F | PM.CF;
			array[10] = PM.CF | PM.GF;
			array[11] = PM.CF;
			array[12] = PM.F | PM.CF | PM.CO | PM.GF | PM.GO;
			array[13] = PM.F | PM.CF | PM.CO;
			array[14] = PM.CF | PM.CO | PM.GF | PM.GO;
			array[15] = PM.CF | PM.CO;
			return array;
		}

		private static AF[] CreatePMtoAFConversionMatrix()
		{
			AF[] array = new AF[32];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = AF.NP;
			}
			array[16] = (AF)0;
			array[21] = AF.OI;
			array[20] = AF.OI | AF.NP;
			array[5] = AF.OI | AF.IO;
			array[4] = AF.OI | AF.IO | AF.NP;
			array[26] = AF.CI;
			array[24] = AF.CI | AF.NP;
			array[10] = AF.CI | AF.IO;
			array[8] = AF.CI | AF.IO | AF.NP;
			array[31] = AF.CI | AF.OI;
			array[28] = AF.CI | AF.OI | AF.NP;
			array[15] = AF.CI | AF.OI | AF.IO;
			array[12] = AF.CI | AF.OI | AF.IO | AF.NP;
			return array;
		}

		private static AF AFFromAceFlags(AceFlags aceFlags, bool isDS)
		{
			AF aF = (AF)0;
			if ((aceFlags & AceFlags.ContainerInherit) != 0)
			{
				aF |= AF.CI;
			}
			if (!isDS && (aceFlags & AceFlags.ObjectInherit) != 0)
			{
				aF |= AF.OI;
			}
			if ((aceFlags & AceFlags.InheritOnly) != 0)
			{
				aF |= AF.IO;
			}
			if ((aceFlags & AceFlags.NoPropagateInherit) != 0)
			{
				aF |= AF.NP;
			}
			return aF;
		}

		private static AceFlags AceFlagsFromAF(AF af, bool isDS)
		{
			AceFlags aceFlags = AceFlags.None;
			if ((af & AF.CI) != 0)
			{
				aceFlags |= AceFlags.ContainerInherit;
			}
			if (!isDS && (af & AF.OI) != 0)
			{
				aceFlags |= AceFlags.ObjectInherit;
			}
			if ((af & AF.IO) != 0)
			{
				aceFlags |= AceFlags.InheritOnly;
			}
			if ((af & AF.NP) != 0)
			{
				aceFlags |= AceFlags.NoPropagateInherit;
			}
			return aceFlags;
		}

		private static bool MergeInheritanceBits(AceFlags left, AceFlags right, bool isDS, out AceFlags result)
		{
			result = AceFlags.None;
			AF aF = AFFromAceFlags(left, isDS);
			AF aF2 = AFFromAceFlags(right, isDS);
			PM pM = s_AFtoPM[(int)aF];
			PM pM2 = s_AFtoPM[(int)aF2];
			if (pM == PM.GO || pM2 == PM.GO)
			{
				return false;
			}
			PM pM3 = pM | pM2;
			AF aF3 = s_PMtoAF[(int)pM3];
			if (aF3 == AF.NP)
			{
				return false;
			}
			result = AceFlagsFromAF(aF3, isDS);
			return true;
		}

		private static bool RemoveInheritanceBits(AceFlags existing, AceFlags remove, bool isDS, out AceFlags result, out bool total)
		{
			result = AceFlags.None;
			total = false;
			AF aF = AFFromAceFlags(existing, isDS);
			AF aF2 = AFFromAceFlags(remove, isDS);
			PM pM = s_AFtoPM[(int)aF];
			PM pM2 = s_AFtoPM[(int)aF2];
			if (pM == PM.GO || pM2 == PM.GO)
			{
				return false;
			}
			PM pM3 = pM & ~pM2;
			if (pM3 == (PM)0)
			{
				total = true;
				return true;
			}
			AF aF3 = s_PMtoAF[(int)pM3];
			if (aF3 == AF.NP)
			{
				return false;
			}
			result = AceFlagsFromAF(aF3, isDS);
			return true;
		}

		private void CanonicalizeIfNecessary()
		{
			if (_isDirty)
			{
				Canonicalize(compact: false, this is DiscretionaryAcl);
				_isDirty = false;
			}
		}

		private static int DaclAcePriority(GenericAce ace)
		{
			AceType aceType = ace.AceType;
			if ((ace.AceFlags & AceFlags.Inherited) != 0)
			{
				return 131070 + ace._indexInAcl;
			}
			switch (aceType)
			{
			case AceType.AccessDenied:
			case AceType.AccessDeniedCallback:
				return 0;
			case AceType.AccessDeniedObject:
			case AceType.AccessDeniedCallbackObject:
				return 1;
			case AceType.AccessAllowed:
			case AceType.AccessAllowedCallback:
				return 2;
			case AceType.AccessAllowedObject:
			case AceType.AccessAllowedCallbackObject:
				return 3;
			default:
				return 65535 + ace._indexInAcl;
			}
		}

		private static int SaclAcePriority(GenericAce ace)
		{
			AceType aceType = ace.AceType;
			if ((ace.AceFlags & AceFlags.Inherited) != 0)
			{
				return 131070 + ace._indexInAcl;
			}
			switch (aceType)
			{
			case AceType.SystemAudit:
			case AceType.SystemAlarm:
			case AceType.SystemAuditCallback:
			case AceType.SystemAlarmCallback:
				return 0;
			case AceType.SystemAuditObject:
			case AceType.SystemAlarmObject:
			case AceType.SystemAuditCallbackObject:
			case AceType.SystemAlarmCallbackObject:
				return 1;
			default:
				return 65535 + ace._indexInAcl;
			}
		}

		private static ComparisonResult CompareAces(GenericAce ace1, GenericAce ace2, bool isDacl)
		{
			int num = (isDacl ? DaclAcePriority(ace1) : SaclAcePriority(ace1));
			int num2 = (isDacl ? DaclAcePriority(ace2) : SaclAcePriority(ace2));
			if (num < num2)
			{
				return ComparisonResult.LessThan;
			}
			if (num > num2)
			{
				return ComparisonResult.GreaterThan;
			}
			KnownAce knownAce = ace1 as KnownAce;
			KnownAce knownAce2 = ace2 as KnownAce;
			if (knownAce != null && knownAce2 != null)
			{
				int num3 = knownAce.SecurityIdentifier.CompareTo(knownAce2.SecurityIdentifier);
				if (num3 < 0)
				{
					return ComparisonResult.LessThan;
				}
				if (num3 > 0)
				{
					return ComparisonResult.GreaterThan;
				}
			}
			return ComparisonResult.EqualTo;
		}

		private void QuickSort(int left, int right, bool isDacl)
		{
			if (left >= right)
			{
				return;
			}
			int num = left;
			int num2 = right;
			GenericAce genericAce = _acl[left];
			int num3 = left;
			while (left < right)
			{
				while (CompareAces(_acl[right], genericAce, isDacl) != 0 && left < right)
				{
					right--;
				}
				if (left != right)
				{
					_acl[left] = _acl[right];
					left++;
				}
				while (ComparisonResult.GreaterThan != CompareAces(_acl[left], genericAce, isDacl) && left < right)
				{
					left++;
				}
				if (left != right)
				{
					_acl[right] = _acl[left];
					right--;
				}
			}
			_acl[left] = genericAce;
			num3 = left;
			left = num;
			right = num2;
			if (left < num3)
			{
				QuickSort(left, num3 - 1, isDacl);
			}
			if (right > num3)
			{
				QuickSort(num3 + 1, right, isDacl);
			}
		}

		private bool InspectAce(ref GenericAce ace, bool isDacl)
		{
			KnownAce knownAce = ace as KnownAce;
			if (knownAce != null && knownAce.AccessMask == 0)
			{
				return false;
			}
			if (!IsContainer)
			{
				if ((ace.AceFlags & AceFlags.InheritOnly) != 0)
				{
					return false;
				}
				if ((ace.AceFlags & AceFlags.InheritanceFlags) != 0)
				{
					ace.AceFlags &= ~AceFlags.InheritanceFlags;
				}
			}
			else
			{
				if ((ace.AceFlags & AceFlags.InheritOnly) != 0 && (ace.AceFlags & AceFlags.ContainerInherit) == 0 && (ace.AceFlags & AceFlags.ObjectInherit) == 0)
				{
					return false;
				}
				if ((ace.AceFlags & AceFlags.NoPropagateInherit) != 0 && (ace.AceFlags & AceFlags.ContainerInherit) == 0 && (ace.AceFlags & AceFlags.ObjectInherit) == 0)
				{
					ace.AceFlags &= ~AceFlags.NoPropagateInherit;
				}
			}
			QualifiedAce qualifiedAce = knownAce as QualifiedAce;
			if (isDacl)
			{
				ace.AceFlags &= ~AceFlags.AuditFlags;
				if (qualifiedAce != null && qualifiedAce.AceQualifier != 0 && qualifiedAce.AceQualifier != AceQualifier.AccessDenied)
				{
					return false;
				}
			}
			else
			{
				if ((ace.AceFlags & AceFlags.AuditFlags) == 0)
				{
					return false;
				}
				if (qualifiedAce != null && qualifiedAce.AceQualifier != AceQualifier.SystemAudit)
				{
					return false;
				}
			}
			return true;
		}

		private void RemoveMeaninglessAcesAndFlags(bool isDacl)
		{
			for (int num = _acl.Count - 1; num >= 0; num--)
			{
				GenericAce ace = _acl[num];
				if (!InspectAce(ref ace, isDacl))
				{
					_acl.RemoveAce(num);
				}
			}
		}

		private void Canonicalize(bool compact, bool isDacl)
		{
			for (ushort num = 0; num < _acl.Count; num++)
			{
				_acl[num]._indexInAcl = num;
			}
			QuickSort(0, _acl.Count - 1, isDacl);
			if (!compact)
			{
				return;
			}
			for (int i = 0; i < Count - 1; i++)
			{
				QualifiedAce ace = _acl[i] as QualifiedAce;
				if (!(ace == null))
				{
					QualifiedAce qualifiedAce = _acl[i + 1] as QualifiedAce;
					if (!(qualifiedAce == null) && MergeAces(ref ace, qualifiedAce))
					{
						_acl.RemoveAce(i + 1);
					}
				}
			}
		}

		private void GetObjectTypesForSplit(ObjectAce originalAce, int accessMask, AceFlags aceFlags, out ObjectAceFlags objectFlags, out Guid objectType, out Guid inheritedObjectType)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: 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)
			//IL_0017: 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_002d: 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_004e: Unknown result type (might be due to invalid IL or missing references)
			objectFlags = ObjectAceFlags.None;
			objectType = Guid.Empty;
			inheritedObjectType = Guid.Empty;
			if ((accessMask & ObjectAce.AccessMaskWithObjectType) != 0)
			{
				objectType = originalAce.ObjectAceType;
				objectFlags |= originalAce.ObjectAceFlags & ObjectAceFlags.ObjectAceTypePresent;
			}
			if ((aceFlags & AceFlags.ContainerInherit) != 0)
			{
				inheritedObjectType = originalAce.InheritedObjectAceType;
				objectFlags |= originalAce.ObjectAceFlags & ObjectAceFlags.InheritedObjectAceTypePresent;
			}
		}

		private bool ObjectTypesMatch(QualifiedAce ace, QualifiedAce newAce)
		{
			//IL_0015: 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_001a: 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_0023: 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_0038: Unknown result type (might be due to invalid IL or missing references)
			Guid val = ((ace is ObjectAce) ? ((ObjectAce)ace).ObjectAceType : Guid.Empty);
			Guid val2 = ((newAce is ObjectAce) ? ((ObjectAce)newAce).ObjectAceType : Guid.Empty);
			return ((Guid)(ref val)).Equals(val2);
		}

		private bool InheritedObjectTypesMatch(QualifiedAce ace, QualifiedAce newAce)
		{
			//IL_0015: 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_001a: 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_0023: 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_0038: Unknown result type (might be due to invalid IL or missing references)
			Guid val = ((ace is ObjectAce) ? ((ObjectAce)ace).InheritedObjectAceType : Guid.Empty);
			Guid val2 = ((newAce is ObjectAce) ? ((ObjectAce)newAce).InheritedObjectAceType : Guid.Empty);
			return ((Guid)(ref val)).Equals(val2);
		}

		private bool AccessMasksAreMergeable(QualifiedAce ace, QualifiedAce newAce)
		{
			if (ObjectTypesMatch(ace, newAce))
			{
				return true;
			}
			ObjectAceFlags objectAceFlags = ((ace is ObjectAce) ? ((ObjectAce)ace).ObjectAceFlags : ObjectAceFlags.None);
			if ((ace.AccessMask & newAce.AccessMask & ObjectAce.AccessMaskWithObjectType) == (newAce.AccessMask & ObjectAce.AccessMaskWithObjectType) && (objectAceFlags & ObjectAceFlags.ObjectAceTypePresent) == 0)
			{
				return true;
			}
			return false;
		}

		private bool AceFlagsAreMergeable(QualifiedAce ace, QualifiedAce newAce)
		{
			if (InheritedObjectTypesMatch(ace, newAce))
			{
				return true;
			}
			ObjectAceFlags objectAceFlags = ((ace is ObjectAce) ? ((ObjectAce)ace).ObjectAceFlags : ObjectAceFlags.None);
			if ((objectAceFlags & ObjectAceFlags.InheritedObjectAceTypePresent) == 0)
			{
				return true;
			}
			return false;
		}

		private bool GetAccessMaskForRemoval(QualifiedAce ace, ObjectAceFlags objectFlags, Guid objectType, ref int accessMask)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			if ((ace.AccessMask & accessMask & ObjectAce.AccessMaskWithObjectType) != 0)
			{
				if (ace is ObjectAce)
				{
					bool flag = true;
					ObjectAce objectAce = ace as ObjectAce;
					if ((objectFlags & ObjectAceFlags.ObjectAceTypePresent) != 0 && (objectAce.ObjectAceFlags & ObjectAceFlags.ObjectAceTypePresent) == 0)
					{
						return false;
					}
					if ((objectFlags & ObjectAceFlags.ObjectAceTypePresent) != 0 && !objectAce.ObjectTypesMatch(objectFlags, objectType))
					{
						accessMask &= ~ObjectAce.AccessMaskWithObjectType;
					}
				}
				else if ((objectFlags & ObjectAceFlags.ObjectAceTypePresent) != 0)
				{
					return false;
				}
			}
			return true;
		}

		private bool GetInheritanceFlagsForRemoval(QualifiedAce ace, ObjectAceFlags objectFlags, Guid inheritedObjectType, ref AceFlags aceFlags)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			if ((ace.AceFlags & AceFlags.ContainerInherit) != 0 && (aceFlags & AceFlags.ContainerInherit) != 0)
			{
				if (ace is ObjectAce)
				{
					bool flag = true;
					ObjectAce objectAce = ace as ObjectAce;
					if ((objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent) != 0 && (objectAce.ObjectAceFlags & ObjectAceFlags.InheritedObjectAceTypePresent) == 0)
					{
						return false;
					}
					if ((objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent) != 0 && !objectAce.InheritedObjectTypesMatch(objectFlags, inheritedObjectType))
					{
						aceFlags &= ~AceFlags.InheritanceFlags;
					}
				}
				else if ((objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent) != 0)
				{
					return false;
				}
			}
			return true;
		}

		private static bool AceOpaquesMatch(QualifiedAce ace, QualifiedAce newAce)
		{
			byte[] opaque = ace.GetOpaque();
			byte[] opaque2 = newAce.GetOpaque();
			if (opaque == null || opaque2 == null)
			{
				return opaque == opaque2;
			}
			if (opaque.Length != opaque2.Length)
			{
				return false;
			}
			for (int i = 0; i < opaque.Length; i++)
			{
				if (opaque[i] != opaque2[i])
				{
					return false;
				}
			}
			return true;
		}

		private static bool AcesAreMergeable(QualifiedAce ace, QualifiedAce newAce)
		{
			if (ace.AceType != newAce.AceType)
			{
				return false;
			}
			if ((ace.AceFlags & AceFlags.Inherited) != 0)
			{
				return false;
			}
			if ((newAce.AceFlags & AceFlags.Inherited) != 0)
			{
				return false;
			}
			if (ace.AceQualifier != newAce.AceQualifier)
			{
				return false;
			}
			if (ace.SecurityIdentifier != newAce.SecurityIdentifier)
			{
				return false;
			}
			if (!AceOpaquesMatch(ace, newAce))
			{
				return false;
			}
			return true;
		}

		private bool MergeAces(ref QualifiedAce ace, QualifiedAce newAce)
		{
			if (!AcesAreMergeable(ace, newAce))
			{
				return false;
			}
			if (ace.AceFlags == newAce.AceFlags)
			{
				if (!(ace is ObjectAce) && !(newAce is ObjectAce))
				{
					ace.AccessMask |= newAce.AccessMask;
					return true;
				}
				if (InheritedObjectTypesMatch(ace, newAce) && AccessMasksAreMergeable(ace, newAce))
				{
					ace.AccessMask |= newAce.AccessMask;
					return true;
				}
			}
			if ((ace.AceFlags & AceFlags.InheritanceFlags) == (newAce.AceFlags & AceFlags.InheritanceFlags) && ace.AccessMask == newAce.AccessMask)
			{
				if (!(ace is ObjectAce) && !(newAce is ObjectAce))
				{
					ace.AceFlags |= newAce.AceFlags & AceFlags.AuditFlags;
					return true;
				}
				if (InheritedObjectTypesMatch(ace, newAce) && ObjectTypesMatch(ace, newAce))
				{
					ace.AceFlags |= newAce.AceFlags & AceFlags.AuditFlags;
					return true;
				}
			}
			if ((ace.AceFlags & AceFlags.AuditFlags) == (newAce.AceFlags & AceFlags.AuditFlags) && ace.AccessMask == newAce.AccessMask)
			{
				AceFlags result;
				if (ace is ObjectAce || newAce is ObjectAce)
				{
					if (ObjectTypesMatch(ace, newAce) && AceFlagsAreMergeable(ace, newAce) && MergeInheritanceBits(ace.AceFlags, newAce.AceFlags, IsDS, out result))
					{
						ace.AceFlags = result | (ace.AceFlags & AceFlags.AuditFlags);
						return true;
					}
				}
				else if (MergeInheritanceBits(ace.AceFlags, newAce.AceFlags, IsDS, out result))
				{
					ace.AceFlags = result | (ace.AceFlags & AceFlags.AuditFlags);
					return true;
				}
			}
			return false;
		}

		private bool CanonicalCheck(bool isDacl)
		{
			if (isDacl)
			{
				int num = 0;
				for (int i = 0; i < _acl.Count; i++)
				{
					GenericAce genericAce = _acl[i];
					int num2;
					if ((genericAce.AceFlags & AceFlags.Inherited) != 0)
					{
						num2 = 2;
					}
					else
					{
						QualifiedAce qualifiedAce = genericAce as QualifiedAce;
						if (qualifiedAce == null)
						{
							return false;
						}
						if (qualifiedAce.AceQualifier == AceQualifier.AccessAllowed)
						{
							num2 = 1;
						}
						else
						{
							if (qualifiedAce.AceQualifier != AceQualifier.AccessDenied)
							{
								return false;
							}
							num2 = 0;
						}
					}
					if (num2 > num)
					{
						num = num2;
					}
					else if (num2 < num)
					{
						return false;
					}
				}
			}
			else
			{
				int num3 = 0;
				for (int j = 0; j < _acl.Count; j++)
				{
					GenericAce genericAce2 = _acl[j];
					if (genericAce2 == null)
					{
						continue;
					}
					int num4;
					if ((genericAce2.AceFlags & AceFlags.Inherited) != 0)
					{
						num4 = 1;
					}
					else
					{
						QualifiedAce qualifiedAce2 = genericAce2 as QualifiedAce;
						if (qualifiedAce2 == null)
						{
							return false;
						}
						if (qualifiedAce2.AceQualifier != AceQualifier.SystemAudit && qualifiedAce2.AceQualifier != AceQualifier.SystemAlarm)
						{
							return false;
						}
						num4 = 0;
					}
					if (num4 > num3)
					{
						num3 = num4;
					}
					else if (num4 < num3)
					{
						return false;
					}
				}
			}
			return true;
		}

		private void ThrowIfNotCanonical()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			if (!_isCanonical)
			{
				throw new InvalidOperationException(System.SR.InvalidOperation_ModificationOfNonCanonicalAcl);
			}
		}

		internal CommonAcl(bool isContainer, bool isDS, byte revision, int capacity)
		{
			_isContainer = isContainer;
			_isDS = isDS;
			_acl = new RawAcl(revision, capacity);
			_isCanonical = true;
		}

		internal CommonAcl(bool isContainer, bool isDS, RawAcl rawAcl, bool trusted, bool isDacl)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (rawAcl == null)
			{
				throw new ArgumentNullException("rawAcl");
			}
			_isContainer = isContainer;
			_isDS = isDS;
			if (trusted)
			{
				_acl = rawAcl;
				RemoveMeaninglessAcesAndFlags(isDacl);
			}
			else
			{
				_acl = new RawAcl(rawAcl.Revision, rawAcl.Count);
				for (int i = 0; i < rawAcl.Count; i++)
				{
					GenericAce ace = rawAcl[i].Copy();
					if (InspectAce(ref ace, isDacl))
					{
						_acl.InsertAce(_acl.Count, ace);
					}
				}
			}
			if (CanonicalCheck(isDacl))
			{
				Canonicalize(compact: true, isDacl);
				_isCanonical = true;
			}
			else
			{
				_isCanonical = false;
			}
		}

		internal void CheckAccessType(AccessControlType accessType)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			if (accessType != 0 && accessType != AccessControlType.Deny)
			{
				throw new ArgumentOutOfRangeException("accessType", System.SR.ArgumentOutOfRange_Enum);
			}
		}

		internal void CheckFlags(InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: 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)
			if (IsContainer)
			{
				if (inheritanceFlags == InheritanceFlags.None && propagationFlags != 0)
				{
					throw new ArgumentException(System.SR.Argument_InvalidAnyFlag, "propagationFlags");
				}
				return;
			}
			if (inheritanceFlags != 0)
			{
				throw new ArgumentException(System.SR.Argument_InvalidAnyFlag, "inheritanceFlags");
			}
			if (propagationFlags != 0)
			{
				throw new ArgumentException(System.SR.Argument_InvalidAnyFlag, "propagationFlags");
			}
		}

		internal void AddQualifiedAce(SecurityIdentifier sid, AceQualifier qualifier, int accessMask, AceFlags flags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: 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_006f: 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)
			if (sid == null)
			{
				throw new ArgumentNullException("sid");
			}
			ThrowIfNotCanonical();
			bool flag = false;
			if (qualifier == AceQualifier.SystemAudit && (flags & AceFlags.AuditFlags) == 0)
			{
				throw new ArgumentException(System.SR.Arg_EnumAtLeastOneFlag, "flags");
			}
			if (accessMask == 0)
			{
				throw new ArgumentException(System.SR.Argument_ArgumentZero, "accessMask");
			}
			GenericAce ace = ((IsDS && objectFlags != 0) ? ((QualifiedAce)new ObjectAce(flags, qualifier, accessMask, sid, objectFlags, objectType, inheritedObjectType, isCallback: false, null)) : ((QualifiedAce)new CommonAce(flags, qualifier, accessMask, sid, isCallback: false, null)));
			if (!InspectAce(ref ace, this is DiscretionaryAcl))
			{
				return;
			}
			for (int i = 0; i < Count; i++)
			{
				QualifiedAce ace2 = _acl[i] as QualifiedAce;
				if (!(ace2 == null) && MergeAces(ref ace2, ace as QualifiedAce))
				{
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				_acl.InsertAce(_acl.Count, ace);
				_isDirty = true;
			}
			OnAclModificationTried();
		}

		internal void SetQualifiedAce(SecurityIdentifier sid, AceQualifier qualifier, int accessMask, AceFlags flags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: 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_006d: 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)
			if (sid == null)
			{
				throw new ArgumentNullException("sid");
			}
			if (qualifier == AceQualifier.SystemAudit && (flags & AceFlags.AuditFlags) == 0)
			{
				throw new ArgumentException(System.SR.Arg_EnumAtLeastOneFlag, "flags");
			}
			if (accessMask == 0)
			{
				throw new ArgumentException(System.SR.Argument_ArgumentZero, "accessMask");
			}
			ThrowIfNotCanonical();
			GenericAce ace = ((IsDS && objectFlags != 0) ? ((QualifiedAce)new ObjectAce(flags, qualifier, accessMask, sid, objectFlags, objectType, inheritedObjectType, isCallback: false, null)) : ((QualifiedAce)new CommonAce(flags, qualifier, accessMask, sid, isCallback: false, null)));
			if (!InspectAce(ref ace, this is DiscretionaryAcl))
			{
				return;
			}
			for (int i = 0; i < Count; i++)
			{
				QualifiedAce qualifiedAce = _acl[i] as QualifiedAce;
				if (!(qualifiedAce == null) && (qualifiedAce.AceFlags & AceFlags.Inherited) == 0 && qualifiedAce.AceQualifier == qualifier && !(qualifiedAce.SecurityIdentifier != sid))
				{
					_acl.RemoveAce(i);
					i--;
				}
			}
			_acl.InsertAce(_acl.Count, ace);
			_isDirty = true;
			OnAclModificationTried();
		}

		internal bool RemoveQualifiedAces(SecurityIdentifier sid, AceQualifier qualifier, int accessMask, AceFlags flags, bool saclSemantics, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: 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)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0362: Unknown result type (might be due to invalid IL or missing references)
			//IL_036b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0315: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_0417: Unknown result type (might be due to invalid IL or missing references)
			//IL_0419: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
			if (accessMask == 0)
			{
				throw new ArgumentException(System.SR.Argument_ArgumentZero, "accessMask");
			}
			if (qualifier == AceQualifier.SystemAudit && (flags & AceFlags.AuditFlags) == 0)
			{
				throw new ArgumentException(System.SR.Arg_EnumAtLeastOneFlag, "flags");
			}
			if (sid == null)
			{
				throw new ArgumentNullException("sid");
			}
			ThrowIfNotCanonical();
			bool flag = true;
			bool flag2 = true;
			int num = accessMask;
			AceFlags aceFlags = flags;
			byte[] binaryForm = new byte[BinaryLength];
			GetBinaryForm(binaryForm, 0);
			while (true)
			{
				try
				{
					for (int i = 0; i < Count; i++)
					{
						QualifiedAce qualifiedAce = _acl[i] as QualifiedAce;
						if (qualifiedAce == null || (qualifiedAce.AceFlags & AceFlags.Inherited) != 0 || qualifiedAce.AceQualifier != qualifier || qualifiedAce.SecurityIdentifier != sid)
						{
							continue;
						}
						if (IsDS)
						{
							accessMask = num;
							bool flag3 = !GetAccessMaskForRemoval(qualifiedAce, objectFlags, objectType, ref accessMask);
							if ((qualifiedAce.AccessMask & accessMask) == 0)
							{
								continue;
							}
							flags = aceFlags;
							bool flag4 = !GetInheritanceFlagsForRemoval(qualifiedAce, objectFlags, inheritedObjectType, ref flags);
							if (((qualifiedAce.AceFlags & AceFlags.ContainerInherit) == 0 && (flags & AceFlags.ContainerInherit) != 0 && (flags & AceFlags.InheritOnly) != 0) || ((flags & AceFlags.ContainerInherit) == 0 && (qualifiedAce.AceFlags & AceFlags.ContainerInherit) != 0 && (qualifiedAce.AceFlags & AceFlags.InheritOnly) != 0) || ((aceFlags & AceFlags.ContainerInherit) != 0 && (aceFlags & AceFlags.InheritOnly) != 0 && (flags & AceFlags.ContainerInherit) == 0))
							{
								continue;
							}
							if (flag3 || flag4)
							{
								flag2 = false;
								break;
							}
						}
						else if ((qualifiedAce.AccessMask & accessMask) == 0)
						{
							continue;
						}
						if (saclSemantics && (qualifiedAce.AceFlags & flags & AceFlags.AuditFlags) == 0)
						{
							continue;
						}
						AceFlags aceFlags2 = AceFlags.None;
						int num2 = 0;
						ObjectAceFlags objectFlags2 = ObjectAceFlags.None;
						Guid objectType2 = Guid.Empty;
						Guid inheritedObjectType2 = Guid.Empty;
						AceFlags aceFlags3 = AceFlags.None;
						int accessMask2 = 0;
						ObjectAceFlags objectFlags3 = ObjectAceFlags.None;
						Guid objectType3 = Guid.Empty;
						Guid inheritedObjectType3 = Guid.Empty;
						AceFlags aceFlags4 = AceFlags.None;
						int num3 = 0;
						ObjectAceFlags objectFlags4 = ObjectAceFlags.None;
						Guid objectType4 = Guid.Empty;
						Guid inheritedObjectType4 = Guid.Empty;
						AceFlags result = AceFlags.None;
						bool total = false;
						aceFlags2 = qualifiedAce.AceFlags;
						num2 = qualifiedAce.AccessMask & ~accessMask;
						if (qualifiedAce is ObjectAce)
						{
							GetObjectTypesForSplit(qualifiedAce as ObjectAce, num2, aceFlags2, out objectFlags2, out objectType2, out inheritedObjectType2);
						}
						if (saclSemantics)
						{
							aceFlags3 = qualifiedAce.AceFlags & (AceFlags)(~(uint)(flags & AceFlags.AuditFlags));
							accessMask2 = qualifiedAce.AccessMask & accessMask;
							if (qualifiedAce is ObjectAce)
							{
								GetObjectTyp

plugins/System.Security.Principal.Windows.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading;
using FxResources.System.Security.Principal.Windows;
using Microsoft.Win32.SafeHandles;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(/*Could not decode attribute arguments.*/)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyTitle("System.Security.Principal.Windows")]
[assembly: AssemblyDescription("System.Security.Principal.Windows")]
[assembly: AssemblyDefaultAlias("System.Security.Principal.Windows")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: AssemblyCopyright("© Microsoft Corporation.  All rights reserved.")]
[assembly: AssemblyFileVersion("4.6.24705.01")]
[assembly: AssemblyInformationalVersion("4.6.24705.01. Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyVersion("4.0.1.0")]
internal static class Interop
{
	internal static class Libraries
	{
		internal const string Advapi32 = "advapi32.dll";

		internal const string BCrypt = "BCrypt.dll";

		internal const string Combase = "combase.dll";

		internal const string Console_L1 = "api-ms-win-core-console-l1-1-0.dll";

		internal const string Console_L2 = "api-ms-win-core-console-l2-1-0.dll";

		internal const string CoreFile_L1 = "api-ms-win-core-file-l1-1-0.dll";

		internal const string CoreFile_L1_2 = "api-ms-win-core-file-l1-2-0.dll";

		internal const string CoreFile_L2 = "api-ms-win-core-file-l2-1-0.dll";

		internal const string Crypt32 = "crypt32.dll";

		internal const string Debug = "api-ms-win-core-debug-l1-1-0.dll";

		internal const string Error_L1 = "api-ms-win-core-winrt-error-l1-1-0.dll";

		internal const string ErrorHandling = "api-ms-win-core-errorhandling-l1-1-0.dll";

		internal const string Eventing = "api-ms-win-eventing-provider-l1-1-0.dll";

		internal const string Handle = "api-ms-win-core-handle-l1-1-0.dll";

		internal const string Heap = "api-ms-win-core-heap-obsolete-l1-1-0.dll";

		internal const string Heap_L1 = "api-ms-win-core-heap-l1-1-0.dll";

		internal const string IO = "api-ms-win-core-io-l1-1-0.dll";

		internal const string IpHlpApi = "iphlpapi.dll";

		internal const string Kernel32 = "kernel32.dll";

		internal const string Kernel32_L1 = "api-ms-win-core-kernel32-legacy-l1-1-1.dll";

		internal const string Kernel32_L2 = "api-ms-win-core-kernel32-legacy-l1-1-0.dll";

		internal const string Keyboard = "ext-ms-win-ntuser-keyboard-l1-2-1.dll";

		internal const string LibraryLoader = "api-ms-win-core-libraryloader-l1-1-0.dll";

		internal const string Localization = "api-ms-win-core-localization-l1-2-0.dll";

		internal const string Memory_L1_0 = "api-ms-win-core-memory-l1-1-0.dll";

		internal const string Memory_L1_1 = "api-ms-win-core-memory-l1-1-1.dll";

		internal const string Memory_L1_2 = "api-ms-win-core-memory-l1-1-2.dll";

		internal const string Memory_L1_3 = "api-ms-win-core-memory-l1-1-3.dll";

		internal const string NCrypt = "ncrypt.dll";

		internal const string NtDll = "ntdll.dll";

		internal const string OleAut32 = "oleaut32.dll";

		internal const string Pipe = "api-ms-win-core-namedpipe-l1-1-0.dll";

		internal const string Pipe_L2 = "api-ms-win-core-namedpipe-l1-2-1.dll";

		internal const string ProcessEnvironment = "api-ms-win-core-processenvironment-l1-1-0.dll";

		internal const string ProcessThread_L1 = "api-ms-win-core-processthreads-l1-1-0.dll";

		internal const string ProcessThread_L1_1 = "api-ms-win-core-processthreads-l1-1-1.dll";

		internal const string ProcessThread_L1_2 = "api-ms-win-core-processthreads-l1-1-2.dll";

		internal const string ProcessTopology = "api-ms-win-core-processtopology-obsolete-l1-1-0.dll";

		internal const string Profile = "api-ms-win-core-profile-l1-1-0.dll";

		internal const string Psapi = "api-ms-win-core-psapi-l1-1-0.dll";

		internal const string Psapi_Obsolete = "api-ms-win-core-psapi-obsolete-l1-1-0.dll";

		internal const string Registry_L1 = "api-ms-win-core-registry-l1-1-0.dll";

		internal const string Registry_L2 = "api-ms-win-core-registry-l2-1-0.dll";

		internal const string RoBuffer = "api-ms-win-core-winrt-robuffer-l1-1-0.dll";

		internal const string SecurityBase = "api-ms-win-security-base-l1-1-0.dll";

		internal const string SecurityCpwl = "api-ms-win-security-cpwl-l1-1-0.dll";

		internal const string SecurityCryptoApi = "api-ms-win-security-cryptoapi-l1-1-0.dll";

		internal const string SecurityLsa = "api-ms-win-security-lsalookup-l2-1-0.dll";

		internal const string SecurityLsaPolicy = "api-ms-win-security-lsapolicy-l1-1-0.dll";

		internal const string SecurityProvider = "api-ms-win-security-provider-l1-1-0.dll";

		internal const string SecuritySddl = "api-ms-win-security-sddl-l1-1-0.dll";

		internal const string ServiceCore = "api-ms-win-service-core-l1-1-1.dll";

		internal const string ServiceMgmt_L1 = "api-ms-win-service-management-l1-1-0.dll";

		internal const string ServiceMgmt_L2 = "api-ms-win-service-management-l2-1-0.dll";

		internal const string ServiceWinSvc = "api-ms-win-service-winsvc-l1-1-0.dll";

		internal const string Sspi = "sspicli.dll";

		internal const string String_L1 = "api-ms-win-core-string-l1-1-0.dll";

		internal const string Synch = "api-ms-win-core-synch-l1-1-0.dll";

		internal const string SystemInfo_L1_1 = "api-ms-win-core-sysinfo-l1-1-0.dll";

		internal const string SystemInfo_L1_2 = "api-ms-win-core-sysinfo-l1-2-0.dll";

		internal const string ThreadPool = "api-ms-win-core-threadpool-l1-2-0.dll";

		internal const string User32 = "user32.dll";

		internal const string Util = "api-ms-win-core-util-l1-1-0.dll";

		internal const string Version = "api-ms-win-core-version-l1-1-0.dll";

		internal const string WinHttp = "winhttp.dll";

		internal const string Winsock = "Ws2_32.dll";

		internal const string Wow64 = "api-ms-win-core-wow64-l1-1-0.dll";

		internal const string Ws2_32 = "ws2_32.dll";

		internal const string Zlib = "clrcompression.dll";
	}

	internal struct LUID
	{
		internal uint LowPart;

		internal int HighPart;
	}

	[StructLayout(0, CharSet = 3)]
	internal struct TOKEN_GROUPS
	{
		internal uint GroupCount;

		internal SID_AND_ATTRIBUTES Groups;
	}

	[StructLayout(0, CharSet = 3)]
	internal struct SID_AND_ATTRIBUTES
	{
		internal System.IntPtr Sid;

		internal uint Attributes;

		internal static readonly long SizeOf = Marshal.SizeOf<SID_AND_ATTRIBUTES>();
	}

	[StructLayout(0, CharSet = 3)]
	internal struct TOKEN_PRIMARY_GROUP
	{
		internal System.IntPtr PrimaryGroup;
	}

	[StructLayout(0, CharSet = 3)]
	internal struct TOKEN_STATISTICS
	{
		internal LUID TokenId;

		internal LUID AuthenticationId;

		internal long ExpirationTime;

		internal uint TokenType;

		internal uint ImpersonationLevel;

		internal uint DynamicCharged;

		internal uint DynamicAvailable;

		internal uint GroupCount;

		internal uint PrivilegeCount;

		internal LUID ModifiedId;
	}

	internal static class mincore
	{
		internal class Errors
		{
			internal const int ERROR_SUCCESS = 0;

			internal const int ERROR_INVALID_FUNCTION = 1;

			internal const int ERROR_FILE_NOT_FOUND = 2;

			internal const int ERROR_PATH_NOT_FOUND = 3;

			internal const int ERROR_ACCESS_DENIED = 5;

			internal const int ERROR_INVALID_HANDLE = 6;

			internal const int ERROR_NOT_ENOUGH_MEMORY = 8;

			internal const int ERROR_INVALID_DATA = 13;

			internal const int ERROR_INVALID_DRIVE = 15;

			internal const int ERROR_NO_MORE_FILES = 18;

			internal const int ERROR_NOT_READY = 21;

			internal const int ERROR_BAD_LENGTH = 24;

			internal const int ERROR_SHARING_VIOLATION = 32;

			internal const int ERROR_LOCK_VIOLATION = 33;

			internal const int ERROR_HANDLE_EOF = 38;

			internal const int ERROR_FILE_EXISTS = 80;

			internal const int ERROR_INVALID_PARAMETER = 87;

			internal const int ERROR_BROKEN_PIPE = 109;

			internal const int ERROR_INSUFFICIENT_BUFFER = 122;

			internal const int ERROR_INVALID_NAME = 123;

			internal const int ERROR_NEGATIVE_SEEK = 131;

			internal const int ERROR_DIR_NOT_EMPTY = 145;

			internal const int ERROR_BAD_PATHNAME = 161;

			internal const int ERROR_LOCK_FAILED = 167;

			internal const int ERROR_BUSY = 170;

			internal const int ERROR_ALREADY_EXISTS = 183;

			internal const int ERROR_BAD_EXE_FORMAT = 193;

			internal const int ERROR_ENVVAR_NOT_FOUND = 203;

			internal const int ERROR_FILENAME_EXCED_RANGE = 206;

			internal const int ERROR_EXE_MACHINE_TYPE_MISMATCH = 216;

			internal const int ERROR_PIPE_BUSY = 231;

			internal const int ERROR_NO_DATA = 232;

			internal const int ERROR_PIPE_NOT_CONNECTED = 233;

			internal const int ERROR_MORE_DATA = 234;

			internal const int ERROR_NO_MORE_ITEMS = 259;

			internal const int ERROR_PARTIAL_COPY = 299;

			internal const int ERROR_ARITHMETIC_OVERFLOW = 534;

			internal const int ERROR_PIPE_CONNECTED = 535;

			internal const int ERROR_PIPE_LISTENING = 536;

			internal const int ERROR_OPERATION_ABORTED = 995;

			internal const int ERROR_IO_PENDING = 997;

			internal const int ERROR_NO_TOKEN = 1008;

			internal const int ERROR_DLL_INIT_FAILED = 1114;

			internal const int ERROR_NOT_FOUND = 1168;

			internal const int ERROR_NON_ACCOUNT_SID = 1257;

			internal const int ERROR_NOT_ALL_ASSIGNED = 1300;

			internal const int ERROR_UNKNOWN_REVISION = 1305;

			internal const int ERROR_INVALID_OWNER = 1307;

			internal const int ERROR_INVALID_PRIMARY_GROUP = 1308;

			internal const int ERROR_NO_SUCH_PRIVILEGE = 1313;

			internal const int ERROR_PRIVILEGE_NOT_HELD = 1314;

			internal const int ERROR_INVALID_ACL = 1336;

			internal const int ERROR_INVALID_SECURITY_DESCR = 1338;

			internal const int ERROR_INVALID_SID = 1337;

			internal const int ERROR_BAD_IMPERSONATION_LEVEL = 1346;

			internal const int ERROR_CANT_OPEN_ANONYMOUS = 1347;

			internal const int ERROR_NO_SECURITY_ON_OBJECT = 1350;

			internal const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 1789;

			internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 1815;

			internal const int EFail = -2147467259;

			internal const int E_FILENOTFOUND = -2147024894;
		}

		[DllImport("api-ms-win-core-processthreads-l1-1-0.dll", SetLastError = true)]
		internal static extern System.IntPtr GetCurrentProcess();

		[DllImport("api-ms-win-core-processthreads-l1-1-0.dll")]
		internal static extern System.IntPtr GetCurrentThread();

		[DllImport("api-ms-win-core-processthreads-l1-1-0.dll", SetLastError = true)]
		internal static extern bool OpenProcessToken(System.IntPtr ProcessToken, TokenAccessLevels DesiredAccess, out SafeAccessTokenHandle TokenHandle);

		[DllImport("api-ms-win-security-base-l1-1-0.dll", SetLastError = true)]
		internal static extern bool CheckTokenMembership(SafeAccessTokenHandle TokenHandle, byte[] SidToCheck, ref bool IsMember);

		[DllImport("api-ms-win-security-base-l1-1-0.dll", SetLastError = true)]
		internal static extern bool GetTokenInformation(SafeAccessTokenHandle TokenHandle, uint TokenInformationClass, SafeLocalAllocHandle TokenInformation, uint TokenInformationLength, out uint ReturnLength);

		[DllImport("api-ms-win-security-base-l1-1-0.dll", SetLastError = true)]
		internal static extern bool GetTokenInformation(System.IntPtr TokenHandle, uint TokenInformationClass, SafeLocalAllocHandle TokenInformation, uint TokenInformationLength, out uint ReturnLength);

		[DllImport("api-ms-win-security-base-l1-1-0.dll", SetLastError = true)]
		internal static extern bool DuplicateTokenEx(SafeAccessTokenHandle hExistingToken, uint dwDesiredAccess, System.IntPtr lpTokenAttributes, uint ImpersonationLevel, uint TokenType, ref SafeAccessTokenHandle phNewToken);

		[DllImport("api-ms-win-core-handle-l1-1-0.dll", SetLastError = true)]
		internal static extern bool DuplicateHandle(System.IntPtr hSourceProcessHandle, System.IntPtr hSourceHandle, System.IntPtr hTargetProcessHandle, ref SafeAccessTokenHandle lpTargetHandle, uint dwDesiredAccess, bool bInheritHandle, uint dwOptions);

		[DllImport("api-ms-win-core-handle-l1-1-0.dll", SetLastError = true)]
		[return: MarshalAs(2)]
		internal static extern bool CloseHandle(System.IntPtr handle);

		[DllImport("sspicli.dll", SetLastError = true)]
		internal static extern int LsaGetLogonSessionData(ref LUID LogonId, ref SafeLsaReturnBufferHandle ppLogonSessionData);

		[DllImport("sspicli.dll", SetLastError = true)]
		internal static extern int LsaFreeReturnBuffer(System.IntPtr handle);

		[DllImport("api-ms-win-security-lsapolicy-l1-1-0.dll", CharSet = 3, SetLastError = true)]
		internal static extern uint LsaLookupNames2(SafeLsaPolicyHandle handle, int flags, int count, UNICODE_STRING[] names, ref SafeLsaMemoryHandle referencedDomains, ref SafeLsaMemoryHandle sids);

		[DllImport("api-ms-win-security-lsapolicy-l1-1-0.dll", CharSet = 3, SetLastError = true)]
		internal static extern uint LsaLookupSids(SafeLsaPolicyHandle handle, int count, System.IntPtr[] sids, ref SafeLsaMemoryHandle referencedDomains, ref SafeLsaMemoryHandle names);

		[DllImport("api-ms-win-security-lsapolicy-l1-1-0.dll", SetLastError = true)]
		internal static extern int LsaClose(System.IntPtr handle);

		[DllImport("api-ms-win-security-lsapolicy-l1-1-0.dll", SetLastError = true)]
		internal static extern int LsaFreeMemory(System.IntPtr handle);

		[DllImport("api-ms-win-security-lsapolicy-l1-1-0.dll", CharSet = 3, SetLastError = true)]
		internal static extern uint LsaOpenPolicy(string systemName, ref LSA_OBJECT_ATTRIBUTES attributes, int accessMask, out SafeLsaPolicyHandle handle);

		[DllImport("api-ms-win-security-sddl-l1-1-0.dll", CharSet = 3, EntryPoint = "ConvertStringSidToSidW", SetLastError = true)]
		internal static extern int ConvertStringSidToSid(string stringSid, out System.IntPtr ByteArray);

		[DllImport("api-ms-win-security-base-l1-1-0.dll", CharSet = 3, SetLastError = true)]
		internal static extern int CreateWellKnownSid(int sidType, byte[] domainSid, byte[] resultSid, ref uint resultSidLength);

		[DllImport("api-ms-win-security-base-l1-1-0.dll", CharSet = 3, SetLastError = true)]
		internal static extern int GetWindowsAccountDomainSid(byte[] sid, byte[] resultSid, ref uint resultSidLength);

		[DllImport("api-ms-win-security-base-l1-1-0.dll", CharSet = 3, SetLastError = true)]
		internal static extern int IsWellKnownSid(byte[] sid, int type);

		[DllImport("api-ms-win-security-base-l1-1-0.dll", CharSet = 3, EntryPoint = "EqualDomainSid", SetLastError = true)]
		internal static extern int IsEqualDomainSid(byte[] sid1, byte[] sid2, out bool result);

		[DllImport("api-ms-win-core-processthreads-l1-1-0.dll", SetLastError = true)]
		private static extern bool OpenThreadToken(System.IntPtr ThreadHandle, TokenAccessLevels dwDesiredAccess, bool bOpenAsSelf, out SafeAccessTokenHandle phThreadToken);

		internal static bool OpenThreadToken(TokenAccessLevels desiredAccess, WinSecurityContext openAs, out SafeAccessTokenHandle tokenHandle)
		{
			bool bOpenAsSelf = true;
			if (openAs == WinSecurityContext.Thread)
			{
				bOpenAsSelf = false;
			}
			if (OpenThreadToken(GetCurrentThread(), desiredAccess, bOpenAsSelf, out tokenHandle))
			{
				return true;
			}
			if (openAs == WinSecurityContext.Both)
			{
				bOpenAsSelf = false;
				if (OpenThreadToken(GetCurrentThread(), desiredAccess, bOpenAsSelf, out tokenHandle))
				{
					return true;
				}
			}
			return false;
		}

		[DllImport("api-ms-win-security-base-l1-1-0.dll", CharSet = 3, ExactSpelling = true, SetLastError = true)]
		internal static extern bool RevertToSelf();

		[DllImport("api-ms-win-security-base-l1-1-0.dll", CharSet = 3, SetLastError = true)]
		internal static extern bool ImpersonateLoggedOnUser(SafeAccessTokenHandle userToken);

		[DllImport("ntdll.dll", CharSet = 3, SetLastError = true)]
		internal static extern int RtlNtStatusToDosError(int status);
	}

	internal class LuidOptions
	{
		internal const uint ANONYMOUS_LOGON_LUID = 998u;
	}

	internal class SecurityIdentifier
	{
		internal const int SECURITY_ANONYMOUS_LOGON_RID = 7;

		internal const int SECURITY_AUTHENTICATED_USER_RID = 11;

		internal const int SECURITY_LOCAL_SYSTEM_RID = 18;

		internal const int SECURITY_BUILTIN_DOMAIN_RID = 32;
	}

	internal class SecurityGroups
	{
		internal const uint SE_GROUP_MANDATORY = 1u;

		internal const uint SE_GROUP_ENABLED_BY_DEFAULT = 2u;

		internal const uint SE_GROUP_ENABLED = 4u;

		internal const uint SE_GROUP_OWNER = 8u;

		internal const uint SE_GROUP_USE_FOR_DENY_ONLY = 16u;

		internal const uint SE_GROUP_LOGON_ID = 3221225472u;

		internal const uint SE_GROUP_RESOURCE = 536870912u;
	}

	internal class DuplicateHandleOptions
	{
		internal const uint DUPLICATE_CLOSE_SOURCE = 1u;

		internal const uint DUPLICATE_SAME_ACCESS = 2u;

		internal const uint DUPLICATE_SAME_ATTRIBUTES = 4u;
	}

	internal class StatusOptions
	{
		internal const uint STATUS_SUCCESS = 0u;

		internal const uint STATUS_SOME_NOT_MAPPED = 263u;

		internal const uint STATUS_INVALID_PARAMETER = 3221225485u;

		internal const uint STATUS_NO_MEMORY = 3221225495u;

		internal const uint STATUS_OBJECT_NAME_NOT_FOUND = 3221225524u;

		internal const uint STATUS_NONE_MAPPED = 3221225587u;

		internal const uint STATUS_INSUFFICIENT_RESOURCES = 3221225626u;

		internal const uint STATUS_ACCESS_DENIED = 3221225506u;

		internal const uint STATUS_ACCOUNT_RESTRICTION = 3221225582u;
	}

	internal struct LSA_TRANSLATED_NAME
	{
		internal int Use;

		internal UNICODE_INTPTR_STRING Name;

		internal int DomainIndex;
	}

	internal struct LSA_OBJECT_ATTRIBUTES
	{
		internal int Length;

		internal System.IntPtr RootDirectory;

		internal System.IntPtr ObjectName;

		internal int Attributes;

		internal System.IntPtr SecurityDescriptor;

		internal System.IntPtr SecurityQualityOfService;
	}

	internal struct LSA_TRANSLATED_SID2
	{
		internal int Use;

		internal System.IntPtr Sid;

		internal int DomainIndex;

		private uint Flags;
	}

	internal struct LSA_TRUST_INFORMATION
	{
		internal UNICODE_INTPTR_STRING Name;

		internal System.IntPtr Sid;
	}

	internal struct LSA_REFERENCED_DOMAIN_LIST
	{
		internal int Entries;

		internal System.IntPtr Domains;
	}

	[StructLayout(0, CharSet = 3)]
	internal struct UNICODE_INTPTR_STRING
	{
		internal ushort Length;

		internal ushort MaxLength;

		internal System.IntPtr Buffer;
	}

	[StructLayout(0, CharSet = 3)]
	internal struct SECURITY_LOGON_SESSION_DATA
	{
		internal uint Size;

		internal LUID LogonId;

		internal UNICODE_INTPTR_STRING UserName;

		internal UNICODE_INTPTR_STRING LogonDomain;

		internal UNICODE_INTPTR_STRING AuthenticationPackage;

		internal uint LogonType;

		internal uint Session;

		internal System.IntPtr Sid;

		internal long LogonTime;
	}

	[StructLayout(0, CharSet = 3)]
	internal struct UNICODE_STRING
	{
		internal ushort Length;

		internal ushort MaximumLength;

		[MarshalAs(21)]
		internal string Buffer;
	}

	internal static class mincore_obsolete
	{
		internal const int LMEM_FIXED = 0;

		internal const int LPTR = 64;

		[DllImport("api-ms-win-core-heap-obsolete-l1-1-0.dll", SetLastError = true)]
		internal static extern System.IntPtr LocalFree(System.IntPtr handle);

		[DllImport("api-ms-win-core-heap-obsolete-l1-1-0.dll", SetLastError = true)]
		internal static extern SafeLocalAllocHandle LocalAlloc(int uFlags, System.UIntPtr sizetdwBytes);
	}

	internal class SspiCli
	{
		internal static class AuthenticationPackageNames
		{
			internal const string MICROSOFT_KERBEROS_NAME_A = "Kerberos";
		}

		internal enum KERB_LOGON_SUBMIT_TYPE
		{
			KerbS4ULogon = 12
		}

		internal struct KERB_S4U_LOGON
		{
			internal KERB_LOGON_SUBMIT_TYPE MessageType;

			internal KerbS4uLogonFlags Flags;

			internal LSA_UNICODE_STRING ClientUpn;

			internal LSA_UNICODE_STRING ClientRealm;
		}

		[Flags]
		internal enum KerbS4uLogonFlags
		{
			None = 0,
			KERB_S4U_LOGON_FLAG_CHECK_LOGONHOURS = 2,
			KERB_S4U_LOGON_FLAG_IDENTITY = 8
		}

		internal struct LSA_STRING
		{
			internal ushort Length;

			internal ushort MaximumLength;

			internal System.IntPtr Buffer;

			internal LSA_STRING(System.IntPtr pBuffer, ushort length)
			{
				Length = length;
				MaximumLength = length;
				Buffer = pBuffer;
			}
		}

		internal struct LSA_UNICODE_STRING
		{
			internal ushort Length;

			internal ushort MaximumLength;

			internal System.IntPtr Buffer;

			internal LSA_UNICODE_STRING(System.IntPtr pBuffer, ushort length)
			{
				Length = length;
				MaximumLength = length;
				Buffer = pBuffer;
			}
		}

		internal struct QUOTA_LIMITS
		{
			internal System.IntPtr PagedPoolLimit;

			internal System.IntPtr NonPagedPoolLimit;

			internal System.IntPtr MinimumWorkingSetSize;

			internal System.IntPtr MaximumWorkingSetSize;

			internal System.IntPtr PagefileLimit;

			internal long TimeLimit;
		}

		internal enum SECURITY_LOGON_TYPE
		{
			Network = 3
		}

		internal struct TOKEN_SOURCE
		{
			[MarshalAs(30, SizeConst = 8)]
			internal byte[] SourceName;

			internal LUID SourceIdentifier;

			internal const int TOKEN_SOURCE_LENGTH = 8;
		}

		[DllImport("sspicli.dll")]
		internal static extern int LsaConnectUntrusted(out SafeLsaHandle LsaHandle);

		[DllImport("sspicli.dll")]
		internal static extern int LsaDeregisterLogonProcess(System.IntPtr LsaHandle);

		[DllImport("sspicli.dll")]
		internal static extern int LsaLogonUser([In] SafeLsaHandle LsaHandle, [In] ref LSA_STRING OriginName, [In] SECURITY_LOGON_TYPE LogonType, [In] int AuthenticationPackage, [In] System.IntPtr AuthenticationInformation, [In] int AuthenticationInformationLength, [In] System.IntPtr LocalGroups, [In] ref TOKEN_SOURCE SourceContext, out SafeLsaReturnBufferHandle ProfileBuffer, out int ProfileBufferLength, out LUID LogonId, out SafeAccessTokenHandle Token, out QUOTA_LIMITS Quotas, out int SubStatus);

		[DllImport("sspicli.dll")]
		internal static extern int LsaLookupAuthenticationPackage(SafeLsaHandle LsaHandle, [In] ref LSA_STRING PackageName, out int AuthenticationPackage);
	}

	internal class SecurityBase
	{
		[DllImport("api-ms-win-security-base-l1-1-0.dll")]
		internal static extern bool AllocateLocallyUniqueId(out LUID Luid);
	}
}
namespace FxResources.System.Security.Principal.Windows
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static ResourceManager s_resourceManager;

		private const string s_resourcesName = "FxResources.System.Security.Principal.Windows.SR";

		private static ResourceManager ResourceManager
		{
			get
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Expected O, but got Unknown
				if (s_resourceManager == null)
				{
					s_resourceManager = new ResourceManager(ResourceType);
				}
				return s_resourceManager;
			}
		}

		internal static string Arg_EmptyCollection => GetResourceString("Arg_EmptyCollection", null);

		internal static string Arg_EnumIllegalVal => GetResourceString("Arg_EnumIllegalVal", null);

		internal static string Argument_ImpersonateUser => GetResourceString("Argument_ImpersonateUser", null);

		internal static string Argument_ImproperType => GetResourceString("Argument_ImproperType", null);

		internal static string Argument_InvalidImpersonationToken => GetResourceString("Argument_InvalidImpersonationToken", null);

		internal static string Argument_InvalidValue => GetResourceString("Argument_InvalidValue", null);

		internal static string Argument_TokenZero => GetResourceString("Argument_TokenZero", null);

		internal static string ArgumentOutOfRange_ArrayTooSmall => GetResourceString("ArgumentOutOfRange_ArrayTooSmall", null);

		internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum", null);

		internal static string Argument_StringZeroLength => GetResourceString("Argument_StringZeroLength", null);

		internal static string ExecutionEngine_MissingSecurityDescriptor => GetResourceString("ExecutionEngine_MissingSecurityDescriptor", null);

		internal static string IdentityReference_AccountNameTooLong => GetResourceString("IdentityReference_AccountNameTooLong", null);

		internal static string IdentityReference_CannotCreateLogonIdsSid => GetResourceString("IdentityReference_CannotCreateLogonIdsSid", null);

		internal static string IdentityReference_DomainNameTooLong => GetResourceString("IdentityReference_DomainNameTooLong", null);

		internal static string IdentityReference_DomainSidRequired => GetResourceString("IdentityReference_DomainSidRequired", null);

		internal static string IdentityReference_IdentifierAuthorityTooLarge => GetResourceString("IdentityReference_IdentifierAuthorityTooLarge", null);

		internal static string IdentityReference_IdentityNotMapped => GetResourceString("IdentityReference_IdentityNotMapped", null);

		internal static string IdentityReference_InvalidNumberOfSubauthorities => GetResourceString("IdentityReference_InvalidNumberOfSubauthorities", null);

		internal static string IdentityReference_InvalidSidRevision => GetResourceString("IdentityReference_InvalidSidRevision", null);

		internal static string IdentityReference_MustBeIdentityReference => GetResourceString("IdentityReference_MustBeIdentityReference", null);

		internal static string IdentityReference_NotAWindowsDomain => GetResourceString("IdentityReference_NotAWindowsDomain", null);

		internal static string InvalidOperation_AnonymousCannotImpersonate => GetResourceString("InvalidOperation_AnonymousCannotImpersonate", null);

		internal static string PlatformNotSupported_RequiresW2kSP3 => GetResourceString("PlatformNotSupported_RequiresW2kSP3", null);

		internal static string UnknownError_Num => GetResourceString("UnknownError_Num", null);

		internal static System.Type ResourceType => typeof(SR);

		[MethodImpl(8)]
		private static bool UsingResourceKeys()
		{
			return false;
		}

		internal static string GetResourceString(string resourceKey, string defaultString)
		{
			string text = null;
			try
			{
				text = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			if (defaultString != null && resourceKey.Equals(text, (StringComparison)4))
			{
				return defaultString;
			}
			return text;
		}

		internal static string Format(string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + string.Join(", ", args);
				}
				return string.Format(resourceFormat, args);
			}
			return resourceFormat;
		}

		internal static string Format(string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", new object[2] { resourceFormat, p1 });
			}
			return string.Format(resourceFormat, p1);
		}

		internal static string Format(string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", new object[3] { resourceFormat, p1, p2 });
			}
			return string.Format(resourceFormat, p1, p2);
		}

		internal static string Format(string resourceFormat, object p1, object p2, object p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", new object[4] { resourceFormat, p1, p2, p3 });
			}
			return string.Format(resourceFormat, p1, p2, p3);
		}
	}
}
namespace System.Security.Principal
{
	public sealed class IdentityNotMappedException : System.Exception
	{
		private IdentityReferenceCollection _unmappedIdentities;

		public IdentityReferenceCollection UnmappedIdentities
		{
			get
			{
				if (_unmappedIdentities == null)
				{
					_unmappedIdentities = new IdentityReferenceCollection();
				}
				return _unmappedIdentities;
			}
		}

		public IdentityNotMappedException()
			: base(System.SR.IdentityReference_IdentityNotMapped)
		{
		}

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

		public IdentityNotMappedException(string message, System.Exception inner)
			: base(message, inner)
		{
		}

		internal IdentityNotMappedException(string message, IdentityReferenceCollection unmappedIdentities)
			: this(message)
		{
			_unmappedIdentities = unmappedIdentities;
		}
	}
	public abstract class IdentityReference
	{
		public abstract string Value { get; }

		internal IdentityReference()
		{
		}

		public abstract bool IsValidTargetType(System.Type targetType);

		public abstract IdentityReference Translate(System.Type targetType);

		public abstract virtual bool Equals(object o);

		public abstract virtual int GetHashCode();

		public abstract virtual string ToString();

		public static bool operator ==(IdentityReference left, IdentityReference right)
		{
			if ((object)left == right)
			{
				return true;
			}
			if ((object)left == null || (object)right == null)
			{
				return false;
			}
			return ((object)left).Equals((object)right);
		}

		public static bool operator !=(IdentityReference left, IdentityReference right)
		{
			return !(left == right);
		}
	}
	[DefaultMember("Item")]
	public class IdentityReferenceCollection : System.Collections.Generic.ICollection<IdentityReference>, System.Collections.Generic.IEnumerable<IdentityReference>, System.Collections.IEnumerable
	{
		private readonly List<IdentityReference> _Identities;

		public int Count => _Identities.Count;

		bool System.Collections.Generic.ICollection<IdentityReference>.IsReadOnly => false;

		public IdentityReference this[int index]
		{
			get
			{
				return _Identities[index];
			}
			set
			{
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				if (value == null)
				{
					throw new ArgumentNullException("value");
				}
				_Identities[index] = value;
			}
		}

		internal List<IdentityReference> Identities => _Identities;

		public IdentityReferenceCollection()
			: this(0)
		{
		}

		public IdentityReferenceCollection(int capacity)
		{
			_Identities = new List<IdentityReference>(capacity);
		}

		public void CopyTo(IdentityReference[] array, int offset)
		{
			_Identities.CopyTo(0, array, offset, Count);
		}

		public void Add(IdentityReference identity)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (identity == null)
			{
				throw new ArgumentNullException("identity");
			}
			_Identities.Add(identity);
		}

		public bool Remove(IdentityReference identity)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (identity == null)
			{
				throw new ArgumentNullException("identity");
			}
			if (Contains(identity))
			{
				return _Identities.Remove(identity);
			}
			return false;
		}

		public void Clear()
		{
			_Identities.Clear();
		}

		public bool Contains(IdentityReference identity)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (identity == null)
			{
				throw new ArgumentNullException("identity");
			}
			return _Identities.Contains(identity);
		}

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return (System.Collections.IEnumerator)GetEnumerator();
		}

		public System.Collections.Generic.IEnumerator<IdentityReference> GetEnumerator()
		{
			return new IdentityReferenceEnumerator(this);
		}

		public IdentityReferenceCollection Translate(System.Type targetType)
		{
			return Translate(targetType, forceSuccess: false);
		}

		public IdentityReferenceCollection Translate(System.Type targetType, bool forceSuccess)
		{
			//IL_0008: 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_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d8: Unknown result type (might be due to invalid IL or missing references)
			if (targetType == null)
			{
				throw new ArgumentNullException("targetType");
			}
			if (!IntrospectionExtensions.GetTypeInfo(targetType).IsSubclassOf(typeof(IdentityReference)))
			{
				throw new ArgumentException(System.SR.IdentityReference_MustBeIdentityReference, "targetType");
			}
			if (Identities.Count == 0)
			{
				return new IdentityReferenceCollection();
			}
			int num = 0;
			int num2 = 0;
			for (int i = 0; i < Identities.Count; i++)
			{
				System.Type type = ((object)Identities[i]).GetType();
				if (type == targetType)
				{
					continue;
				}
				if (type == typeof(SecurityIdentifier))
				{
					num++;
					continue;
				}
				if (type == typeof(NTAccount))
				{
					num2++;
					continue;
				}
				throw new NotSupportedException();
			}
			bool flag = false;
			IdentityReferenceCollection identityReferenceCollection = null;
			IdentityReferenceCollection identityReferenceCollection2 = null;
			if (num == Count)
			{
				flag = true;
				identityReferenceCollection = this;
			}
			else if (num > 0)
			{
				identityReferenceCollection = new IdentityReferenceCollection(num);
			}
			if (num2 == Count)
			{
				flag = true;
				identityReferenceCollection2 = this;
			}
			else if (num2 > 0)
			{
				identityReferenceCollection2 = new IdentityReferenceCollection(num2);
			}
			IdentityReferenceCollection identityReferenceCollection3 = null;
			if (!flag)
			{
				identityReferenceCollection3 = new IdentityReferenceCollection(Identities.Count);
				for (int j = 0; j < Identities.Count; j++)
				{
					IdentityReference identityReference = this[j];
					System.Type type2 = ((object)identityReference).GetType();
					if (type2 == targetType)
					{
						continue;
					}
					if (type2 == typeof(SecurityIdentifier))
					{
						identityReferenceCollection.Add(identityReference);
						continue;
					}
					if (type2 == typeof(NTAccount))
					{
						identityReferenceCollection2.Add(identityReference);
						continue;
					}
					throw new NotSupportedException();
				}
			}
			bool someFailed = false;
			IdentityReferenceCollection identityReferenceCollection4 = null;
			IdentityReferenceCollection identityReferenceCollection5 = null;
			if (num > 0)
			{
				identityReferenceCollection4 = SecurityIdentifier.Translate(identityReferenceCollection, targetType, out someFailed);
				if (flag && !(forceSuccess && someFailed))
				{
					identityReferenceCollection3 = identityReferenceCollection4;
				}
			}
			if (num2 > 0)
			{
				identityReferenceCollection5 = NTAccount.Translate(identityReferenceCollection2, targetType, out someFailed);
				if (flag && !(forceSuccess && someFailed))
				{
					identityReferenceCollection3 = identityReferenceCollection5;
				}
			}
			if (forceSuccess && someFailed)
			{
				identityReferenceCollection3 = new IdentityReferenceCollection();
				if (identityReferenceCollection4 != null)
				{
					System.Collections.Generic.IEnumerator<IdentityReference> enumerator = identityReferenceCollection4.GetEnumerator();
					try
					{
						while (((System.Collections.IEnumerator)enumerator).MoveNext())
						{
							IdentityReference current = enumerator.Current;
							if (((object)current).GetType() != targetType)
							{
								identityReferenceCollection3.Add(current);
							}
						}
					}
					finally
					{
						((System.IDisposable)enumerator)?.Dispose();
					}
				}
				if (identityReferenceCollection5 != null)
				{
					System.Collections.Generic.IEnumerator<IdentityReference> enumerator2 = identityReferenceCollection5.GetEnumerator();
					try
					{
						while (((System.Collections.IEnumerator)enumerator2).MoveNext())
						{
							IdentityReference current2 = enumerator2.Current;
							if (((object)current2).GetType() != targetType)
							{
								identityReferenceCollection3.Add(current2);
							}
						}
					}
					finally
					{
						((System.IDisposable)enumerator2)?.Dispose();
					}
				}
				throw new IdentityNotMappedException(System.SR.IdentityReference_IdentityNotMapped, identityReferenceCollection3);
			}
			if (!flag)
			{
				num = 0;
				num2 = 0;
				identityReferenceCollection3 = new IdentityReferenceCollection(Identities.Count);
				for (int k = 0; k < Identities.Count; k++)
				{
					IdentityReference identityReference2 = this[k];
					System.Type type3 = ((object)identityReference2).GetType();
					if (type3 == targetType)
					{
						identityReferenceCollection3.Add(identityReference2);
						continue;
					}
					if (type3 == typeof(SecurityIdentifier))
					{
						identityReferenceCollection3.Add(identityReferenceCollection4[num++]);
						continue;
					}
					if (type3 == typeof(NTAccount))
					{
						identityReferenceCollection3.Add(identityReferenceCollection5[num2++]);
						continue;
					}
					throw new NotSupportedException();
				}
			}
			return identityReferenceCollection3;
		}
	}
	internal class IdentityReferenceEnumerator : System.Collections.Generic.IEnumerator<IdentityReference>, System.Collections.IEnumerator, System.IDisposable
	{
		private int _current;

		private readonly IdentityReferenceCollection _collection;

		object System.Collections.IEnumerator.Current => Current;

		public IdentityReference Current => _collection.Identities[_current];

		internal IdentityReferenceEnumerator(IdentityReferenceCollection collection)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			_collection = collection;
			_current = -1;
		}

		public bool MoveNext()
		{
			_current++;
			return _current < _collection.Count;
		}

		public void Reset()
		{
			_current = -1;
		}

		public void Dispose()
		{
		}
	}
	public sealed class NTAccount : IdentityReference
	{
		private readonly string _name;

		internal const int MaximumAccountNameLength = 256;

		internal const int MaximumDomainNameLength = 255;

		public override string Value => ((object)this).ToString();

		public NTAccount(string domainName, string accountName)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: 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)
			if (accountName == null)
			{
				throw new ArgumentNullException("accountName");
			}
			if (accountName.Length == 0)
			{
				throw new ArgumentException(System.SR.Argument_StringZeroLength, "accountName");
			}
			if (accountName.Length > 256)
			{
				throw new ArgumentException(System.SR.IdentityReference_AccountNameTooLong, "accountName");
			}
			if (domainName != null && domainName.Length > 255)
			{
				throw new ArgumentException(System.SR.IdentityReference_DomainNameTooLong, "domainName");
			}
			if (domainName == null || domainName.Length == 0)
			{
				_name = accountName;
			}
			else
			{
				_name = domainName + "\\" + accountName;
			}
		}

		public NTAccount(string name)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			if (name.Length == 0)
			{
				throw new ArgumentException(System.SR.Argument_StringZeroLength, "name");
			}
			if (name.Length > 512)
			{
				throw new ArgumentException(System.SR.IdentityReference_AccountNameTooLong, "name");
			}
			_name = name;
		}

		public override bool IsValidTargetType(System.Type targetType)
		{
			if (targetType == typeof(SecurityIdentifier))
			{
				return true;
			}
			if (targetType == typeof(NTAccount))
			{
				return true;
			}
			return false;
		}

		public override IdentityReference Translate(System.Type targetType)
		{
			//IL_0008: 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)
			if (targetType == null)
			{
				throw new ArgumentNullException("targetType");
			}
			if (targetType == typeof(NTAccount))
			{
				return this;
			}
			if (targetType == typeof(SecurityIdentifier))
			{
				IdentityReferenceCollection identityReferenceCollection = new IdentityReferenceCollection(1);
				identityReferenceCollection.Add(this);
				IdentityReferenceCollection identityReferenceCollection2 = Translate(identityReferenceCollection, targetType, forceSuccess: true);
				return identityReferenceCollection2[0];
			}
			throw new ArgumentException(System.SR.IdentityReference_MustBeIdentityReference, "targetType");
		}

		public override bool Equals(object o)
		{
			return this == o as NTAccount;
		}

		public override int GetHashCode()
		{
			return StringComparer.OrdinalIgnoreCase.GetHashCode(_name);
		}

		public override string ToString()
		{
			return _name;
		}

		internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceAccounts, System.Type targetType, bool forceSuccess)
		{
			bool someFailed = false;
			IdentityReferenceCollection identityReferenceCollection = Translate(sourceAccounts, targetType, out someFailed);
			if (forceSuccess && someFailed)
			{
				IdentityReferenceCollection identityReferenceCollection2 = new IdentityReferenceCollection();
				System.Collections.Generic.IEnumerator<IdentityReference> enumerator = identityReferenceCollection.GetEnumerator();
				try
				{
					while (((System.Collections.IEnumerator)enumerator).MoveNext())
					{
						IdentityReference current = enumerator.Current;
						if (((object)current).GetType() != targetType)
						{
							identityReferenceCollection2.Add(current);
						}
					}
				}
				finally
				{
					((System.IDisposable)enumerator)?.Dispose();
				}
				throw new IdentityNotMappedException(System.SR.IdentityReference_IdentityNotMapped, identityReferenceCollection2);
			}
			return identityReferenceCollection;
		}

		internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceAccounts, System.Type targetType, out bool someFailed)
		{
			//IL_0008: 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)
			if (sourceAccounts == null)
			{
				throw new ArgumentNullException("sourceAccounts");
			}
			if (targetType == typeof(SecurityIdentifier))
			{
				return TranslateToSids(sourceAccounts, out someFailed);
			}
			throw new ArgumentException(System.SR.IdentityReference_MustBeIdentityReference, "targetType");
		}

		public static bool operator ==(NTAccount left, NTAccount right)
		{
			if ((object)left == right)
			{
				return true;
			}
			if ((object)left == null || (object)right == null)
			{
				return false;
			}
			return ((object)left).ToString().Equals(((object)right).ToString(), (StringComparison)5);
		}

		public static bool operator !=(NTAccount left, NTAccount right)
		{
			return !(left == right);
		}

		private static IdentityReferenceCollection TranslateToSids(IdentityReferenceCollection sourceAccounts, out bool someFailed)
		{
			//IL_0008: 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_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			if (sourceAccounts == null)
			{
				throw new ArgumentNullException("sourceAccounts");
			}
			if (sourceAccounts.Count == 0)
			{
				throw new ArgumentException(System.SR.Arg_EmptyCollection, "sourceAccounts");
			}
			SafeLsaPolicyHandle safeLsaPolicyHandle = SafeLsaPolicyHandle.InvalidHandle;
			SafeLsaMemoryHandle referencedDomains = SafeLsaMemoryHandle.InvalidHandle;
			SafeLsaMemoryHandle sids = SafeLsaMemoryHandle.InvalidHandle;
			try
			{
				global::Interop.UNICODE_STRING[] array = new global::Interop.UNICODE_STRING[sourceAccounts.Count];
				int num = 0;
				System.Collections.Generic.IEnumerator<IdentityReference> enumerator = sourceAccounts.GetEnumerator();
				try
				{
					while (((System.Collections.IEnumerator)enumerator).MoveNext())
					{
						IdentityReference current = enumerator.Current;
						NTAccount nTAccount = current as NTAccount;
						if (nTAccount == null)
						{
							throw new ArgumentException(System.SR.Argument_ImproperType, "sourceAccounts");
						}
						array[num].Buffer = ((object)nTAccount).ToString();
						if (array[num].Buffer.Length * 2 + 2 > 65535)
						{
							throw new InvalidOperationException();
						}
						array[num].Length = (ushort)(array[num].Buffer.Length * 2);
						array[num].MaximumLength = (ushort)(array[num].Length + 2);
						num++;
					}
				}
				finally
				{
					((System.IDisposable)enumerator)?.Dispose();
				}
				safeLsaPolicyHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);
				someFailed = false;
				uint num2 = global::Interop.mincore.LsaLookupNames2(safeLsaPolicyHandle, 0, sourceAccounts.Count, array, ref referencedDomains, ref sids);
				switch (num2)
				{
				case 3221225495u:
				case 3221225626u:
					throw new OutOfMemoryException();
				case 3221225506u:
					throw new UnauthorizedAccessException();
				case 3221225587u:
				case 263u:
					someFailed = true;
					break;
				default:
				{
					int error = global::Interop.mincore.RtlNtStatusToDosError((int)num2);
					_ = 1789;
					throw new Win32Exception(error);
				}
				case 0u:
					break;
				}
				IdentityReferenceCollection identityReferenceCollection = new IdentityReferenceCollection(sourceAccounts.Count);
				if (num2 == 0 || num2 == 263)
				{
					((SafeBuffer)sids).Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf<global::Interop.LSA_TRANSLATED_SID2>());
					Win32.InitializeReferencedDomainsPointer(referencedDomains);
					global::Interop.LSA_TRANSLATED_SID2[] array2 = new global::Interop.LSA_TRANSLATED_SID2[sourceAccounts.Count];
					((SafeBuffer)sids).ReadArray<global::Interop.LSA_TRANSLATED_SID2>(0uL, array2, 0, array2.Length);
					for (int i = 0; i < sourceAccounts.Count; i++)
					{
						global::Interop.LSA_TRANSLATED_SID2 lSA_TRANSLATED_SID = array2[i];
						switch ((SidNameUse)lSA_TRANSLATED_SID.Use)
						{
						case SidNameUse.User:
						case SidNameUse.Group:
						case SidNameUse.Alias:
						case SidNameUse.WellKnownGroup:
						case SidNameUse.Computer:
							identityReferenceCollection.Add(new SecurityIdentifier(lSA_TRANSLATED_SID.Sid, noDemand: true));
							break;
						default:
							someFailed = true;
							identityReferenceCollection.Add(sourceAccounts[i]);
							break;
						}
					}
				}
				else
				{
					for (int j = 0; j < sourceAccounts.Count; j++)
					{
						identityReferenceCollection.Add(sourceAccounts[j]);
					}
				}
				return identityReferenceCollection;
			}
			finally
			{
				((SafeHandle)safeLsaPolicyHandle).Dispose();
				((SafeHandle)referencedDomains).Dispose();
				((SafeHandle)sids).Dispose();
			}
		}
	}
	internal enum IdentifierAuthority : long
	{
		NullAuthority,
		WorldAuthority,
		LocalAuthority,
		CreatorAuthority,
		NonUniqueAuthority,
		NTAuthority,
		SiteServerAuthority,
		InternetSiteAuthority,
		ExchangeAuthority,
		ResourceManagerAuthority
	}
	internal enum SidNameUse
	{
		User = 1,
		Group,
		Domain,
		Alias,
		WellKnownGroup,
		DeletedAccount,
		Invalid,
		Unknown,
		Computer
	}
	public enum WellKnownSidType
	{
		NullSid = 0,
		WorldSid = 1,
		LocalSid = 2,
		CreatorOwnerSid = 3,
		CreatorGroupSid = 4,
		CreatorOwnerServerSid = 5,
		CreatorGroupServerSid = 6,
		NTAuthoritySid = 7,
		DialupSid = 8,
		NetworkSid = 9,
		BatchSid = 10,
		InteractiveSid = 11,
		ServiceSid = 12,
		AnonymousSid = 13,
		ProxySid = 14,
		EnterpriseControllersSid = 15,
		SelfSid = 16,
		AuthenticatedUserSid = 17,
		RestrictedCodeSid = 18,
		TerminalServerSid = 19,
		RemoteLogonIdSid = 20,
		LogonIdsSid = 21,
		LocalSystemSid = 22,
		LocalServiceSid = 23,
		NetworkServiceSid = 24,
		BuiltinDomainSid = 25,
		BuiltinAdministratorsSid = 26,
		BuiltinUsersSid = 27,
		BuiltinGuestsSid = 28,
		BuiltinPowerUsersSid = 29,
		BuiltinAccountOperatorsSid = 30,
		BuiltinSystemOperatorsSid = 31,
		BuiltinPrintOperatorsSid = 32,
		BuiltinBackupOperatorsSid = 33,
		BuiltinReplicatorSid = 34,
		BuiltinPreWindows2000CompatibleAccessSid = 35,
		BuiltinRemoteDesktopUsersSid = 36,
		BuiltinNetworkConfigurationOperatorsSid = 37,
		AccountAdministratorSid = 38,
		AccountGuestSid = 39,
		AccountKrbtgtSid = 40,
		AccountDomainAdminsSid = 41,
		AccountDomainUsersSid = 42,
		AccountDomainGuestsSid = 43,
		AccountComputersSid = 44,
		AccountControllersSid = 45,
		AccountCertAdminsSid = 46,
		AccountSchemaAdminsSid = 47,
		AccountEnterpriseAdminsSid = 48,
		AccountPolicyAdminsSid = 49,
		AccountRasAndIasServersSid = 50,
		NtlmAuthenticationSid = 51,
		DigestAuthenticationSid = 52,
		SChannelAuthenticationSid = 53,
		ThisOrganizationSid = 54,
		OtherOrganizationSid = 55,
		BuiltinIncomingForestTrustBuildersSid = 56,
		BuiltinPerformanceMonitoringUsersSid = 57,
		BuiltinPerformanceLoggingUsersSid = 58,
		BuiltinAuthorizationAccessSid = 59,
		WinBuiltinTerminalServerLicenseServersSid = 60,
		MaxDefined = 60
	}
	public sealed class SecurityIdentifier : IdentityReference, IComparable<SecurityIdentifier>
	{
		internal static readonly long MaxIdentifierAuthority = 281474976710655L;

		internal static readonly byte MaxSubAuthorities = 15;

		public static readonly int MinBinaryLength = 8;

		public static readonly int MaxBinaryLength = 8 + MaxSubAuthorities * 4;

		private IdentifierAuthority _identifierAuthority;

		private int[] _subAuthorities;

		private byte[] _binaryForm;

		private SecurityIdentifier _accountDomainSid;

		private bool _accountDomainSidInitialized;

		private string _sddlForm;

		internal static byte Revision => 1;

		internal byte[] BinaryForm => _binaryForm;

		internal IdentifierAuthority IdentifierAuthority => _identifierAuthority;

		internal int SubAuthorityCount => _subAuthorities.Length;

		public int BinaryLength => _binaryForm.Length;

		public SecurityIdentifier AccountDomainSid
		{
			get
			{
				if (!_accountDomainSidInitialized)
				{
					_accountDomainSid = GetAccountDomainSid();
					_accountDomainSidInitialized = true;
				}
				return _accountDomainSid;
			}
		}

		public override string Value => ((object)this).ToString().ToUpperInvariant();

		private void CreateFromParts(IdentifierAuthority identifierAuthority, int[] subAuthorities)
		{
			//IL_0008: 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_005c: Unknown result type (might be due to invalid IL or missing references)
			if (subAuthorities == null)
			{
				throw new ArgumentNullException("subAuthorities");
			}
			if (subAuthorities.Length > MaxSubAuthorities)
			{
				throw new ArgumentOutOfRangeException("subAuthorities.Length", (object)subAuthorities.Length, System.SR.Format(System.SR.IdentityReference_InvalidNumberOfSubauthorities, MaxSubAuthorities));
			}
			if (identifierAuthority < IdentifierAuthority.NullAuthority || (long)identifierAuthority > MaxIdentifierAuthority)
			{
				throw new ArgumentOutOfRangeException("identifierAuthority", (object)identifierAuthority, System.SR.IdentityReference_IdentifierAuthorityTooLarge);
			}
			_identifierAuthority = identifierAuthority;
			_subAuthorities = new int[subAuthorities.Length];
			((System.Array)subAuthorities).CopyTo((System.Array)_subAuthorities, 0);
			_binaryForm = new byte[8 + 4 * SubAuthorityCount];
			_binaryForm[0] = Revision;
			_binaryForm[1] = (byte)SubAuthorityCount;
			for (byte b = 0; b < 6; b++)
			{
				_binaryForm[2 + b] = (byte)(((ulong)_identifierAuthority >> (5 - b) * 8) & 0xFF);
			}
			for (byte b = 0; b < SubAuthorityCount; b++)
			{
				for (byte b2 = 0; b2 < 4; b2++)
				{
					_binaryForm[8 + 4 * b + b2] = (byte)((ulong)_subAuthorities[b] >> b2 * 8);
				}
			}
		}

		private void CreateFromBinaryForm(byte[] binaryForm, int offset)
		{
			//IL_0008: 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_003e: 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)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			if (binaryForm == null)
			{
				throw new ArgumentNullException("binaryForm");
			}
			if (offset < 0)
			{
				throw new ArgumentOutOfRangeException("offset", (object)offset, System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if (binaryForm.Length - offset < MinBinaryLength)
			{
				throw new ArgumentOutOfRangeException("binaryForm", System.SR.ArgumentOutOfRange_ArrayTooSmall);
			}
			if (binaryForm[offset] != Revision)
			{
				throw new ArgumentException(System.SR.IdentityReference_InvalidSidRevision, "binaryForm");
			}
			if (binaryForm[offset + 1] > MaxSubAuthorities)
			{
				throw new ArgumentException(System.SR.Format(System.SR.IdentityReference_InvalidNumberOfSubauthorities, MaxSubAuthorities), "binaryForm");
			}
			int num = 8 + 4 * binaryForm[offset + 1];
			if (binaryForm.Length - offset < num)
			{
				throw new ArgumentException(System.SR.ArgumentOutOfRange_ArrayTooSmall, "binaryForm");
			}
			IdentifierAuthority identifierAuthority = (IdentifierAuthority)(((ulong)binaryForm[offset + 2] << 40) + ((ulong)binaryForm[offset + 3] << 32) + ((ulong)binaryForm[offset + 4] << 24) + ((ulong)binaryForm[offset + 5] << 16) + ((ulong)binaryForm[offset + 6] << 8) + binaryForm[offset + 7]);
			int[] array = new int[binaryForm[offset + 1]];
			for (byte b = 0; b < binaryForm[offset + 1]; b++)
			{
				array[b] = binaryForm[offset + 8 + 4 * b] + (binaryForm[offset + 8 + 4 * b + 1] << 8) + (binaryForm[offset + 8 + 4 * b + 2] << 16) + (binaryForm[offset + 8 + 4 * b + 3] << 24);
			}
			CreateFromParts(identifierAuthority, array);
		}

		public SecurityIdentifier(string sddlForm)
		{
			//IL_000e: 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_0039: Unknown result type (might be due to invalid IL or missing references)
			if (sddlForm == null)
			{
				throw new ArgumentNullException("sddlForm");
			}
			byte[] resultSid;
			int num = Win32.CreateSidFromString(sddlForm, out resultSid);
			switch (num)
			{
			case 1337:
				throw new ArgumentException(System.SR.Argument_InvalidValue, "sddlForm");
			case 8:
				throw new OutOfMemoryException();
			default:
				throw new Win32Exception(num);
			case 0:
				CreateFromBinaryForm(resultSid, 0);
				break;
			}
		}

		public SecurityIdentifier(byte[] binaryForm, int offset)
		{
			CreateFromBinaryForm(binaryForm, offset);
		}

		public SecurityIdentifier(System.IntPtr binaryForm)
			: this(binaryForm, noDemand: true)
		{
		}

		internal SecurityIdentifier(System.IntPtr binaryForm, bool noDemand)
			: this(Win32.ConvertIntPtrSidToByteArraySid(binaryForm), 0)
		{
		}

		public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier domainSid)
		{
			//IL_0015: 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)
			//IL_00d0: 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_0070: 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_00ab: Unknown result type (might be due to invalid IL or missing references)
			switch (sidType)
			{
			case WellKnownSidType.LogonIdsSid:
				throw new ArgumentException(System.SR.IdentityReference_CannotCreateLogonIdsSid, "sidType");
			default:
				throw new ArgumentException(System.SR.Argument_InvalidValue, "sidType");
			case WellKnownSidType.AccountAdministratorSid:
			case WellKnownSidType.AccountGuestSid:
			case WellKnownSidType.AccountKrbtgtSid:
			case WellKnownSidType.AccountDomainAdminsSid:
			case WellKnownSidType.AccountDomainUsersSid:
			case WellKnownSidType.AccountDomainGuestsSid:
			case WellKnownSidType.AccountComputersSid:
			case WellKnownSidType.AccountControllersSid:
			case WellKnownSidType.AccountCertAdminsSid:
			case WellKnownSidType.AccountSchemaAdminsSid:
			case WellKnownSidType.AccountEnterpriseAdminsSid:
			case WellKnownSidType.AccountPolicyAdminsSid:
			case WellKnownSidType.AccountRasAndIasServersSid:
			{
				if (domainSid == null)
				{
					throw new ArgumentNullException("domainSid", System.SR.Format(System.SR.IdentityReference_DomainSidRequired, sidType));
				}
				SecurityIdentifier resultSid;
				int windowsAccountDomainSid = Win32.GetWindowsAccountDomainSid(domainSid, out resultSid);
				switch (windowsAccountDomainSid)
				{
				case 122:
					throw new OutOfMemoryException();
				case 1257:
					throw new ArgumentException(System.SR.IdentityReference_NotAWindowsDomain, "domainSid");
				default:
					throw new Win32Exception(windowsAccountDomainSid);
				case 0:
					break;
				}
				if (resultSid != domainSid)
				{
					throw new ArgumentException(System.SR.IdentityReference_NotAWindowsDomain, "domainSid");
				}
				break;
			}
			case WellKnownSidType.NullSid:
			case WellKnownSidType.WorldSid:
			case WellKnownSidType.LocalSid:
			case WellKnownSidType.CreatorOwnerSid:
			case WellKnownSidType.CreatorGroupSid:
			case WellKnownSidType.CreatorOwnerServerSid:
			case WellKnownSidType.CreatorGroupServerSid:
			case WellKnownSidType.NTAuthoritySid:
			case WellKnownSidType.DialupSid:
			case WellKnownSidType.NetworkSid:
			case WellKnownSidType.BatchSid:
			case WellKnownSidType.InteractiveSid:
			case WellKnownSidType.ServiceSid:
			case WellKnownSidType.AnonymousSid:
			case WellKnownSidType.ProxySid:
			case WellKnownSidType.EnterpriseControllersSid:
			case WellKnownSidType.SelfSid:
			case WellKnownSidType.AuthenticatedUserSid:
			case WellKnownSidType.RestrictedCodeSid:
			case WellKnownSidType.TerminalServerSid:
			case WellKnownSidType.RemoteLogonIdSid:
			case WellKnownSidType.LocalSystemSid:
			case WellKnownSidType.LocalServiceSid:
			case WellKnownSidType.NetworkServiceSid:
			case WellKnownSidType.BuiltinDomainSid:
			case WellKnownSidType.BuiltinAdministratorsSid:
			case WellKnownSidType.BuiltinUsersSid:
			case WellKnownSidType.BuiltinGuestsSid:
			case WellKnownSidType.BuiltinPowerUsersSid:
			case WellKnownSidType.BuiltinAccountOperatorsSid:
			case WellKnownSidType.BuiltinSystemOperatorsSid:
			case WellKnownSidType.BuiltinPrintOperatorsSid:
			case WellKnownSidType.BuiltinBackupOperatorsSid:
			case WellKnownSidType.BuiltinReplicatorSid:
			case WellKnownSidType.BuiltinPreWindows2000CompatibleAccessSid:
			case WellKnownSidType.BuiltinRemoteDesktopUsersSid:
			case WellKnownSidType.BuiltinNetworkConfigurationOperatorsSid:
			case WellKnownSidType.NtlmAuthenticationSid:
			case WellKnownSidType.DigestAuthenticationSid:
			case WellKnownSidType.SChannelAuthenticationSid:
			case WellKnownSidType.ThisOrganizationSid:
			case WellKnownSidType.OtherOrganizationSid:
			case WellKnownSidType.BuiltinIncomingForestTrustBuildersSid:
			case WellKnownSidType.BuiltinPerformanceMonitoringUsersSid:
			case WellKnownSidType.BuiltinPerformanceLoggingUsersSid:
			case WellKnownSidType.BuiltinAuthorizationAccessSid:
			case WellKnownSidType.WinBuiltinTerminalServerLicenseServersSid:
				break;
			}
			byte[] resultSid2;
			int num = Win32.CreateWellKnownSid(sidType, domainSid, out resultSid2);
			switch (num)
			{
			case 87:
				throw new ArgumentException(((System.Exception)(object)new Win32Exception(num)).Message, "sidType/domainSid");
			default:
				throw new Win32Exception(num);
			case 0:
				CreateFromBinaryForm(resultSid2, 0);
				break;
			}
		}

		internal SecurityIdentifier(SecurityIdentifier domainSid, uint rid)
		{
			int[] array = new int[domainSid.SubAuthorityCount + 1];
			int i;
			for (i = 0; i < domainSid.SubAuthorityCount; i++)
			{
				array[i] = domainSid.GetSubAuthority(i);
			}
			array[i] = (int)rid;
			CreateFromParts(domainSid.IdentifierAuthority, array);
		}

		internal SecurityIdentifier(IdentifierAuthority identifierAuthority, int[] subAuthorities)
		{
			CreateFromParts(identifierAuthority, subAuthorities);
		}

		public override bool Equals(object o)
		{
			return this == o as SecurityIdentifier;
		}

		public bool Equals(SecurityIdentifier sid)
		{
			return this == sid;
		}

		public override int GetHashCode()
		{
			int num = ((long)IdentifierAuthority).GetHashCode();
			for (int i = 0; i < SubAuthorityCount; i++)
			{
				num ^= GetSubAuthority(i);
			}
			return num;
		}

		public override string ToString()
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Expected O, but got Unknown
			if (_sddlForm == null)
			{
				StringBuilder val = new StringBuilder();
				val.AppendFormat("S-1-{0}", (object)(long)_identifierAuthority);
				for (int i = 0; i < SubAuthorityCount; i++)
				{
					val.AppendFormat("-{0}", (object)(uint)_subAuthorities[i]);
				}
				_sddlForm = ((object)val).ToString();
			}
			return _sddlForm;
		}

		internal static bool IsValidTargetTypeStatic(System.Type targetType)
		{
			if (targetType == typeof(NTAccount))
			{
				return true;
			}
			if (targetType == typeof(SecurityIdentifier))
			{
				return true;
			}
			return false;
		}

		public override bool IsValidTargetType(System.Type targetType)
		{
			return IsValidTargetTypeStatic(targetType);
		}

		internal SecurityIdentifier GetAccountDomainSid()
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			SecurityIdentifier resultSid;
			int windowsAccountDomainSid = Win32.GetWindowsAccountDomainSid(this, out resultSid);
			return windowsAccountDomainSid switch
			{
				122 => throw new OutOfMemoryException(), 
				1257 => null, 
				0 => resultSid, 
				_ => throw new Win32Exception(windowsAccountDomainSid), 
			};
		}

		public bool IsAccountSid()
		{
			if (!_accountDomainSidInitialized)
			{
				_accountDomainSid = GetAccountDomainSid();
				_accountDomainSidInitialized = true;
			}
			if (_accountDomainSid == null)
			{
				return false;
			}
			return true;
		}

		public override IdentityReference Translate(System.Type targetType)
		{
			//IL_0008: 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)
			if (targetType == null)
			{
				throw new ArgumentNullException("targetType");
			}
			if (targetType == typeof(SecurityIdentifier))
			{
				return this;
			}
			if (targetType == typeof(NTAccount))
			{
				IdentityReferenceCollection identityReferenceCollection = new IdentityReferenceCollection(1);
				identityReferenceCollection.Add(this);
				IdentityReferenceCollection identityReferenceCollection2 = Translate(identityReferenceCollection, targetType, forceSuccess: true);
				return identityReferenceCollection2[0];
			}
			throw new ArgumentException(System.SR.IdentityReference_MustBeIdentityReference, "targetType");
		}

		public static bool operator ==(SecurityIdentifier left, SecurityIdentifier right)
		{
			if ((object)left == right)
			{
				return true;
			}
			if ((object)left == null || (object)right == null)
			{
				return false;
			}
			return left.CompareTo(right) == 0;
		}

		public static bool operator !=(SecurityIdentifier left, SecurityIdentifier right)
		{
			return !(left == right);
		}

		public int CompareTo(SecurityIdentifier sid)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (sid == null)
			{
				throw new ArgumentNullException("sid");
			}
			if (IdentifierAuthority < sid.IdentifierAuthority)
			{
				return -1;
			}
			if (IdentifierAuthority > sid.IdentifierAuthority)
			{
				return 1;
			}
			if (SubAuthorityCount < sid.SubAuthorityCount)
			{
				return -1;
			}
			if (SubAuthorityCount > sid.SubAuthorityCount)
			{
				return 1;
			}
			for (int i = 0; i < SubAuthorityCount; i++)
			{
				int num = GetSubAuthority(i) - sid.GetSubAuthority(i);
				if (num != 0)
				{
					return num;
				}
			}
			return 0;
		}

		internal int GetSubAuthority(int index)
		{
			return _subAuthorities[index];
		}

		public bool IsWellKnown(WellKnownSidType type)
		{
			return Win32.IsWellKnownSid(this, type);
		}

		public void GetBinaryForm(byte[] binaryForm, int offset)
		{
			((System.Array)_binaryForm).CopyTo((System.Array)binaryForm, offset);
		}

		public bool IsEqualDomainSid(SecurityIdentifier sid)
		{
			return Win32.IsEqualDomainSid(this, sid);
		}

		private static IdentityReferenceCollection TranslateToNTAccounts(IdentityReferenceCollection sourceSids, out bool someFailed)
		{
			//IL_0008: 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_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: 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)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			if (sourceSids == null)
			{
				throw new ArgumentNullException("sourceSids");
			}
			if (sourceSids.Count == 0)
			{
				throw new ArgumentException(System.SR.Arg_EmptyCollection, "sourceSids");
			}
			System.IntPtr[] array = new System.IntPtr[sourceSids.Count];
			GCHandle[] array2 = (GCHandle[])(object)new GCHandle[sourceSids.Count];
			SafeLsaPolicyHandle safeLsaPolicyHandle = SafeLsaPolicyHandle.InvalidHandle;
			SafeLsaMemoryHandle referencedDomains = SafeLsaMemoryHandle.InvalidHandle;
			SafeLsaMemoryHandle names = SafeLsaMemoryHandle.InvalidHandle;
			try
			{
				int num = 0;
				System.Collections.Generic.IEnumerator<IdentityReference> enumerator = sourceSids.GetEnumerator();
				try
				{
					while (((System.Collections.IEnumerator)enumerator).MoveNext())
					{
						IdentityReference current = enumerator.Current;
						SecurityIdentifier securityIdentifier = current as SecurityIdentifier;
						if (securityIdentifier == null)
						{
							throw new ArgumentException(System.SR.Argument_ImproperType, "sourceSids");
						}
						array2[num] = GCHandle.Alloc((object)securityIdentifier.BinaryForm, (GCHandleType)3);
						array[num] = ((GCHandle)(ref array2[num])).AddrOfPinnedObject();
						num++;
					}
				}
				finally
				{
					((System.IDisposable)enumerator)?.Dispose();
				}
				safeLsaPolicyHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);
				someFailed = false;
				uint num2 = global::Interop.mincore.LsaLookupSids(safeLsaPolicyHandle, sourceSids.Count, array, ref referencedDomains, ref names);
				switch (num2)
				{
				case 3221225495u:
				case 3221225626u:
					throw new OutOfMemoryException();
				case 3221225506u:
					throw new UnauthorizedAccessException();
				case 3221225587u:
				case 263u:
					someFailed = true;
					break;
				default:
				{
					int error = global::Interop.mincore.RtlNtStatusToDosError((int)num2);
					throw new Win32Exception(error);
				}
				case 0u:
					break;
				}
				((SafeBuffer)names).Initialize((uint)sourceSids.Count, (uint)Marshal.SizeOf<global::Interop.LSA_TRANSLATED_NAME>());
				Win32.InitializeReferencedDomainsPointer(referencedDomains);
				IdentityReferenceCollection identityReferenceCollection = new IdentityReferenceCollection(sourceSids.Count);
				if (num2 == 0 || num2 == 263)
				{
					global::Interop.LSA_REFERENCED_DOMAIN_LIST lSA_REFERENCED_DOMAIN_LIST = ((SafeBuffer)referencedDomains).Read<global::Interop.LSA_REFERENCED_DOMAIN_LIST>(0uL);
					string[] array3 = new string[lSA_REFERENCED_DOMAIN_LIST.Entries];
					for (int i = 0; i < lSA_REFERENCED_DOMAIN_LIST.Entries; i++)
					{
						global::Interop.LSA_TRUST_INFORMATION lSA_TRUST_INFORMATION = Marshal.PtrToStructure<global::Interop.LSA_TRUST_INFORMATION>(new System.IntPtr((long)lSA_REFERENCED_DOMAIN_LIST.Domains + i * Marshal.SizeOf<global::Interop.LSA_TRUST_INFORMATION>()));
						array3[i] = Marshal.PtrToStringUni(lSA_TRUST_INFORMATION.Name.Buffer, lSA_TRUST_INFORMATION.Name.Length / 2);
					}
					global::Interop.LSA_TRANSLATED_NAME[] array4 = new global::Interop.LSA_TRANSLATED_NAME[sourceSids.Count];
					((SafeBuffer)names).ReadArray<global::Interop.LSA_TRANSLATED_NAME>(0uL, array4, 0, array4.Length);
					for (int j = 0; j < sourceSids.Count; j++)
					{
						global::Interop.LSA_TRANSLATED_NAME lSA_TRANSLATED_NAME = array4[j];
						switch ((SidNameUse)lSA_TRANSLATED_NAME.Use)
						{
						case SidNameUse.User:
						case SidNameUse.Group:
						case SidNameUse.Alias:
						case SidNameUse.WellKnownGroup:
						case SidNameUse.Computer:
						{
							string accountName = Marshal.PtrToStringUni(lSA_TRANSLATED_NAME.Name.Buffer, lSA_TRANSLATED_NAME.Name.Length / 2);
							string domainName = array3[lSA_TRANSLATED_NAME.DomainIndex];
							identityReferenceCollection.Add(new NTAccount(domainName, accountName));
							break;
						}
						default:
							someFailed = true;
							identityReferenceCollection.Add(sourceSids[j]);
							break;
						}
					}
				}
				else
				{
					for (int k = 0; k < sourceSids.Count; k++)
					{
						identityReferenceCollection.Add(sourceSids[k]);
					}
				}
				return identityReferenceCollection;
			}
			finally
			{
				for (int l = 0; l < sourceSids.Count; l++)
				{
					if (((GCHandle)(ref array2[l])).IsAllocated)
					{
						((GCHandle)(ref array2[l])).Free();
					}
				}
				((SafeHandle)safeLsaPolicyHandle).Dispose();
				((SafeHandle)referencedDomains).Dispose();
				((SafeHandle)names).Dispose();
			}
		}

		internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceSids, System.Type targetType, bool forceSuccess)
		{
			bool someFailed = false;
			IdentityReferenceCollection identityReferenceCollection = Translate(sourceSids, targetType, out someFailed);
			if (forceSuccess && someFailed)
			{
				IdentityReferenceCollection identityReferenceCollection2 = new IdentityReferenceCollection();
				System.Collections.Generic.IEnumerator<IdentityReference> enumerator = identityReferenceCollection.GetEnumerator();
				try
				{
					while (((System.Collections.IEnumerator)enumerator).MoveNext())
					{
						IdentityReference current = enumerator.Current;
						if (((object)current).GetType() != targetType)
						{
							identityReferenceCollection2.Add(current);
						}
					}
				}
				finally
				{
					((System.IDisposable)enumerator)?.Dispose();
				}
				throw new IdentityNotMappedException(System.SR.IdentityReference_IdentityNotMapped, identityReferenceCollection2);
			}
			return identityReferenceCollection;
		}

		internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceSids, System.Type targetType, out bool someFailed)
		{
			//IL_0008: 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)
			if (sourceSids == null)
			{
				throw new ArgumentNullException("sourceSids");
			}
			if (targetType == typeof(NTAccount))
			{
				return TranslateToNTAccounts(sourceSids, out someFailed);
			}
			throw new ArgumentException(System.SR.IdentityReference_MustBeIdentityReference, "targetType");
		}
	}
	[Flags]
	public enum TokenAccessLevels
	{
		AssignPrimary = 1,
		Duplicate = 2,
		Impersonate = 4,
		Query = 8,
		QuerySource = 0x10,
		AdjustPrivileges = 0x20,
		AdjustGroups = 0x40,
		AdjustDefault = 0x80,
		AdjustSessionId = 0x100,
		Read = 0x20008,
		Write = 0x200E0,
		AllAccess = 0xF01FF,
		MaximumAllowed = 0x2000000
	}
	[Flags]
	internal enum PolicyRights
	{
		POLICY_VIEW_LOCAL_INFORMATION = 1,
		POLICY_VIEW_AUDIT_INFORMATION = 2,
		POLICY_GET_PRIVATE_INFORMATION = 4,
		POLICY_TRUST_ADMIN = 8,
		POLICY_CREATE_ACCOUNT = 0x10,
		POLICY_CREATE_SECRET = 0x20,
		POLICY_CREATE_PRIVILEGE = 0x40,
		POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x80,
		POLICY_SET_AUDIT_REQUIREMENTS = 0x100,
		POLICY_AUDIT_LOG_ADMIN = 0x200,
		POLICY_SERVER_ADMIN = 0x400,
		POLICY_LOOKUP_NAMES = 0x800,
		POLICY_NOTIFICATION = 0x1000
	}
	internal static class Win32
	{
		internal const int FALSE = 0;

		internal static SafeLsaPolicyHandle LsaOpenPolicy(string systemName, PolicyRights rights)
		{
			//IL_005d: 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)
			global::Interop.LSA_OBJECT_ATTRIBUTES attributes = default(global::Interop.LSA_OBJECT_ATTRIBUTES);
			attributes.Length = Marshal.SizeOf<global::Interop.LSA_OBJECT_ATTRIBUTES>();
			attributes.RootDirectory = System.IntPtr.Zero;
			attributes.ObjectName = System.IntPtr.Zero;
			attributes.Attributes = 0;
			attributes.SecurityDescriptor = System.IntPtr.Zero;
			attributes.SecurityQualityOfService = System.IntPtr.Zero;
			uint num;
			if ((num = global::Interop.mincore.LsaOpenPolicy(systemName, ref attributes, (int)rights, out var handle)) == 0)
			{
				return handle;
			}
			switch (num)
			{
			case 3221225506u:
				throw new UnauthorizedAccessException();
			case 3221225495u:
			case 3221225626u:
				throw new OutOfMemoryException();
			default:
			{
				int error = global::Interop.mincore.RtlNtStatusToDosError((int)num);
				throw new Win32Exception(error);
			}
			}
		}

		internal static byte[] ConvertIntPtrSidToByteArraySid(System.IntPtr binaryForm)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			byte b = Marshal.ReadByte(binaryForm, 0);
			if (b != SecurityIdentifier.Revision)
			{
				throw new ArgumentException(System.SR.IdentityReference_InvalidSidRevision, "binaryForm");
			}
			byte b2 = Marshal.ReadByte(binaryForm, 1);
			if (b2 < 0 || b2 > SecurityIdentifier.MaxSubAuthorities)
			{
				throw new ArgumentException(System.SR.Format(System.SR.IdentityReference_InvalidNumberOfSubauthorities, SecurityIdentifier.MaxSubAuthorities), "binaryForm");
			}
			int num = 8 + b2 * 4;
			byte[] array = new byte[num];
			Marshal.Copy(binaryForm, array, 0, num);
			return array;
		}

		internal static int CreateSidFromString(string stringSid, out byte[] resultSid)
		{
			System.IntPtr ByteArray = System.IntPtr.Zero;
			int lastWin32Error;
			try
			{
				if (global::Interop.mincore.ConvertStringSidToSid(stringSid, out ByteArray) != 0)
				{
					resultSid = ConvertIntPtrSidToByteArraySid(ByteArray);
					goto IL_002a;
				}
				lastWin32Error = Marshal.GetLastWin32Error();
			}
			finally
			{
				global::Interop.mincore_obsolete.LocalFree(ByteArray);
			}
			resultSid = null;
			return lastWin32Error;
			IL_002a:
			return 0;
		}

		internal static int CreateWellKnownSid(WellKnownSidType sidType, SecurityIdentifier domainSid, out byte[] resultSid)
		{
			uint resultSidLength = (uint)SecurityIdentifier.MaxBinaryLength;
			resultSid = new byte[resultSidLength];
			if (global::Interop.mincore.CreateWellKnownSid((int)sidType, (domainSid == null) ? null : domainSid.BinaryForm, resultSid, ref resultSidLength) != 0)
			{
				return 0;
			}
			resultSid = null;
			return Marshal.GetLastWin32Error();
		}

		internal static bool IsEqualDomainSid(SecurityIdentifier sid1, SecurityIdentifier sid2)
		{
			if (sid1 == null || sid2 == null)
			{
				return false;
			}
			byte[] array = new byte[sid1.BinaryLength];
			sid1.GetBinaryForm(array, 0);
			byte[] array2 = new byte[sid2.BinaryLength];
			sid2.GetBinaryForm(array2, 0);
			if (global::Interop.mincore.IsEqualDomainSid(array, array2, out var result) != 0)
			{
				return result;
			}
			return false;
		}

		internal unsafe static void InitializeReferencedDomainsPointer(SafeLsaMemoryHandle referencedDomains)
		{
			((SafeBuffer)referencedDomains).Initialize((ulong)(uint)Marshal.SizeOf<global::Interop.LSA_REFERENCED_DOMAIN_LIST>());
			global::Interop.LSA_REFERENCED_DOMAIN_LIST lSA_REFERENCED_DOMAIN_LIST = ((SafeBuffer)referencedDomains).Read<global::Interop.LSA_REFERENCED_DOMAIN_LIST>(0uL);
			byte* ptr = null;
			try
			{
				((SafeBuffer)referencedDomains).AcquirePointer(ref ptr);
				if (lSA_REFERENCED_DOMAIN_LIST.Domains != System.IntPtr.Zero)
				{
					global::Interop.LSA_TRUST_INFORMATION* ptr2 = (global::Interop.LSA_TRUST_INFORMATION*)(void*)lSA_REFERENCED_DOMAIN_LIST.Domains;
					ptr2 += lSA_REFERENCED_DOMAIN_LIST.Entries;
					long num = (byte*)ptr2 - ptr;
					((SafeBuffer)referencedDomains).Initialize((ulong)num);
				}
			}
			finally
			{
				if (ptr != null)
				{
					((SafeBuffer)referencedDomains).ReleasePointer();
				}
			}
		}

		internal static int GetWindowsAccountDomainSid(SecurityIdentifier sid, out SecurityIdentifier resultSid)
		{
			byte[] array = new byte[sid.BinaryLength];
			sid.GetBinaryForm(array, 0);
			uint resultSidLength = (uint)SecurityIdentifier.MaxBinaryLength;
			byte[] array2 = new byte[resultSidLength];
			if (global::Interop.mincore.GetWindowsAccountDomainSid(array, array2, ref resultSidLength) != 0)
			{
				resultSid = new SecurityIdentifier(array2, 0);
				return 0;
			}
			resultSid = null;
			return Marshal.GetLastWin32Error();
		}

		internal static bool IsWellKnownSid(SecurityIdentifier sid, WellKnownSidType type)
		{
			byte[] array = new byte[sid.BinaryLength];
			sid.GetBinaryForm(array, 0);
			if (global::Interop.mincore.IsWellKnownSid(array, (int)type) == 0)
			{
				return false;
			}
			return true;
		}
	}
	public class WindowsIdentity : ClaimsIdentity, System.IDisposable
	{
		[CompilerGenerated]
		private sealed class <get_Claims>d__78 : System.Collections.Generic.IEnumerable<Claim>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<Claim>, System.Collections.IEnumerator, System.IDisposable
		{
			private int <>1__state;

			private Claim <>2__current;

			private int <>l__initialThreadId;

			public WindowsIdentity <>4__this;

			private System.Collections.Generic.IEnumerator<Claim> <>7__wrap1;

			private Enumerator<Claim> <>7__wrap2;

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

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

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

			[DebuggerHidden]
			void System.IDisposable.Dispose()
			{
				switch (<>1__state)
				{
				case -3:
				case 1:
					try
					{
						break;
					}
					finally
					{
						<>m__Finally1();
					}
				case -4:
				case 2:
					try
					{
						break;
					}
					finally
					{
						<>m__Finally2();
					}
				case -5:
				case 3:
					try
					{
						break;
					}
					finally
					{
						<>m__Finally3();
					}
				case -2:
				case -1:
				case 0:
					break;
				}
			}

			private bool MoveNext()
			{
				//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
				//IL_010a: Unknown result type (might be due to invalid IL or missing references)
				//IL_011c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0121: Unknown result type (might be due to invalid IL or missing references)
				//IL_0171: Unknown result type (might be due to invalid IL or missing references)
				try
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						if (!<>4__this._claimsInitialized)
						{
							<>4__this.InitializeClaims();
						}
						<>7__wrap1 = ((ClaimsIdentity)<>4__this).Claims.GetEnumerator();
						<>1__state = -3;
						goto IL_008e;
					case 1:
						<>1__state = -3;
						goto IL_008e;
					case 2:
						<>1__state = -4;
						goto IL_00f1;
					case 3:
						{
							<>1__state = -5;
							break;
						}
						IL_00f1:
						if (<>7__wrap2.MoveNext())
						{
							Claim current = <>7__wrap2.Current;
							<>2__current = current;
							<>1__state = 2;
							return true;
						}
						<>m__Finally2();
						<>7__wrap2 = default(Enumerator<Claim>);
						<>7__wrap2 = <>4__this._deviceClaims.GetEnumerator();
						<>1__state = -5;
						break;
						IL_008e:
						if (((System.Collections.IEnumerator)<>7__wrap1).MoveNext())
						{
							Claim current2 = <>7__wrap1.Current;
							<>2__current = current2;
							<>1__state = 1;
							return true;
						}
						<>m__Finally1();
						<>7__wrap1 = null;
						<>7__wrap2 = <>4__this._userClaims.GetEnumerator();
						<>1__state = -4;
						goto IL_00f1;
					}
					if (<>7__wrap2.MoveNext())
					{
						Claim current3 = <>7__wrap2.Current;
						<>2__current = current3;
						<>1__state = 3;
						return true;
					}
					<>m__Finally3();
					<>7__wrap2 = default(Enumerator<Claim>);
					return false;
				}
				catch
				{
					//try-fault
					((System.IDisposable)this).Dispose();
					throw;
				}
			}

			bool 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)
				{
					((System.IDisposable)<>7__wrap1).Dispose();
				}
			}

			private void <>m__Finally2()
			{
				<>1__state = -1;
				((System.IDisposable)<>7__wrap2).Dispose();
			}

			private void <>m__Finally3()
			{
				<>1__state = -1;
				((System.IDisposable)<>7__wrap2).Dispose();
			}

			[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<Claim> System.Collections.Generic.IEnumerable<Claim>.GetEnumerator()
			{
				<get_Claims>d__78 result;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					result = this;
				}
				else
				{
					result = new <get_Claims>d__78(0)
					{
						<>4__this = <>4__this
					};
				}
				return result;
			}

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

		private string _name;

		private SecurityIdentifier _owner;

		private SecurityIdentifier _user;

		private IdentityReferenceCollection _groups;

		private SafeAccessTokenHandle _safeTokenHandle = SafeAccessTokenHandle.InvalidHandle;

		private string _authType;

		private int _isAuthenticated = -1;

		private volatile TokenImpersonationLevel _impersonationLevel;

		private volatile bool _impersonationLevelInitialized;

		public new const string DefaultIssuer = "AD AUTHORITY";

		private string _issuerName = "AD AUTHORITY";

		private object _claimsIntiailizedLock = new object();

		private volatile bool _claimsInitialized;

		private List<Claim> _deviceClaims;

		private List<Claim> _userClaims;

		private static AsyncLocal<SafeAccessTokenHandle> s_currentImpersonatedToken = new AsyncLocal<SafeAccessTokenHandle>((Action<AsyncLocalValueChangedArgs<SafeAccessTokenHandle>>)CurrentImpersonatedTokenChanged);

		public sealed override string AuthenticationType
		{
			get
			{
				if (((SafeHandle)_safeTokenHandle).IsInvalid)
				{
					return string.Empty;
				}
				if (_authType == null)
				{
					global::Interop.LUID LogonId = GetLogonAuthId(_safeTokenHandle);
					if (LogonId.LowPart == 998)
					{
						return string.Empty;
					}
					SafeLsaReturnBufferHandle ppLogonSessionData = SafeLsaReturnBufferHandle.InvalidHandle;
					try
					{
						int num = global::Interop.mincore.LsaGetLogonSessionData(ref LogonId, ref ppLogonSessionData);
						if (num < 0)
						{
							throw GetExceptionFromNtStatus(num);
						}
						((SafeBuffer)ppLogonSessionData).Initialize((ulong)(uint)Marshal.SizeOf<global::Interop.SECURITY_LOGON_SESSION_DATA>());
						return Marshal.PtrToStringUni(((SafeBuffer)ppLogonSessionData).Read<global::Interop.SECURITY_LOGON_SESSION_DATA>(0uL).AuthenticationPackage.Buffer);
					}
					finally
					{
						if (!((SafeHandle)ppLogonSessionData).IsInvalid)
						{
							((SafeHandle)ppLogonSessionData).Dispose();
						}
					}
				}
				return _authType;
			}
		}

		public TokenImpersonationLevel ImpersonationLevel
		{
			get
			{
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				//IL_000b: 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_0039: 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_003b: 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 (!_impersonationLevelInitialized)
				{
					TokenImpersonationLevel val = (TokenImpersonationLevel)0;
					if (((SafeHandle)_safeTokenHandle).IsInvalid)
					{
						val = (TokenImpersonationLevel)1;
					}
					else
					{
						TokenType tokenInformation = (TokenType)GetTokenInformation<int>(TokenInformationClass.TokenType);
						if (tokenInformation == TokenType.TokenPrimary)
						{
							val = (TokenImpersonationLevel)0;
						}
						else
						{
							int tokenInformation2 = GetTokenInformation<int>(TokenInformationClass.TokenImpersonationLevel);
							val = (TokenImpersonationLevel)(tokenInformation2 + 1);
						}
					}
					_impersonationLevel = val;
					_impersonationLevelInitialized = true;
				}
				return _impersonationLevel;
			}
		}

		public override bool IsAuthenticated
		{
			get
			{
				if (_isAuthenticated == -1)
				{
					_isAuthenticated = (CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[1] { 11 })) ? 1 : 0);
				}
				return _isAuthenticated == 1;
			}
		}

		public virtual bool IsGuest
		{
			get
			{
				if (((SafeHandle)_safeTokenHandle).IsInvalid)
				{
					return false;
				}
				return CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[2] { 32, 546 }));
			}
		}

		public virtual bool IsSystem
		{
			get
			{
				if (((SafeHandle)_safeTokenHandle).IsInvalid)
				{
					return false;
				}
				SecurityIdentifier securityIdentifier = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[1] { 18 });
				return User == securityIdentifier;
			}
		}

		public virtual bool IsAnonymous
		{
			get
			{
				if (((SafeHandle)_safeTokenHandle).IsInvalid)
				{
					return true;
				}
				SecurityIdentifier securityIdentifier = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[1] { 7 });
				return User == securityIdentifier;
			}
		}

		public override string Name => GetName();

		public SecurityIdentifier Owner
		{
			get
			{
				if (((SafeHandle)_safeTokenHandle).IsInvalid)
				{
					return null;
				}
				if (_owner == null)
				{
					using SafeLocalAllocHandle safeLocalAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenOwner);
					_owner = new SecurityIdentifier(((SafeBuffer)safeLocalAllocHandle).Read<System.IntPtr>(0uL), noDemand: true);
				}
				return _owner;
			}
		}

		public SecurityIdentifier User
		{
			get
			{
				if (((SafeHandle)_safeTokenHandle).IsInvalid)
				{
					return null;
				}
				if (_user == null)
				{
					using SafeLocalAllocHandle safeLocalAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenUser);
					_user = new SecurityIdentifier(((SafeBuffer)safeLocalAllocHandle).Read<System.IntPtr>(0uL), noDemand: true);
				}
				return _user;
			}
		}

		public IdentityReferenceCollection Groups
		{
			get
			{
				if (((SafeHandle)_safeTokenHandle).IsInvalid)
				{
					return null;
				}
				if (_groups == null)
				{
					IdentityReferenceCollection identityReferenceCollection = new IdentityReferenceCollection();
					using (SafeLocalAllocHandle safeLocalAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenGroups))
					{
						uint num = ((SafeBuffer)safeLocalAllocHandle).Read<uint>(0uL);
						global::Interop.SID_AND_ATTRIBUTES[] array = new global::Interop.SID_AND_ATTRIBUTES[((SafeBuffer)safeLocalAllocHandle).Read<global::Interop.TOKEN_GROUPS>(0uL).GroupCount];
						((SafeBuffer)safeLocalAllocHandle).ReadArray<global::Interop.SID_AND_ATTRIBUTES>((ulong)(uint)Marshal.OffsetOf<global::Interop.TOKEN_GROUPS>("Groups").ToInt32(), array, 0, array.Length);
						global::Interop.SID_AND_ATTRIBUTES[] array2 = array;
						for (int i = 0; i < array2.Length; i++)
						{
							global::Interop.SID_AND_ATTRIBUTES sID_AND_ATTRIBUTES = array2[i];
							uint num2 = 3221225492u;
							if ((sID_AND_ATTRIBUTES.Attributes & num2) == 4)
							{
								identityReferenceCollection.Add(new SecurityIdentifier(sID_AND_ATTRIBUTES.Sid, noDemand: true));
							}
						}
					}
					Interlocked.CompareExchange<IdentityReferenceCollection>(ref _groups, identityReferenceCollection, (IdentityReferenceCollection)null);
				}
				return _groups;
			}
		}

		public SafeAccessTokenHandle AccessToken => _safeTokenHandle;

		public virtual System.Collections.Generic.IEnumerable<Claim> UserClaims
		{
			get
			{
				InitializeClaims();
				return _userClaims.ToArray();
			}
		}

		public virtual System.Collections.Generic.IEnumerable<Claim> DeviceClaims
		{
			get
			{
				InitializeClaims();
				return _deviceClaims.ToArray();
			}
		}

		public override System.Collections.Generic.IEnumerable<Claim> Claims
		{
			[IteratorStateMachine(typeof(<get_Claims>d__78))]
			get
			{
				if (!_claimsInitialized)
				{
					InitializeClaims();
				}
				System.Collections.Generic.IEnumerator<Claim> enumerator = base.Claims.GetEnumerator();
				try
				{
					while (((System.Collections.IEnumerator)enumerator).MoveNext())
					{
						yield return enumerator.Current;
					}
				}
				finally
				{
					((System.IDisposable)enumerator)?.Dispose();
				}
				Enumerator<Claim> enumerator2 = _userClaims.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						yield return enumerator2.Current;
					}
				}
				finally
				{
					((System.IDisposable)enumerator2).Dispose();
				}
				enumerator2 = _deviceClaims.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						yield return enumerator2.Current;
					}
				}
				finally
				{
					((System.IDisposable)enumerator2).Dispose();
				}
			}
		}

		private WindowsIdentity()
			: base(null, null, null, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid")
		{
		}

		public unsafe WindowsIdentity(string sUserPrincipalName)
			: base(null, null, null, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid")
		{
			//IL_0077: 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_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			SafeLsaHandle safeLsaHandle = ConnectToLsa();
			try
			{
				int authenticationPackage = LookupAuthenticationPackage(safeLsaHandle, "Kerberos");
				byte[] array = new byte[4];
				RuntimeHelpers.InitializeArray((System.Array)array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
				byte[] array2 = array;
				global::Interop.SspiCli.TOKEN_SOURCE SourceContext = default(global::Interop.SspiCli.TOKEN_SOURCE);
				if (!global::Interop.SecurityBase.AllocateLocallyUniqueId(out SourceContext.SourceIdentifier))
				{
					throw new SecurityException(((System.Exception)(object)new Win32Exception()).Message);
				}
				SourceContext.SourceName = new byte[8];
				Buffer.BlockCopy((System.Array)array2, 0, (System.Array)SourceContext.SourceName, 0, array2.Length);
				if (sUserPrincipalName == null)
				{
					throw new ArgumentNullException("s");
				}
				byte[] bytes = Encoding.Unicode.GetBytes(sUserPrincipalName);
				if (bytes.Length > 65535)
				{
					System.Array.Resize<byte>(ref bytes, bytes.Length & 0xFFFF);
				}
				int num = checked(sizeof(global::Interop.SspiCli.KERB_S4U_LOGON) + bytes.Length);
				using SafeLocalAllocHandle safeLocalAllocHandle = global::Interop.mincore_obsolete.LocalAlloc(0, new System.UIntPtr(checked((uint)num)));
				if (((SafeHandle)safeLocalAllocHandle).IsInvalid)
				{
					throw new OutOfMemoryException();
				}
				global::Interop.SspiCli.KERB_S4U_LOGON* ptr = (global::Interop.SspiCli.KERB_S4U_LOGON*)(void*)((SafeHandle)safeLocalAllocHandle).DangerousGetHandle();
				ptr->MessageType = global::Interop.SspiCli.KERB_LOGON_SUBMIT_TYPE.KerbS4ULogon;
				ptr->Flags = global::Interop.SspiCli.KerbS4uLogonFlags.None;
				ptr->ClientUpn.Length = (ptr->ClientUpn.MaximumLength = checked((ushort)bytes.Length));
				System.IntPtr buffer = (System.IntPtr)(void*)(ptr + 1);
				ptr->ClientUpn.Buffer = buffer;
				Marshal.Copy(bytes, 0, ptr->ClientUpn.Buffer, bytes.Length);
				ptr->ClientRealm.Length = (ptr->ClientRealm.MaximumLength = 0);
				ptr->ClientRealm.Buffer = System.IntPtr.Zero;
				ushort num2 = checked((ushort)array2.Length);
				using SafeLocalAllocHandle safeLocalAllocHandle2 = global::Interop.mincore_obsolete.LocalAlloc(0, new System.UIntPtr((uint)num2));
				if (((SafeHandle)safeLocalAllocHandle2).IsInvalid)
				{
					throw new OutOfMemoryException();
				}
				Marshal.Copy(array2, 0, ((SafeHandle)safeLocalAllocHandle2).DangerousGetHandle(), array2.Length);
				global::Interop.SspiCli.LSA_STRING OriginName = new global::Interop.SspiCli.LSA_STRING(((SafeHandle)safeLocalAllocHandle2).DangerousGetHandle(), num2);
				SafeLsaReturnBufferHandle ProfileBuffer;
				int ProfileBufferLength;
				global::Interop.LUID LogonId;
				SafeAccessTokenHandle Token;
				global::Interop.SspiCli.QUOTA_LIMITS Quotas;
				int SubStatus;
				int num3 = global::Interop.SspiCli.LsaLogonUser(safeLsaHandle, ref OriginName, global::Interop.SspiCli.SECURITY_LOGON_TYPE.Network, authenticationPackage, ((SafeHandle)safeLocalAllocHandle).DangerousGetHandle(), num, System.IntPtr.Zero, ref SourceContext, out ProfileBuffer, out ProfileBufferLength, out LogonId, out Token, out Quotas, out SubStatus);
				if (num3 == -1073741714 && SubStatus < 0)
				{
					num3 = SubStatus;
				}
				if (num3 < 0)
				{
					throw GetExceptionFromNtStatus(num3);
				}
				if (SubStatus < 0)
				{
					throw GetExceptionFromNtStatus(SubStatus);
				}
				if (ProfileBuffer != null)
				{
					((SafeHandle)ProfileBuffer).Dispose();
				}
				_safeTokenHandle = Token;
			}
			finally
			{
				((System.IDisposable)(object)safeLsaHandle)?.Dispose();
			}
		}

		private static SafeLsaHandle ConnectToLsa()
		{
			SafeLsaHandle LsaHandle;
			int num = global::Interop.SspiCli.LsaConnectUntrusted(out LsaHandle);
			if (num < 0)
			{
				throw GetExceptionFromNtStatus(num);
			}
			return LsaHandle;
		}

		private unsafe static int LookupAuthenticationPackage(SafeLsaHandle lsaHandle, string packageName)
		{
			byte[] bytes = Encoding.ASCII.GetBytes(packageName);
			int AuthenticationPackage;
			fixed (byte* ptr = bytes)
			{
				global::Interop.SspiCli.LSA_STRING PackageName = new global::Interop.SspiCli.LSA_STRING((System.IntPtr)(void*)ptr, checked((ushort)bytes.Length));
				int num = global::Interop.SspiCli.LsaLookupAuthenticationPackage(lsaHandle, ref PackageName, out AuthenticationPackage);
				if (num < 0)
				{
					throw GetExceptionFromNtStatus(num);
				}
			}
			return AuthenticationPackage;
		}

		public WindowsIdentity(System.IntPtr userToken)
			: this(userToken, null, -1)
		{
		}

		public WindowsIdentity(System.IntPtr userToken, string type)
			: this(userToken, type, -1)
		{
		}

		private WindowsIdentity(System.IntPtr userToken, string authType, int isAuthenticated)
			: base(null, null, null, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid")
		{
			CreateFromToken(userToken);
			_authType = authType;
			_isAuthenticated = isAuthenticated;
		}

		private void CreateFromToken(System.IntPtr userToken)
		{
			//IL_0012: 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_0066: Unknown result type (might be due to invalid IL or missing references)
			if (userToken == System.IntPtr.Zero)
			{
				throw new ArgumentException(System.SR.Argument_TokenZero);
			}
			uint ReturnLength = (uint)Marshal.SizeOf<uint>();
			bool tokenInformation = global::Interop.mincore.GetTokenInformation(userToken, 8u, SafeLocalAllocHandle.InvalidHandle, 0u, out ReturnLength);
			if (Marshal.GetLastWin32Error() == 6)
			{
				throw new ArgumentException(System.SR.Argument_InvalidImpersonationToken);
			}
			if (!global::Interop.mincore.DuplicateHandle(global::Interop.mincore.GetCurrentProcess(), userToken, global::Interop.mincore.GetCurrentProcess(), ref _safeTokenHandle, 0u, bInheritHandle: true, 2u))
			{
				throw new SecurityException(((System.Exception)(object)new Win32Exception()).Message);
			}
		}

		public static WindowsIdentity GetCurrent()
		{
			return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, threadOnly: false);
		}

		public static WindowsIdentity GetCurrent(bool ifImpersonating)
		{
			return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, ifImpersonating);
		}

		public static WindowsIdentity GetCurrent(TokenAccessLevels desiredAccess)
		{
			return GetCurrentInternal(desiredAccess, threadOnly: false);
		}

		public static WindowsIdentity GetAnonymous()
		{
			return new WindowsIdentity();
		}

		private bool CheckNtTokenForSid(SecurityIdentifier sid)
		{
			//IL_0016: 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_001e: 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_0042: 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)
			if (((SafeHandle)_safeTokenHandle).IsInvalid)
			{
				return false;
			}
			SafeAccessTokenHandle phNewToken = SafeAccessTokenHandle.InvalidHandle;
			TokenImpersonationLevel impersonationLevel = ImpersonationLevel;
			bool IsMember = false;
			try
			{
				if ((int)impersonationLevel == 0 && !global::Interop.mincore.DuplicateTokenEx(_safeTokenHandle, 8u, System.IntPtr.Zero, 2u, 2u, ref phNewToken))
				{
					throw new SecurityException(((System.Exception)(object)new Win32Exception()).Message);
				}
				if (!global::Interop.mincore.CheckTokenMembership(((int)impersonationLevel != 0) ? _safeTokenHandle : phNewToken, sid.BinaryForm, ref IsMember))
				{
					throw new SecurityException(((System.Exception)(object)new Win32Exception()).Message);
				}
				return IsMember;
			}
			finally
			{
				if (phNewToken != SafeAccessTokenHandle.InvalidHandle)
				{
					((SafeHandle)phNewToken).Dispose();
				}
			}
		}

		internal string GetName()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			if (((SafeHandle)_safeTokenHandle).IsInvalid)
			{
				return string.Empty;
			}
			if (_name == null)
			{
				RunImpersonated(SafeAccessTokenHandle.InvalidHandle, (Action)([CompilerGenerated] () =>
				{
					NTAccount nTAccount = User.Translate(typeof(NTAccount)) as NTAccount;
					_name = ((object)nTAccount).ToString();
				}));
			}
			return _name;
		}

		public static void RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (action == null)
			{
				throw new ArgumentNullException("action");
			}
			RunImpersonatedInternal(safeAccessTokenHandle, action);
		}

		public static T RunImpersonated<T>(SafeAccessTokenHandle safeAccessTokenHandle, Func<T> func)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			if (func == null)
			{
				throw new ArgumentNullException("func");
			}
			T result = default(T);
			RunImpersonatedInternal(safeAccess